StackPractices
intermediate By Mathias Paulenko

Cache Function Results with Redis and TTL in Python

Build a Python decorator that caches function return values in Redis with configurable TTL, key generation, and cache invalidation

Caching expensive function results in Redis cuts latency and database load, and a decorator wraps that in a single @cached line so the business logic stays readable. Underneath, this is the cache-aside pattern: check the cache, fall back to the real function on a miss, store the result for next time. This recipe builds the decorator with deterministic key generation, JSON serialization, configurable TTL, and per-call invalidation.

When to Use This

  • Pure or near-pure functions: same arguments in, same result out
  • Database queries, API calls, or heavy computations that are expensive but change rarely
  • Results that can be served slightly stale for the TTL duration
  • Multi-process or multi-server apps where functools.lru_cache can’t share state
  • Read-heavy endpoints where the same hot arguments repeat constantly

Skip this approach when the function has side effects (writes, emails, charges), when results must always be fresh (stock levels, balances), or when every call has unique arguments — a cache that never hits just adds Redis round-trips.

Prerequisites

  • Python 3.10+
  • redis package (pip install redis)
  • A running Redis instance

Solution

1. Install Dependencies

pip install redis

2. Build the Cache Decorator

import functools
import hashlib
import json
import logging
from typing import Any, Callable, TypeVar
from redis import Redis

logger = logging.getLogger(__name__)
T = TypeVar("T")


def cached(
    redis_client: Redis,
    ttl: int = 300,
    prefix: str = "cache",
    skip_args: tuple[str, ...] = (),
) -> Callable:
    """Cache function results in Redis with a TTL.

    Args:
        redis_client: Redis client instance.
        ttl: Time-to-live in seconds.
        prefix: Cache key prefix.
        skip_args: Argument names to exclude from the cache key.

    Returns:
        Decorator that wraps the function with Redis caching.
    """

    def decorator(func: Callable[..., T]) -> Callable[..., T]:
        @functools.wraps(func)
        def wrapper(*args, **kwargs) -> T:
            key = _make_key(func, args, kwargs, prefix, skip_args)

            try:
                cached_value = redis_client.get(key)
                if cached_value is not None:
                    return json.loads(cached_value)
            except (json.JSONDecodeError, ConnectionError) as e:
                logger.warning("Cache read failed for %s: %s", key, e)

            result = func(*args, **kwargs)

            try:
                redis_client.setex(key, ttl, json.dumps(result, default=str))
            except (TypeError, ConnectionError) as e:
                logger.warning("Cache write failed for %s: %s", key, e)

            return result

        wrapper.cache_invalidate = _make_invalidator(  # type: ignore[attr-defined]
            redis_client, func, prefix, skip_args
        )
        return wrapper

    return decorator


def _make_key(
    func: Callable,
    args: tuple,
    kwargs: dict,
    prefix: str,
    skip_args: tuple[str, ...],
) -> str:
    """Generate a deterministic cache key from function name and arguments."""
    import inspect

    sig = inspect.signature(func)
    bound = sig.bind(*args, **kwargs)
    bound.apply_defaults()

    filtered = {
        k: v for k, v in bound.arguments.items()
        if k not in skip_args and k != "self"
    }

    arg_hash = hashlib.sha256(
        json.dumps(filtered, sort_keys=True, default=str).encode()
    ).hexdigest()[:16]

    return f"{prefix}:{func.__module__}:{func.__name__}:{arg_hash}"


def _make_invalidator(
    redis_client: Redis,
    func: Callable,
    prefix: str,
    skip_args: tuple[str, ...],
) -> Callable:
    """Create a cache invalidation function for a specific decorated function."""
    def invalidate(*args, **kwargs) -> int:
        key = _make_key(func, args, kwargs, prefix, skip_args)
        return redis_client.delete(key)

    return invalidate

3. Use the Decorator

import redis
from myapp.database import get_user_by_id

r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)

@cached(r, ttl=60, prefix="user")
def get_user(user_id: str, include_posts: bool = False) -> dict:
    user = get_user_by_id(user_id)
    if include_posts:
        user["posts"] = fetch_user_posts(user_id)
    return user

# First call — hits the database, caches result
user = get_user("123", include_posts=True)

# Second call — returns from cache
user = get_user("123", include_posts=True)

# Invalidate the cache for specific arguments
get_user.cache_invalidate("123", include_posts=True)

4. Async Version

import asyncio
from redis.asyncio import Redis as AsyncRedis

def async_cached(
    redis_client: AsyncRedis,
    ttl: int = 300,
    prefix: str = "cache",
) -> Callable:
    def decorator(func: Callable) -> Callable:
        @functools.wraps(func)
        async def wrapper(*args, **kwargs):
            key = _make_key(func, args, kwargs, prefix, ())

            try:
                cached = await redis_client.get(key)
                if cached is not None:
                    return json.loads(cached)
            except Exception as e:
                logger.warning("Async cache read failed: %s", e)

            result = await func(*args, **kwargs)

            try:
                await redis_client.setex(key, ttl, json.dumps(result, default=str))
            except Exception as e:
                logger.warning("Async cache write failed: %s", e)

            return result

        return wrapper
    return decorator

# Usage
r = AsyncRedis(host="localhost", port=6379, decode_responses=True)

@async_cached(r, ttl=120, prefix="api")
async def fetch_weather(city: str) -> dict:
    async with httpx.AsyncClient() as client:
        resp = await client.get(f"https://api.weather.example/{city}")
        return resp.json()

A runnable version with a hit/miss/invalidation smoke test lives in the companion repo.

How It Works

flowchart diagram: Call func
  1. Key generation hashes the function’s module, name, and normalized arguments. inspect.signature + sig.bind is the important part: calling get_user("123", include_posts=True) and get_user(user_id="123", include_posts=True) produce the same key, because bind maps positional args onto parameter names before hashing.
  2. skip_args drops arguments like self or a request object from the key. Without it, id(self) changes between calls and every lookup misses.
  3. setex writes the value and the expiration in one atomic command — no window where a key exists without a TTL.
  4. cache_invalidate hangs off the wrapper, so callers delete one specific entry by passing the same arguments they’d pass to the function.
  5. Graceful degradation: when Redis is down, get/setex raise ConnectionError, the decorator logs it, and the real function still runs. The cache is an optimization, never a source of truth.
  6. Serialization is the quiet limit: json.dumps handles dicts, lists, and primitives. Return a dataclass or datetime and you either write a default serializer or switch to pickle — faster and more flexible, but it unpickles whatever Redis hands back, so only use it on a store you control.

Stick with JSON unless the return type actually needs it: pickle and msgpack earn their complexity only with exotic types or multi-KB payloads.

Variants

Cache-Aside with Manual Refresh

@cached(r, ttl=300, prefix="product")
def get_product(product_id: str) -> dict:
    return db.products.find_by_id(product_id)

def refresh_product(product_id: str) -> dict:
    get_product.cache_invalidate(product_id)
    return get_product(product_id)

Tag-Based Invalidation

Invalidate all cache entries for a tag (e.g., every user-related key):

def invalidate_tag(redis_client: Redis, tag: str) -> int:
    keys = redis_client.smembers(f"tag:{tag}")
    if keys:
        redis_client.delete(*keys)
        redis_client.delete(f"tag:{tag}")
    return len(keys)

# When caching, add key to a tag set
redis_client.sadd("tag:users", key)

Tags work better than SCAN-ing for a key pattern — KEYS and SCAN patterns get slow on large keyspaces, while a set lookup is O(1) plus the deletes.

Compression for Large Values

import zlib

@cached(r, ttl=600, prefix="report")
def generate_report(date: str) -> dict:
    data = heavy_computation(date)
    return data  # Could be large

# In the decorator, compress before storing:
redis_client.setex(key, ttl, zlib.compress(json.dumps(result).encode()))

Best Practices

  • Short TTLs for data that moves — 30-60 seconds for user feeds, 5-10 minutes for reference data. When unsure, go shorter: a stale read usually costs more than a cache miss.
  • Cache serializable results only — json.dumps needs a default serializer for custom types, or the write silently fails and you get permanent misses.
  • Invalidate on writes — call cache_invalidate right after any mutation that would change the result.
  • Add jitter to TTLs on hot keys — if many entries expire at the same second, they all recompute together. ttl + random.randint(0, 30) spreads the load.
  • For the bigger picture — eviction policies, multi-level caches, stampede protection — see the complete Redis caching strategies guide.

Common Mistakes

  • Caching functions with side effects — a cache hit skips the function body entirely, including any writes it does.
  • Forgetting self in the key on methods — id(self) changes between calls, so every lookup misses. That’s what skip_args is for.
  • Renaming the function and wondering why hit rate collapsed — the key contains func.__module__ and func.__name__; a rename or move mints fresh keys and the old entries sit there until their TTL.
  • Treating a None return as a miss — get returns None both for “key absent” and “cached None”. If the function legitimately returns None, check exists(key) or store a sentinel.
  • Cold-start thundering herd — after a flush or deploy, every request computes at once. For genuinely hot keys, add a short lock or request coalescing instead of relying on the decorator alone.
  • Caching mutable default arguments — mutate a default list or dict between calls and the key hash changes underneath you.

Further Reading

Frequently Asked Questions

Should I use Redis or in-memory caching?

Redis when several processes or servers share the cache — that's the whole point of an external store. For a single-process, short-lived cache, functools.lru_cache is faster and has nothing to deploy.

How do I handle non-serializable return values?

Give json.dumps a default function that converts custom types to dicts. If the types are too exotic, switch the store to pickle — but only against a Redis you control, since unpickling runs arbitrary code.

What TTL should I use?

Start at 300 seconds and tune from there. Ask how stale the data can get before a user notices, then halve it. Hot keys benefit from TTL jitter so they don't all expire in the same second.

Can I cache functions that return None?

Yes, but get returning None is ambiguous — it means both "miss" and "cached None". Check exists(key) or store a sentinel value like "__none__" if your functions return None often.

What happens when Redis goes down?

The decorator catches ConnectionError, logs a warning, and calls the real function — so Redis down means "no cache", not "site down". Watch your logs though: a silent Redis outage shows up as a database load spike, not an error page.

How do I invalidate a whole prefix, not just one call?

cache_invalidate deletes one argument combination. For a whole prefix, either track keys in a tag set (see Variants) or use a versioned prefix — bump prefix="user" to prefix="user:v2" on deploy and let the old entries expire on their own.