Django 6.1.3

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.core.cache import cache, caches") 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.create_connection, 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.make_key passes it through default_key_func:

return "%s:%s:%s" % (key_prefix, version, key)

That three-part format (":1:edition:2026-11-25" when "KEY_PREFIX" is empty and "VERSION" is 1) solves two operational problems without touching your application code:

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.OrderedDict protected by a threading.Lock:

  1. Every set() pickles and every get() unpickles: Notice LocMemCache.set calls pickle.dumps(value, pickle.HIGHEST_PROTOCOL) and LocMemCache.get calls pickle.loads(pickled). Why pay pickle overhead for an in-process dictionary? So LocMemCache mirrors 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!
  2. LRU culling on "MAX_ENTRIES": Both get() and _set() call collections.OrderedDict.move_to_end (last=False, putting hot keys at the front); once len(_cache) >= _max_entries (300 by default), LocMemCache._cull pops one-third ("1 / CULL_FREQUENCY") of the oldest keys from the tail.
  3. 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.delete('edition:2026-11-25')", Workers 2, 3, and 4 keep serving stale HTML until their TTL expires — and four copies of every cached object waste 4x RAM!

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.validate_key), 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.make_key versioning ("v1" vs. "v2"), and pickle isolation execute live on "desk/":

Recorded on Django 6.1.3 ch12-services script
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.