How to Cache Data in Redis with Python
Build a simple Redis cache wrapper that stores and retrieves JSON data with automatic TTL and serialization.
pip install redis
Python code
31 linesimport redis
import json
import time
class Cache:
def __init__(self, host="localhost", port=6379, db=0, default_ttl=60):
self.client = redis.Redis(host=host, port=port, db=db)
self.default_ttl = default_ttl
def get(self, key):
value = self.client.get(key)
if value is None:
return None
return json.loads(value)
def set(self, key, value, ttl=None):
ttl = ttl or self.default_ttl
self.client.setex(key, ttl, json.dumps(value))
def delete(self, key):
self.client.delete(key)
if __name__ == "__main__":
cache = Cache()
cache.set("user:42", {"name": "Alice", "age": 30})
data = cache.get("user:42")
print(f"Cached data: {data}")
cache.delete("user:42")
print(f"After delete: {cache.get('user:42')}")
Output
Cached data: {'name': 'Alice', 'age': 30}
After delete: None
How it works
The Cache class wraps a redis.Redis client. set uses setex to store the JSON-serialized value with a time-to-live (TTL), so the key expires automatically after the given seconds. get retrieves the raw bytes from Redis and decodes them with json.loads to return a native Python object. When the key is missing, get returns None instead of raising an error. The delete method removes the key entirely, which is why the second print shows None.
Common mistakes
- Forgetting that Redis returns bytes, so you must decode or use json.loads directly
- Not setting a TTL, leading to stale data or memory leaks
- Using `client.set` instead of `setex` and handling expiry manually
Variations
- Use `redis-py-cluster` for Redis Cluster support
- Use `pickle` instead of JSON for complex objects, but beware security risks
Real-world use cases
- Caching API responses to reduce load on slow upstream services.
- Storing user session data temporarily to speed up authentication checks.
- Memoizing database query results to serve frequently requested data faster.
Sponsored
More from Caching & Redis
- Cache Asides in Python with a Read-Through Loader easy
- Cache Data in Redis with Python easy
- Cache Penetration Null Object Mock in Python medium
- Cache Stampede Prevention with SingleFlight in Python medium
- Cache Warming with Python: Preload Hot Keys easy
- Coalescing duplicate in-flight requests: one shared result for concurrent callers hard
Keep learning
Related tutorials and quizzes for this topic.