Sharing a cache across web workers
Deployment is where a cache meets the real world: several worker processes that don’t know each other’s names, a server that forks and recycles them while they’re busy, a cron job that opens the same directory on the side. diskcache-oxide is built for exactly this, so there isn’t much to it. This page gives one setup that works, then covers the few choices that matter. The example app runs this setup end to end.
The recommended setup
Most apps keep two kinds of things in a cache directory, and they need opposite settings:
- Cache: rendered pages, API responses, anything you can rebuild from somewhere else. If the cache has an outage, the right answer is a miss and a slower request, never an error page. These go in a
Cachesregistry withdurable=True, so a lock that stays busy or a full disk turns into a miss, logged, instead of an exception. - State: sessions, job claims, locks and work queues. Here a write that silently didn’t happen is a bug: a login that doesn’t stick, a job that runs twice, a queued job that vanishes. These are plain Caches, opened directly (never through the registry, which hands out a NullCache when a cache can’t open), not durable, with eviction off, so a failure raises and the app can say so. State isn’t cache explains why each of these breaks on a NullCache or a durable handle.
Both live under one directory the app owns, with the caches and the state side by side:
/var/lib/my-app/
├── cache/ # the registry's base directory
│ ├── pages/
│ └── api/
└── state/
├── sessions/
├── coordination/ # job claims and locks
└── jobs/ # the work queue
from pathlib import Path
from diskcache_oxide import Cache, Caches
ROOT = Path('/var/lib/my-app')
# Rebuildable data: durable, so an outage is a miss, never an error page.
caches = Caches(ROOT / 'cache', durable=True, timeout=1.0)
caches.register('pages', size_limit=1 * 2**30)
caches.register('api', size_limit=256 * 2**20)
# State: plain caches, opened directly, not durable, never evicted for size.
sessions = Cache(ROOT / 'state' / 'sessions', timeout=3.0, eviction_policy='none')
coordination = Cache(ROOT / 'state' / 'coordination', timeout=3.0, eviction_policy='none')
jobs = Cache(ROOT / 'state' / 'jobs', timeout=3.0, eviction_policy='none')
def close_everything() -> None:
caches.close_all()
for state in (sessions, coordination, jobs):
state.close()A few things about that layout:
- A directory is a cache or a parent of caches, never both.
cache/andstate/hold caches; they aren’t caches themselves. Don’t open a Cache on/var/lib/my-appor oncache/: maintenance treats two-character subdirectories of a cache as its own value folders, so a cache nested inside another one can lose its files. - Plain caches, no sharding. One Cache per purpose keeps memory low, one connection pool each. Reach for a
FanoutCacheonly for a cache that many processes write to at once. - Timeouts are short and stated.
timeout=1.0on the registry keeps a busy lock from holding a request for the default 60 seconds; durable doesn’t bound time by itself. State caches get a few seconds, and a Timeout from one is an error the app handles: a 503 page in a request, a retry in a worker. /var/lib, not/var/cache, because sessions and queues are state: a system may wipe/var/cache(systemctl clean --what=cachedoes), and that’s fine for caches and not for logins.
Pick a directory
- Persistent and private. The directory belongs to the user the app runs as. diskcache-oxide creates each cache directory
0700if it doesn’t exist (on Unix; on Windows it inherits its parent’s permissions); if you create them yourself, keep them that way. Anyone who can write to a cache directory can change what your app reads from it. With systemd,StateDirectory=my-appcreates/var/lib/my-appowned by the service’s user. - On a local disk. The cache relies on SQLite’s write-ahead log and its shared-memory file, which need a local filesystem. diskcache-oxide refuses to open only when SQLite itself declines the write-ahead log (some FUSE mounts do). It can’t tell that a directory is on NFS, SMB, EFS or Azure Files, where the log is usually accepted and then corrupts, so never put a cache on a network share or a Kubernetes ReadWriteMany volume.
- In Docker, mount one named volume at
/var/lib/my-appand give it to every container that should share the caches. Docker and Compose has the Compose file, the Dockerfile, and the ownership details that otherwise end inPermissionError.
Start and stop with the app
Open everything once per process, at startup, and share it across requests and threads. A Cache is safe to use from any number of threads. The setup above lives in a module of its own (say caching.py) that every entry point imports, together with the types you store.
FastAPI
from contextlib import asynccontextmanager
from fastapi import FastAPI
from myapp.caching import close_everything
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
close_everything()
app = FastAPI(lifespan=lifespan)In async code, reads can run on the event loop and writes go through asyncio.to_thread: see asyncio.
Flask
import atexit
from flask import Flask
from myapp.caching import close_everything
app = Flask(__name__)
atexit.register(close_everything)Django
Django’s own cache runs on diskcache-oxide through 'BACKEND': 'diskcache_oxide.DjangoCache': pages and fragments on a durable alias, sessions and counters on a plain one, each in its own directory under the app’s root. Django cache backend has the settings, and the example project runs them under gunicorn (walked through here). The backend opens nothing until first use and Django’s per-request close() does nothing, so there’s no startup or shutdown hook to write. For caches the app uses directly, outside django.core.cache (a Caches registry, a Lock, a work queue), put the setup in a module of its own (myapp/caching.py), take ROOT from settings, and import it where it’s needed.
Celery and other background workers
Celery’s prefork pool, RQ and multiprocessing with the fork start method are pre-forking servers like gunicorn: import the setup at import time, and each child gets its own connections on first use. Register your types the same way the web workers do, or a worker that reads a web worker’s value gets ForeignValueError (or, on a durable cache, a miss and a logged warning, so every read of it goes to the source). Closing at shutdown is optional; Celery’s worker_process_shutdown signal is the place for it.
from celery.signals import worker_process_shutdown
from myapp.caching import close_everything
@worker_process_shutdown.connect
def close_caches(**kwargs) -> None:
close_everything()Pre-forking and spawning servers
With gunicorn (including --preload) or Celery’s prefork pool, it doesn’t matter whether you open the cache before or after the fork. diskcache-oxide’s fork barrier makes sure no worker starts life holding half a database transaction, and each child opens its own fresh connections on first use. See Concurrency and forks.
uvicorn --workers doesn’t fork: it starts each worker as a fresh process (the spawn start method, on every platform), so each worker imports your app and opens its caches itself. On Linux, multiprocessing defaults to the forkserver start method since Python 3.14, which behaves the same way. Either is fine; there’s nothing to configure.
Keep the request path fast
Reads never wait for writers, so a get stays fast however busy the cache is. Writes are different: only one process can commit to a cache file at a time, and a write waits up to the cache’s timeout for its turn. On the durable registry a write that runs out of time is dropped and counted, which is what you want for a page fragment: the next request writes it. On a plain cache, treat Timeout as “skip this time” where that’s safe:
from diskcache_oxide import Timeout
def cache_quietly(cache, key: str, value: object, expire: float) -> None:
try:
cache.set(key, value, expire=expire)
except Timeout:
log.warning('cache busy; skipped storing %s', key)Under normal load a write takes about 20 µs and never comes near the timeout. The timeout matters during bursts, such as a big clear() from a maintenance script, and even then clear() steps aside between chunks to let waiting writes in.
Maintenance
There’s no maintenance job to write. Background maintenance looks after every open cache in every worker: every 5 minutes (maintenance_interval) it removes expired entries and their value files, trims a cache left over its size_limit (never one opened with eviction_policy='none', like the state caches), checkpoints a write-ahead log grown past its trim size, and once an hour clears stray temporary files and empty value folders. The workers sharing a cache take turns, so eight workers don’t do the same work eight times. maintenance_stats() on a cache, or the maintenance field of caches.stats(), shows how it’s going.
expire(), cull(), clear() and checkpoint(), and the registry’s expire_all(), are for when you want it done now: after a big import, say, or before a backup. Each takes its own timeout=, so a script can wait longer than a request would: sessions.expire(timeout=10.0). checkpoint() returns False instead of waiting long if workers are busy, so it’s safe to call any time.
At shutdown
close_all() and close() at shutdown, as above, are optional but tidy. Closing copies a large write-ahead log back into the database and truncates it, waiting at most a second. Call checkpoint() first after a burst of writes for a more thorough job. See Storage and WAL.
Switching caching off
To run with caching off (local development, or chasing a stale-data bug in production), switch the registry’s caches off by name: caches.disable('pages'). Lookups then return a NullCache that still forwards deletes, so nothing stale is waiting when you switch it back on. Don’t switch off state: sessions, claims and queues stop working on a NullCache. See Caches and NullCache.