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.

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

Requires third-party packages — install first
pip install redis

Python code

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

stdout
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

  1. Use `redis-py-cluster` for Redis Cluster support
  2. 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

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.