---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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` (`django/core/cache/__init__.py:CacheHandler`): it subclasses `BaseConnectionHandler` (`django/utils/connection.py: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 `django/core/cache/__init__.py:cache` is simply a `ConnectionProxy` (`django/utils/connection.py:ConnectionProxy`) forwarding attributes to alias `"default"`. At the end of every HTTP request, `close_caches` (`django/core/cache/__init__.py: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`** (`django/core/cache/backends/base.py:BaseCache.make_key`) passes it through `default_key_func` (`django/core/cache/backends/base.py:default_key_func`):

```python
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:

- **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 `"cache.incr_version(...)"` or deploying `"VERSION = 2"`) immediately misses every stale v1 entry (`":2:edition:2026-11-25"`) in `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/core/cache/backends/locmem.py: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` (`django/core/cache/backends/locmem.py:LocMemCache.set`) calls `pickle.dumps(value, pickle.HIGHEST_PROTOCOL)` and `LocMemCache.get` (`django/core/cache/backends/locmem.py: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` (`django/core/cache/backends/redis.py:RedisCache`, using `redis-py` connection pools), `PyMemcacheCache` (`django/core/cache/backends/memcached.py:PyMemcacheCache`, fast volatile RAM with strict 250-byte key limits enforced by `BaseCache.validate_key`), or `DatabaseCache` (`django/core/cache/backends/db.py: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` (`django/core/cache/backends/base.py: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/"`:

```text recording=ch12-services
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](cache-middleware.md).
