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.

Easy Python 3.9+ Aug 9, 2026 Caching & Redis 14 views 0 copies

Requires third-party packages — install first
pip install redis

Python code

20 lines
Python 3.9+
import 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

stdout
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

  1. Use `json.dumps` and `json.loads` to automatically serialize and deserialize dictionaries as cached values instead of pre-built JSON strings.
  2. 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

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Caching & Redis

Related tutorials and quizzes for this topic.