Skip to main content

Recipes

A shared cache does more jobs in a real app than caching. It elects a worker, counts requests, holds sessions and one-time tokens, remembers what was invalidated, and stands in for Redis wherever Redis was only ever there to hold a counter. Each recipe below starts with the moment you’d reach for one, then shows the pattern, then says where it stops working. The examples with output under them run against diskcache-oxide every time these docs are built, and the example app puts most of these recipes together in one FastAPI app, tested.

Setting up your caches

Start here. The recipes after these two assume the app opens its caches and reaches them this way.

Sharing a cache across web workers. The recommended setup: durable caches for data you can rebuild, plain caches for state, where to put the directory, when to open it with gunicorn, uvicorn, FastAPI, Flask, Django and Celery, how to keep a busy cache from slowing requests, and what to do at shutdown.

One typed module for your caches. Wrap the Caches registry in a module with a function per cache, so the app gets autocomplete and type checking instead of string lookups scattered through the code.

Caching

Caching expensive calls. The cache-aside pattern, and memoize, which turns a function into a cached one keyed on its arguments.

Serving stale values while refreshing. Keep a slow page or report available while one worker rebuilds it in the background, or refresh the hot keys ahead of time from a job, so readers never wait and the thundering herd is one worker.

Caching responses from other services. Cache an upstream API’s answers, honor its max-age, revalidate with ETags, and keep serving the last good answer when it’s down.

Invalidating groups of keys. Clear everything cached for one user, one product or one page at once: delete by key prefix, drop every entry with a tag using evict(tag), or bump a generation number so stale entries are never read again.

Storing your own types. UUIDs, enums, timedeltas, Paths, dataclasses and Pydantic models in the cache with one registration each, and no pickle.

Coordinating workers

For locks, semaphores and a throttle that hold across every process, see the Coordination guide page. The recipes here build on the same atomic calls.

Running a job once across workers. Eight gunicorn workers each schedule the same hourly job, and you want it to run once. add() is atomic across processes, so exactly one of them claims it.

Rate limiting. Count requests per client in fixed time windows with add() and incr(), shared by every worker on the machine, with no Redis.

Counting things. View counts, download totals and usage quotas with incr() and decr(), flushed to the database with pop() so no count is lost or doubled.

Work queues. A queue every worker on the machine shares: push() at one end, pull() from the other, each item delivered to exactly one worker.

Single-use keys. Reset links, verification codes and idempotency keys: pop() hands a value to exactly one caller, and add() accepts a key exactly once.

State

Server-side sessions. Sessions every worker can read, with a sliding idle timeout from touch(), an absolute lifetime, and log-out-everywhere by key prefix.

Async code

Using the cache from asyncio. Read inline, write off the loop, and keep transactions on one thread, in FastAPI, Starlette or aiohttp.

Deployment and testing

Docker and Compose. One named volume for the caches and state, a fixed non-root user, the ownership rules that otherwise end in PermissionError, Kubernetes volumes, disk sizing, and the cleanup step after a format change.

Watching a cache in production. A health check and an admin endpoint: entries, bytes on disk, hit ratio across workers, the size limit, the write-ahead log, check() for damage, and the log lines worth alerting on.

Upgrading across a format change. When a release changes the on-disk format: the new release opens its own cache in a versioned subdirectory, old and new workers run side by side, remove_old_formats() cleans up afterwards, and what to do first about queues, counters and sessions.

Testing code that uses a cache. pytest fixtures for a real cache in a temporary directory, a NullCache for tests that shouldn’t cache at all, and a fake clock for testing expiry without sleeping.

In the user guide

Some features have more to them than a recipe can hold, so they have guide pages of their own: Coordination (locks, semaphores, throttle, barrier, Averager and memoize_stampede, which refreshes a hot value before it expires), FanoutCache for a cache many writers share, and Transactions. What’s coming next is on the roadmap.