Introduction
redis-py is the official Python client for Redis, maintained by Redis Ltd. It provides both synchronous and async interfaces, automatic connection pooling, and support for all Redis data structures, modules, and topologies. With over 200 million monthly downloads from PyPI, it is the standard way Python applications interact with Redis.
What redis-py Does
- Connects to standalone Redis, Sentinel, and Cluster deployments
- Executes all Redis commands with Pythonic method names
- Manages a connection pool that reuses TCP connections across requests
- Supports Pub/Sub, streams, transactions, pipelines, and Lua scripting
- Provides async support via
redis.asynciofor asyncio-based applications
Architecture Overview
redis-py maintains a connection pool per client instance. Each command call checks out a connection, sends the RESP-encoded command, reads the response, and returns the connection to the pool. Pipelines batch multiple commands into a single network write for throughput. The async client uses the same architecture but with non-blocking I/O via asyncio. Connection pooling, retry logic, and health checks are configurable.
Setup & Configuration
- Install via
pip install redisorpip install redis[hiredis]for the C parser (2-10x faster parsing) - Create a client with
redis.Redis(host, port, db, decode_responses=True) - Use
redis.ConnectionPoolfor explicit pool sizing and timeout control - For Sentinel, use
redis.Sentinel(sentinels).master_for('mymaster')to connect to the primary - For Cluster, use
redis.RedisCluster(host, port)for automatic slot routing
Key Features
- Automatic connection pooling with configurable pool size and timeouts
- Async API via
redis.asynciofor non-blocking I/O - Hiredis C parser integration for high-throughput parsing
- Pipeline and transaction support for batched operations
- Built-in support for Redis Cluster, Sentinel, and module commands
Comparison with Similar Tools
- node-redis — official Node.js client, redis-py serves the same role for Python
- ioredis — feature-rich Node.js client, redis-py is the Python equivalent
- aioredis — was the async Python client, now merged into redis-py's
redis.asyncio - Jedis — synchronous Java client, redis-py provides both sync and async interfaces
FAQ
Q: Should I install hiredis?
A: Yes. pip install redis[hiredis] installs the C-based parser, which is 2-10x faster for response parsing. It is a drop-in optimization.
Q: How do I use redis-py with async frameworks like FastAPI?
A: Use redis.asyncio.Redis and await each command. Share a single client instance across requests for connection pooling.
Q: Does redis-py support Redis Streams?
A: Yes. Use r.xadd(), r.xread(), r.xreadgroup(), and related methods for stream operations.
Q: How do I handle connection failures?
A: Configure retry_on_timeout=True and set socket_connect_timeout and socket_timeout for resilience. The connection pool automatically replaces dead connections.