# 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](https://github.com/mikeckennedy/diskcache-oxide/tree/main/examples/webapp) 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 [`Caches`](../user-guide/caches.md) registry with `durable=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 [Cache](../reference/Cache.md#diskcache_oxide.Cache)s, opened directly (never through the registry, which hands out a [NullCache](../reference/NullCache.md#diskcache_oxide.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](../user-guide/caches.md#state-isnt-cache) explains why each of these breaks on a [NullCache](../reference/NullCache.md#diskcache_oxide.NullCache) or a durable handle. Both live under one directory the app owns, with the caches and the state side by side: ``` text /var/lib/my-app/ ├── cache/ # the registry's base directory │ ├── pages/ │ └── api/ └── state/ ├── sessions/ ├── coordination/ # job claims and locks └── jobs/ # the work queue ``` ``` python 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/` and `state/` hold caches; they aren't caches themselves. Don't open a [Cache](../reference/Cache.md#diskcache_oxide.Cache) on `/var/lib/my-app` or on `cache/`: 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](../reference/Cache.md#diskcache_oxide.Cache) per purpose keeps memory low, one connection pool each. Reach for a [`FanoutCache`](../user-guide/fanoutcache.md) only for a cache that many processes write to at once. - **Timeouts are short and stated.** `timeout=1.0` on 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](../reference/Timeout.md#diskcache_oxide.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=cache` does), 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 `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](docker.md) 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](../reference/Cache.md#diskcache_oxide.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](custom-types.md) you store. ## FastAPI ``` python 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](asyncio.md). ## Flask ``` python 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](../user-guide/django.md) has the settings, and the [example project](https://github.com/mikeckennedy/diskcache-oxide/tree/main/examples/django) runs them under gunicorn ([walked through here](../example-apps/django.md)). The backend opens nothing until first use and Django's per-request [close()](../reference/Cache.close.md#diskcache_oxide.Cache.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](../reference/Caches.md#diskcache_oxide.Caches) registry, a [Lock](../reference/Lock.md#diskcache_oxide.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](../reference/ForeignValueError.md#diskcache_oxide.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. ``` python 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](../user-guide/concurrency-and-forks.md). `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](../reference/Cache.get.md#diskcache_oxide.Cache.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](../reference/Cache.timeout.md#diskcache_oxide.Cache.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](../reference/Timeout.md#diskcache_oxide.Timeout) as "skip this time" where that's safe: ``` python 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()](../reference/Cache.clear.md#diskcache_oxide.Cache.clear) from a maintenance script, and even then [clear()](../reference/Cache.clear.md#diskcache_oxide.Cache.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](../reference/Cache.size_limit.md#diskcache_oxide.Cache.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()](../reference/Cache.maintenance_stats.md#diskcache_oxide.Cache.maintenance_stats) on a cache, or the `maintenance` field of `caches.stats()`, shows how it's going. [expire()](../reference/Cache.expire.md#diskcache_oxide.Cache.expire), [cull()](../reference/Cache.cull.md#diskcache_oxide.Cache.cull), [clear()](../reference/Cache.clear.md#diskcache_oxide.Cache.clear) and [checkpoint()](../reference/Cache.checkpoint.md#diskcache_oxide.Cache.checkpoint), and the registry's [expire_all()](../reference/Caches.expire_all.md#diskcache_oxide.Caches.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()](../reference/Cache.checkpoint.md#diskcache_oxide.Cache.checkpoint) returns `False` instead of waiting long if workers are busy, so it's safe to call any time. # At shutdown [close_all()](../reference/Caches.close_all.md#diskcache_oxide.Caches.close_all) and [close()](../reference/Cache.close.md#diskcache_oxide.Cache.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()](../reference/Cache.checkpoint.md#diskcache_oxide.Cache.checkpoint) first after a burst of writes for a more thorough job. See [Storage and WAL](../user-guide/storage-and-wal.md). # 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](../reference/NullCache.md#diskcache_oxide.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](../reference/NullCache.md#diskcache_oxide.NullCache). See [Caches](../user-guide/caches.md#switching-caches-off) and [NullCache](../user-guide/null-cache.md).