Cache Data in Redis with Python
A beginner-friendly Redis cache helper that stores JSON strings with a TTL and retrieves them with the redis-py client.
pip install redis
Python code
20 linesimport redis
class DataCache:
def __init__(self, host="localhost", port=6379, db=0):
self.client = redis.Redis(host=host, port=port, db=db, decode_responses=True)
def cache_data(self, key, value, ttl=60):
self.client.setex(key, ttl, value)
def get_cached_data(self, key):
return self.client.get(key)
if __name__ == "__main__":
cache = DataCache()
cache.cache_data("user:1", '{"name": "Alice", "age": 30}', ttl=30)
data = cache.get_cached_data("user:1")
print(f"Cached data: {data}")
print(f"Cache TTL remaining: {cache.client.ttl('user:1')} seconds")
Output
Cached data: {"name": "Alice", "age": 30}
Cache TTL remaining: 29 seconds
How it works
The DataCache class wraps a redis.Redis client, enabling setex to store a key with an expiry time and get to fetch the value. With decode_responses=True, keys and values are returned as strings instead of bytes, making the data easier to work with in Python. The ttl method reports the remaining lifetime of the key in seconds, confirming that the expiry mechanism is working as expected. This pattern gives you a clean, reusable interface for caching simple data structures like JSON strings without repeating client setup code.
Common mistakes
- Forgetting to start the Redis server before running the script, which causes a connection error.
- Storing non-string values (like ints or dicts) without serializing them to JSON or another string format first.
- Assuming data persists beyond the TTL — Redis deletes the key automatically after expiration.
Variations
- Use `json.dumps` and `json.loads` to automatically serialize and deserialize dictionaries as cached values instead of pre-built JSON strings.
- Add a `delete` method and connection pooling for production-scale applications with high request volumes.
Real-world use cases
- Caching user profile responses in a web API to reduce database load on frequent requests.
- Storing session tokens with short TTLs to enforce automatic logout after inactivity periods.
- Buffering rate-limited data like survey responses to batch-process them before a scheduled job.
Sponsored
More from Caching & Redis
- Cache Asides in Python with a Read-Through Loader 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
- Consistent Hashing Cache Shard in Python medium
Keep learning
Related tutorials and quizzes for this topic.