IC Improve Code Recipes

Recipe 3.5 · Python

Distributed Caching with IDistributedCache and Redis

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

The application now runs on four servers behind a load balancer. Each has its own in-memory cache, so each loads the same data, invalidation on one server does not reach the others, and a user can see a new value on one request and the old value on the next. Some data also needs to survive an application restart, such as an expensive report result.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

BinaryFormatter is a remote-code-execution risk when it reads data it did not write, it is obsolete, and starting with .NET 9 it throws on every call. Code like this also tends to connect to Redis directly in every class, with no expiration and no plan for what happens when Redis is down.

Requirements: Python 3.12+. Install: pip install redis · Needs at run time: a Redis server. The module loads without them; calling the code does not work without them.

Python Binary serialization into a shared Redis store (p070_r3_5_binary_serialized_redis_before.py)
"""Binary serialization into a shared Redis store

Source: ImproveCode, Chapter 3, Recipe 3.5 "Distributed Caching with IDistributedCache and Redis"
Section: The way it's often written
Book page: 70-71  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
BinaryFormatter -> pickle (same problems: unsafe to load, brittle across versions);
StackExchange.Redis StringSet -> redis-py set() with no expiry.
"""

import io
import pickle
from typing import Any

import redis


def cache_report(r: redis.Redis, id: int, report: Any) -> None:
    # Not to copy: binary serialization into a shared store.
    with io.BytesIO() as ms:
        pickle.dump(report, ms)
        r.set("Report_" + str(id), ms.getvalue())

The improved recipe

Requirements: Python 3.12+. Install: pip install pydantic redis · Needs at run time: a Redis server. The module loads without them; calling the code does not work without them.

Python JSON distributed cache over Redis with a memory fallback (p071_r3_5_json_distributed_cache_redis.py)
"""JSON distributed cache over Redis with a memory fallback

Source: ImproveCode, Chapter 3, Recipe 3.5 "Distributed Caching with IDistributedCache and Redis"
Section: The improved recipe
Book page: 71-72  -- original C# listing
Converted from C# to Python.
IDistributedCache -> a DistributedCache Protocol with redis.asyncio and in-memory implementations;
System.Text.Json -> pydantic TypeAdapter (callers pass the type, as Python generics are erased);
ILogger -> logging; cache failures are logged and swallowed, cancellation is not.
"""

import asyncio
import logging
import time
from collections.abc import Awaitable, Callable
from datetime import timedelta
from typing import Protocol

import redis.asyncio as redis
from pydantic import TypeAdapter


class DistributedCache(Protocol):
    async def get(self, key: str) -> bytes | None: ...
    async def set(self, key: str, value: bytes, ttl: timedelta) -> None: ...
    async def remove(self, key: str) -> None: ...


class RedisDistributedCache:
    def __init__(self, configuration: str, instance_name: str) -> None:
        self._redis = redis.from_url(configuration)
        self._prefix = instance_name

    async def get(self, key: str) -> bytes | None:
        return await self._redis.get(self._prefix + key)

    async def set(self, key: str, value: bytes, ttl: timedelta) -> None:
        await self._redis.set(self._prefix + key, value, px=ttl)

    async def remove(self, key: str) -> None:
        await self._redis.delete(self._prefix + key)


class MemoryDistributedCache:
    """AddDistributedMemoryCache equivalent: per-process, for dev and single server."""

    def __init__(self) -> None:
        self._items: dict[str, tuple[bytes, float]] = {}

    async def get(self, key: str) -> bytes | None:
        item = self._items.get(key)
        if item is None or item[1] <= time.monotonic():
            self._items.pop(key, None)
            return None
        return item[0]

    async def set(self, key: str, value: bytes, ttl: timedelta) -> None:
        self._items[key] = (value, time.monotonic() + ttl.total_seconds())

    async def remove(self, key: str) -> None:
        self._items.pop(key, None)


class JsonDistributedCache:
    def __init__(self, cache: DistributedCache, logger: logging.Logger) -> None:
        self._cache = cache
        self._logger = logger

    async def get_or_create[T](self, key: str, type_: type[T],
                               factory: Callable[[], Awaitable[T]],
                               time_to_live: timedelta) -> T:
        adapter = TypeAdapter(type_)
        data: bytes | None = None
        try:
            data = await self._cache.get(key)
        except asyncio.CancelledError:
            raise
        except Exception:
            self._logger.warning("Cache read failed for %s", key, exc_info=True)

        if data is not None:
            return adapter.validate_json(data)

        value = await factory()

        try:
            await self._cache.set(key, adapter.dump_json(value), time_to_live)
        except asyncio.CancelledError:
            raise
        except Exception:
            self._logger.warning("Cache write failed for %s", key, exc_info=True)

        return value

    async def remove(self, key: str) -> None:
        await self._cache.remove(key)


def add_app_distributed_cache(redis_connection: str | None) -> JsonDistributedCache:
    cache: DistributedCache
    if not redis_connection or not redis_connection.strip():
        # Development and single-server fallback.
        cache = MemoryDistributedCache()
    else:
        cache = RedisDistributedCache(redis_connection, instance_name="appdb:")

    return JsonDistributedCache(cache, logging.getLogger(JsonDistributedCache.__name__))

How it works

IDistributedCache is a small interface for storing byte arrays by string key, with expiration. The application codes against the interface, and the registration picks the store: Redis through AddStackExchangeRedisCache, or an in-process implementation through AddDistributedMemoryCache for development. SQL Server is a third option, through the Microsoft.Extensions.Caching.SqlServer package.

JsonDistributedCache adds the two things the raw interface lacks: typed values and resilience. Values are serialized with System.Text.Json into UTF-8 bytes, which is safe, fast and readable when you inspect Redis by hand. Read and write failures are logged and treated as misses, so when Redis restarts, the application gets slower for a minute instead of failing every request. A cache should never be a single point of failure for data that lives in the database anyway.

InstanceName prefixes every key, so several applications can share one Redis server without colliding.

Wire it up in Program.cs:

Requirements: Python 3.12+. Install: pip install fastapi

Python Register the distributed cache at startup from the Redis connection string (p073_r3_5_register_distributed_cache_startup.py)
"""Register the distributed cache at startup from the Redis connection string

Source: ImproveCode, Chapter 3, Recipe 3.5 "Distributed Caching with IDistributedCache and Redis"
Section: How it works
Book page: 73  -- original C# listing
Converted from C# to Python.
builder.Services registration -> FastAPI app.state; GetConnectionString("Redis") -> os.environ.
"""

import os

from fastapi import FastAPI

from p071_r3_5_json_distributed_cache_redis import add_app_distributed_cache


def configure(app: FastAPI) -> None:
    # Usage snippet
    app.state.json_cache = add_app_distributed_cache(
        os.environ.get("CONNECTIONSTRINGS__REDIS"))

Variations and pitfalls

  • Every read is a network call. A Redis read takes about a millisecond, which is far faster than a database query and far slower than memory. For data read many times per request, put a short in-memory level in front. That two-level design is exactly what HybridCache provides.
  • Version your keys. When the shape of a cached type changes, old JSON may not deserialize into the new type. Put a version in the key (report:v2:42) and bump it with the change.
  • Mind the size. Large values slow down every server that reads them. Cache the summary, not the 50,000-row result.
  • Sliding expiration costs a write. In Redis, every sliding-expiration read also refreshes the key's lifetime. Prefer absolute expiration unless you need sliding.
  • Sensitive data. Redis is often less protected than the database. Do not cache personal data, tokens or anything secret unless the Redis server is secured with TLS and authentication and the data is needed there.
  • Stampedes again. This class does not deduplicate loads. Combine it with the in-flight logic from Recipe 3.4, or use HybridCache.