12.1 Caching, signals, tasks, and files
Cache backends, key versioning, and stampedes
How does CacheHandler isolate connections, how does make_key add prefixes and version numbers, and why does LocMemCache fail across multiple worker processes?
Django’s cache API ("from django) uses the exact same lazy per-thread/coroutine connection handler pattern as DATABASES (Chapter 9). Underneath that uniform get/set/add/delete contract, however, the individual backends have radically different process-isolation, serialization, and eviction semantics.
CacheHandler and BaseCache.make_key versioning
Open CacheHandler: it subclasses BaseConnectionHandler with "settings_name = 'CACHES'". Accessing caches["default"] instantiates the configured backend lazily on first use in the current thread or async task via CacheHandler, and cache is simply a ConnectionProxy forwarding attributes to alias "default". At the end of every HTTP request, close_caches runs on request_finished to release any per-request backend sockets cleanly.
Before any backend stores or fetches a key, BaseCache passes it through default_key_func:
return "%s:%s:%s" % (key_prefix, version, key)
That three-part format (": when "KEY_PREFIX" is empty and "VERSION" is 1) solves two operational problems without touching your application code:
- Shared-cluster isolation (
"KEY_PREFIX"): Staging and production (or two apps sharing one Redis/Memcached cluster) never collide when each sets a distinct"KEY_PREFIX". - Atomic namespace invalidation (
"VERSION"): Because Memcached and Redis caches do not support cheap wildcard deletes, bumping a key’s"version"(via"cacheor deploying.incr_version(...)" "VERSION = 2") immediately misses every stale v1 entry (":) in2: edition: 2026-11-25" O(1)time while letting old v1 entries expire naturally!
Why LocMemCache pickles — and why it breaks under multi-worker deploys
Look inside LocMemCache, Django’s default development cache backend (and "desk/"'s in-memory backend). Its storage is three module-level Python globals — "_caches", "_expire_info", and "_locks" — keyed by "LOCATION", storing values inside a collections protected by a threading.Lock:
- Every
set()pickles and everyget()unpickles: NoticeLocMemCache.setcallspickleand.dumps(value, pickle .HIGHEST_PROTOCOL) LocMemCache.getcallspickle. Why pay pickle overhead for an in-process dictionary? So.loads(pickled) LocMemCachemirrors network backends (RedisCache,PyMemcacheCache): mutating a list or dict returned by"cache.get()"never mutates the cached object, and unpicklable objects fail immediately in development instead of crashing only in production! - LRU culling on
"MAX_ENTRIES": Bothget()and_set()callcollections(.OrderedDict .move_to_end last=False, putting hot keys at the front); oncelen(_cache) >= _max_entries(300by default),LocMemCachepops one-third (._cull "1 / CULL_FREQUENCY") of the oldest keys from the tail. - Strict single-process isolation: Because
"_caches"lives inside one Python interpreter’s heap, running four Gunicorn or uWSGI workers creates four independent, unsynchronized caches. When Worker 1 updates a"Story"and calls"cache, Workers 2, 3, and 4 keep serving stale HTML until their TTL expires — and four copies of every cached object waste.delete('edition: 2026-11-25')" 4xRAM!
For multi-process production deployments, swap to a shared backend: RedisCache (RedisCache, using redis-py connection pools), PyMemcacheCache (PyMemcacheCache, fast volatile RAM with strict 250-byte key limits enforced by BaseCache), or DatabaseCache (DatabaseCache, durable across restarts at the cost of DB writes and periodic culling). Watch out too for cache stampedes (thundering herds): when a hot key expires under heavy traffic, dozens of workers miss simultaneously and slam the database with identical queries; mitigate stampedes with short lock keys via atomic BaseCache.add (BaseCache.add, which sets only if absent), jittered TTLs, or background refresh tasks.
Watch LocMemCache, BaseCache versioning ("v1" vs. "v2"), and pickle isolation execute live on "desk/":
1. CacheHandler, BaseCache.make_key, and LocMemCache pickling
backend=LocMemCache make_key_v1=':1:edition:2026-11-25' make_key_v2=':2:edition:2026-11-25'
pickle_isolation: returned_is_original=False cached_stories_after_mutation=[1, 2, 3, 4] version_2_miss=None
Mutating "got1['stories']" left the cached [1, 2, 3, 4] completely untouched because LocMemCache unpickled a fresh copy, and requesting version=2 missed cleanly without deleting version=1.
Low-level key/value caching is explicit. Whole-site HTTP response caching is automatic — and depends completely on placing two middleware classes at opposite ends of "MIDDLEWARE", which we trace next in Page caching and the middleware ordering trap.