Redis
suggest changeRedis is an in-memory data store. It keeps all data in RAM, so reads and writes take well under a millisecond, and it optionally saves data to disk. Values aren't just strings: Redis has hashes, lists, sets, sorted sets and streams, each with atomic server-side commands.
Typical uses from Python:
- a cache in front of a slow database or API
- session storage and counters
- job queues and message passing between processes
- rate limiting and distributed locks
- leaderboards and other ranked data
The official Python client is redis (often called redis-py). It has a synchronous API and an asyncio API (redis.asyncio).
All examples were run with Python 3.13, redis-py 8.1 and Redis server 8.10.
Installation
Install the client:
pip install redis
You also need a running Redis server. The easiest way is Docker:
docker run -d --name redis -p 6379:6379 redis:8
On Linux you can also install the redis-server package, and on macOS use brew install redis.
Connecting
import redis
r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)
print(r.ping())
r.set("greeting", "hello")
print(r.get("greeting"))
print(r.get("missing"))
raw = redis.Redis(host="localhost", port=6379)
print(raw.get("greeting"))
True
hello
None
b'hello'
Things to know:
- Redis stores bytes. By default redis-py returns
bytes. Passdecode_responses=Trueto getstrback, which is what you want most of the time. Use the default only when you store binary data like images or pickled objects. - A missing key returns
None, not an exception. Redis()doesn't connect right away. It creates a connection pool and opens connections on the first command.- A
Redisobject is thread-safe. Create one at startup and share it, don't create a new one per request.
You can also connect with a URL, which is convenient for configuration in environment variables:
r = redis.Redis.from_url("redis://:password@localhost:6379/0", decode_responses=True)
Use rediss:// (two s) for TLS connections, which most hosted Redis services require.
Strings, expiry and counters
The basic type is a string value under a string key. By convention keys are namespaced with colons, like user:42:name.
import time
import redis
r = redis.Redis(decode_responses=True)
# set with expiry
r.set("session:abc", "user42", ex=2)
print("ttl:", r.ttl("session:abc"))
time.sleep(2.1)
print("after expiry:", r.get("session:abc"))
# only set if the key doesn't exist
print(r.set("lock:report", "worker-1", nx=True))
print(r.set("lock:report", "worker-2", nx=True))
print(r.get("lock:report"))
# counters are atomic
r.set("visits", 0)
r.incr("visits")
r.incrby("visits", 10)
print("visits:", r.get("visits"), type(r.get("visits")))
print(r.incrbyfloat("price", 9.99))
# many keys at once
r.mset({"user:1:name": "Alice", "user:2:name": "Bob"})
print(r.mget("user:1:name", "user:2:name", "user:3:name"))
print(r.exists("user:1:name", "user:3:name"))
print(r.delete("user:1:name", "user:2:name"))
ttl: 2
after expiry: None
True
None
worker-1
visits: 11 <class 'str'>
9.99
['Alice', 'Bob', None]
1
2
ex=sets expiry in seconds (px=in milliseconds). Redis deletes the key automatically, which is what makes it a good cache and session store.expire()adds a timeout to an existing key andttl()returns the remaining seconds (-1means no expiry,-2means the key doesn't exist).nx=Truesets the key only if it doesn't exist and returnsNoneotherwise.xx=Truedoes the opposite.incr()is atomic on the server. Ten processes incrementing the same key never lose an update, unlike a read-modify-write in Python (see Race conditions).- Numbers come back as strings.
get("visits")returns'11', so convert withint()yourself. exists()anddelete()return how many of the given keys existed or were deleted.
Hashes
A hash is a small dictionary stored under one key. It's a natural fit for objects with fields:
import redis
r = redis.Redis(decode_responses=True)
r.hset("user:1", mapping={"name": "Alice", "email": "alice@example.com", "logins": 0})
r.hincrby("user:1", "logins", 1)
print(r.hget("user:1", "name"))
print(r.hgetall("user:1"))
print(r.hmget("user:1", ["name", "age"]))
print(r.hexists("user:1", "email"))
r.hdel("user:1", "email")
print(r.hkeys("user:1"))
print(r.hgetall("no-such-user"))
Alice
{'name': 'Alice', 'email': 'alice@example.com', 'logins': '1'}
['Alice', None]
True
['name', 'logins']
{}
Hash values are flat strings: you can't nest a dict or list inside a hash field. hgetall() on a missing key returns an empty dict.
Lists
A list is a linked list of strings. Push and pop at either end are fast, which makes lists a simple queue:
import redis
r = redis.Redis(decode_responses=True)
# a queue: push on the left, pop on the right
r.lpush("jobs", "job1", "job2", "job3")
print(r.lrange("jobs", 0, -1))
print(r.rpop("jobs"))
print(r.llen("jobs"))
# keep only the 3 most recent events
for i in range(6):
r.lpush("recent", f"event{i}")
r.ltrim("recent", 0, 2)
print(r.lrange("recent", 0, -1))
# blocking pop: wait up to 1 second for an item
print(r.brpop("jobs", timeout=1))
print(r.brpop("jobs", timeout=1))
print(r.brpop("jobs", timeout=1))
['job3', 'job2', 'job1']
job1
2
['event5', 'event4', 'event3']
('jobs', 'job2')
('jobs', 'job3')
None
brpop() blocks until an item arrives or the timeout passes, so a worker can wait for jobs without polling. It returns a (key, value) tuple because it can wait on several lists at once. timeout=0 waits forever.
Sets and sorted sets
A set holds unique strings. Set operations run on the server:
import redis
r = redis.Redis(decode_responses=True)
r.sadd("tags:post1", "python", "redis", "database")
r.sadd("tags:post2", "python", "web")
print(sorted(r.smembers("tags:post1")))
print(r.sismember("tags:post1", "redis"))
print(r.sadd("tags:post1", "python")) # already there
print(r.sinter("tags:post1", "tags:post2"))
print(sorted(r.sunion("tags:post1", "tags:post2")))
print(r.scard("tags:post1"))
['database', 'python', 'redis']
1
0
{'python'}
['database', 'python', 'redis', 'web']
3
smembers() returns a Python set, so the order is random. sadd() returns the number of members actually added.
A sorted set gives every member a score and keeps members ordered by it. It's the classic structure for leaderboards:
import redis
r = redis.Redis(decode_responses=True)
r.zadd("leaderboard", {"alice": 120, "bob": 95, "carol": 150})
r.zincrby("leaderboard", 40, "bob")
# top 3, highest score first
print(r.zrange("leaderboard", 0, 2, desc=True, withscores=True))
print(r.zscore("leaderboard", "bob"))
print(r.zrevrank("leaderboard", "alice")) # 0-based position from the top
print(r.zrangebyscore("leaderboard", 100, 140))
print(r.zcount("leaderboard", "-inf", "+inf"))
[('carol', 150.0), ('bob', 135.0), ('alice', 120.0)]
135.0
2
['alice', 'bob']
3
Scores are floats. Adding, updating and looking up the rank of a member are all O(log n), even with millions of members.
Storing Python objects
redis-py only accepts str, bytes, int and float values. To store a dict or list, serialize it, usually with JSON:
import json
import redis
r = redis.Redis(decode_responses=True)
order = {"id": 1001, "items": [{"sku": "A1", "qty": 2}], "paid": False}
r.set("order:1001", json.dumps(order), ex=3600)
loaded = json.loads(r.get("order:1001"))
print(loaded["items"][0]["qty"], loaded["paid"])
try:
r.set("order:1002", order)
except redis.DataError as e:
print("DataError:", e)
2 False
DataError: Invalid input of type: 'dict'. Convert to a bytes, string, int or float first.
Use a hash instead of JSON when you need to read or update single fields without fetching the whole object. Avoid pickle for data that other programs or untrusted parties can write: unpickling can execute arbitrary code.
Pipelines
Every command is a network round trip. A pipeline buffers many commands and sends them in one go:
import time
import redis
r = redis.Redis(decode_responses=True)
start = time.perf_counter()
for i in range(10_000):
r.set(f"k:{i}", i)
print(f"one by one: {time.perf_counter() - start:.2f}s")
start = time.perf_counter()
with r.pipeline(transaction=False) as pipe:
for i in range(10_000):
pipe.set(f"k:{i}", i)
pipe.execute()
print(f"pipeline: {time.perf_counter() - start:.2f}s")
with r.pipeline() as pipe:
pipe.incr("counter").incr("counter").get("counter")
print(pipe.execute())
one by one: 2.09s
pipeline: 0.11s
[1, 2, '2']
That's 20 times faster against a server on the same machine; over a real network the difference is bigger. Commands on a pipeline return the pipeline itself, so they can be chained, and execute() returns a list with one result per command.
By default pipeline() wraps the commands in MULTI/EXEC, so they run as one atomic transaction: no other client's command runs in between. Pass transaction=False when you only want the speed.
Transactions with WATCH
A transaction alone can't make a decision based on a value it reads, because commands in it are only queued. For check-then-act logic, use WATCH: if a watched key changes before EXEC, the transaction is aborted with WatchError and you retry. This is optimistic locking:
import redis
r = redis.Redis(decode_responses=True)
r.set("balance:alice", 100)
def withdraw(account, amount):
key = f"balance:{account}"
with r.pipeline() as pipe:
while True:
try:
pipe.watch(key) # start watching, back in immediate mode
balance = int(pipe.get(key))
if balance < amount:
pipe.unwatch()
return False
pipe.multi() # start buffering the transaction
pipe.set(key, balance - amount)
pipe.execute() # fails if key changed since watch()
return True
except redis.WatchError:
continue # someone else changed it, retry
print(withdraw("alice", 30), r.get("balance:alice"))
print(withdraw("alice", 100), r.get("balance:alice"))
# the same thing with the transaction() helper
def take(pipe):
balance = int(pipe.get("balance:alice"))
pipe.multi()
pipe.set("balance:alice", balance - 20)
r.transaction(take, "balance:alice")
print(r.get("balance:alice"))
True 70
False 70
50
r.transaction(func, *keys) runs the watch/retry loop for you and calls func with the pipeline.
Caching function results
The most common use of Redis is cache-aside: look in Redis first, and on a miss compute the value and store it with an expiry. Unlike functools.lru_cache (see Caching), the cache is shared by all processes and servers and survives restarts of your app.
import functools
import json
import time
import redis
r = redis.Redis(decode_responses=True)
def redis_cache(ttl):
def decorator(func):
@functools.wraps(func)
def wrapper(*args):
key = f"cache:{func.__name__}:{json.dumps(args)}"
cached = r.get(key)
if cached is not None:
return json.loads(cached)
result = func(*args)
r.set(key, json.dumps(result), ex=ttl)
return result
return wrapper
return decorator
@redis_cache(ttl=60)
def get_user_profile(user_id):
time.sleep(1) # pretend this is a slow database query
return {"id": user_id, "name": f"user{user_id}"}
for _ in range(3):
start = time.perf_counter()
profile = get_user_profile(7)
print(profile, f"{time.perf_counter() - start:.3f}s")
print(r.keys("cache:*"))
print(r.ttl('cache:get_user_profile:[7]'))
{'id': 7, 'name': 'user7'} 1.020s
{'id': 7, 'name': 'user7'} 0.000s
{'id': 7, 'name': 'user7'} 0.000s
['cache:get_user_profile:[7]']
60
Always set an expiry on cache keys, and delete the key when the underlying data changes. When Redis is used purely as a cache, configure the server with maxmemory and maxmemory-policy allkeys-lru so it evicts old keys instead of running out of memory.
Iterating over keys
keys() is fine for a quick look, but it scans the whole database in a single command and blocks the server while doing it. In production use scan_iter(), which walks the keyspace in small batches:
import redis
r = redis.Redis(decode_responses=True)
for i in range(1000):
r.set(f"temp:{i}", i, ex=300)
r.set("config:theme", "dark")
count = 0
for key in r.scan_iter(match="temp:*", count=500):
count += 1
print("found", count, "temp keys")
# delete in batches with a pipeline
with r.pipeline(transaction=False) as pipe:
for key in r.scan_iter(match="temp:*", count=500):
pipe.unlink(key)
pipe.execute()
print("keys left:", r.dbsize())
found 1000 temp keys
keys left: 1
count is a hint for how many keys to examine per round trip. unlink() is like delete() but frees memory in a background thread.
Rate limiting
A fixed-window rate limiter is a counter per user per time window, with INCR and EXPIRE in one transaction:
import time
import redis
r = redis.Redis(decode_responses=True)
def allow_request(user_id, limit=3, window=1):
key = f"rate:{user_id}:{int(time.time() // window)}"
with r.pipeline() as pipe:
pipe.incr(key)
pipe.expire(key, window * 2)
count, _ = pipe.execute()
return count <= limit
time.sleep(1 - time.time() % 1) # start at the beginning of a second
print([allow_request("u1") for _ in range(5)])
time.sleep(1)
print([allow_request("u1") for _ in range(2)])
[True, True, True, False, False]
[True, True]
Because the counter lives in Redis, the limit holds across all worker processes and servers.
Distributed locks
threading.Lock only protects threads in one process (see Locks and synchronization). r.lock() gives you a lock that works across processes and machines:
import threading
import time
import redis
r = redis.Redis(decode_responses=True)
r.set("stock", 5)
def buy(name):
# timeout: auto-release after 10s if the holder crashes
# blocking_timeout: give up waiting after 5s
with r.lock("lock:stock", timeout=10, blocking_timeout=5):
stock = int(r.get("stock"))
time.sleep(0.05) # read-modify-write window
if stock > 0:
r.set("stock", stock - 1)
print(f"{name} bought one, {stock - 1} left")
else:
print(f"{name}: sold out")
threads = [threading.Thread(target=buy, args=(f"buyer{i}",)) for i in range(7)]
for t in threads:
t.start()
for t in threads:
t.join()
print("final stock:", r.get("stock"))
buyer0 bought one, 4 left
buyer5 bought one, 3 left
buyer2 bought one, 2 left
buyer6 bought one, 1 left
buyer1 bought one, 0 left
buyer4: sold out
buyer3: sold out
final stock: 0
The order of buyers differs between runs, but the stock never goes negative. Without the lock, several buyers would read the same stock value and oversell.
Always set timeout: if the process holding the lock dies, the key expires and the lock is released. If blocking_timeout passes, LockError is raised. Keep critical sections shorter than timeout, otherwise the lock expires while you still think you hold it. For a single counter like this, decr() or a WATCH transaction is simpler than a lock.
Pub/Sub
Publish/subscribe sends messages to everyone currently subscribed to a channel:
import threading
import time
import redis
r = redis.Redis(decode_responses=True)
def listener():
p = r.pubsub()
p.subscribe("news")
p.psubscribe("alerts:*")
for message in p.listen():
if message["type"] in ("message", "pmessage"):
print(f"[{message['channel']}] {message['data']}")
if message["data"] == "bye":
break
p.close()
t = threading.Thread(target=listener)
t.start()
time.sleep(0.2) # give the subscriber time to subscribe
print("receivers:", r.publish("news", "Redis 8 released"))
r.publish("alerts:disk", "disk 91% full")
r.publish("nobody-listens", "lost")
r.publish("news", "bye")
t.join()
receivers: 1
[news] Redis 8 released
[alerts:disk] disk 91% full
[news] bye
listen() also yields subscribe confirmation messages, which is why the code filters on type. psubscribe() subscribes to a pattern. publish() returns how many subscribers got the message.
Pub/Sub is fire-and-forget: a message published while nobody is subscribed is lost, and a subscriber that disconnects misses everything in the meantime. When messages must not be lost, use streams.
Streams
A stream is an append-only log. Messages stay in it after they are read, and consumer groups track which messages each consumer has processed and acknowledged:
import redis
r = redis.Redis(decode_responses=True)
r.xadd("orders", {"order_id": "1", "total": "19.99"})
r.xadd("orders", {"order_id": "2", "total": "5.00"})
# a consumer group remembers what each consumer has processed
r.xgroup_create("orders", "billing", id="0")
resp = r.xreadgroup("billing", "worker-1", {"orders": ">"}, count=10, block=1000)
for stream, messages in resp:
for msg_id, fields in messages:
print(stream, fields)
r.xack("orders", "billing", msg_id)
print("pending:", r.xpending("orders", "billing")["pending"])
orders {'order_id': '1', 'total': '19.99'}
orders {'order_id': '2', 'total': '5.00'}
pending: 0
">" means "messages never delivered to this group". A message that was read but not acknowledged with xack() stays pending, so it can be re-delivered if the worker crashes. Pass maxlen= to xadd() to cap the length of the stream.
asyncio
redis.asyncio has the same API, with await in front of each command. Use it in asyncio applications such as FastAPI services:
import asyncio
import redis.asyncio as redis
async def main():
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
try:
await r.set("async:greeting", "hi")
print(await r.get("async:greeting"))
# run many commands concurrently over the connection pool
await asyncio.gather(*(r.incr("async:counter") for _ in range(100)))
print(await r.get("async:counter"))
async with r.pipeline() as pipe:
pipe.hset("async:user", mapping={"name": "Ann", "age": 31})
pipe.hgetall("async:user")
print(await pipe.execute())
finally:
await r.aclose()
asyncio.run(main())
hi
100
[2, {'name': 'Ann', 'age': '31'}]
Close the client with await r.aclose() when you're done. In a pipeline the commands are only queued, so you don't await them; you await pipe.execute().
Connection pools, timeouts and retries
Every Redis object has a connection pool. You can create one explicitly to share it or limit its size, and add automatic retries for transient network errors:
import redis
from redis.backoff import ExponentialBackoff
from redis.retry import Retry
pool = redis.ConnectionPool.from_url(
"redis://localhost:6379/0",
decode_responses=True,
max_connections=20,
)
r = redis.Redis(
connection_pool=pool,
retry=Retry(ExponentialBackoff(cap=1, base=0.1), retries=3),
)
print(r.ping())
info = r.info("server")
print(info["redis_version"])
True
8.10.2
By default there are no socket timeouts, so a hung server can block your program forever. Set socket_connect_timeout and socket_timeout and handle the errors:
import redis
r = redis.Redis(host="localhost", port=6390, socket_connect_timeout=5, socket_timeout=5)
try:
r.ping()
except (redis.ConnectionError, redis.TimeoutError) as e:
print(f"{type(e).__name__}: {e}")
r = redis.Redis(decode_responses=True)
r.set("name", "Alice")
try:
r.incr("name")
except redis.ResponseError as e:
print("ResponseError:", e)
try:
r.lpush("name", "x")
except redis.ResponseError as e:
print("ResponseError:", e)
ConnectionError: Error 10061 connecting to localhost:6390. No connection could be made because the target machine actively refused it.
ResponseError: value is not an integer or out of range
ResponseError: WRONGTYPE Operation against a key holding the wrong kind of value
The connection error text comes from the operating system; on Linux it's Error 111 connecting to localhost:6390. Connection refused. ResponseError means the server rejected the command, for example WRONGTYPE when you use a list command on a string key. All of these exceptions inherit from redis.RedisError.
For a relational database pool, see Database connection pooling.
Best practices
- Create one client and reuse it. It's thread-safe and pools connections.
- Use
decode_responses=Trueunless you store binary data. - Namespace keys (
app:user:42) and set an expiry on everything that is a cache or a session. - Use pipelines when sending many commands, and atomic commands (
incr,set(nx=True),WATCH) instead of read-modify-write in Python. - Never call
keys()in production code; usescan_iter(). - Set socket timeouts so a slow or unreachable Redis can't hang your app.
- Remember Redis is memory-bound. Keep values small, and enable persistence (RDB snapshots or AOF) if you can't afford to lose data on restart.