Skip to main content

Sharing a cache across web workers

The recommended production setup: a durable registry for rebuildable data, plain caches for state, one directory layout, and startup and shutdown for FastAPI, Flask, Django, Celery and pre-forking servers.

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.

Pick a directory

  • Persistent and private. The directory belongs to the user the app runs as. diskcache-oxide creates each cache directory 0700 if 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-app creates /var/lib/my-app owned 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-app and 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 in PermissionError.

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.