The Analogy: A Pharmacy's Will-Call Prescription Shelf
A busy pharmacy does not fill your prescription while you wait at the counter. It fills scripts in advance, seals each one in a stapled bag, and lines the bags up on a shelf behind the register called will-call. When you arrive the technician does not count pills or print a label; they walk to the shelf, pull your bag, and hand it over. The slow work was done once, ahead of time, so the counter itself is fast. That is the entire promise of a cache: pay for the work once, store the result, and serve it back in the time it takes to reach a shelf.
The shelf only works because every bag is labelled, and the label is what makes a bag findable. A good label is not just a surname. Two patients are both called Ada Okafor; a label that says only "Okafor" cannot tell their bags apart. So the pharmacy prints the full name, the date of birth, the drug, and the dose on every bag, because those are the things that distinguish one bag from another. The label has to carry every detail the contents depend on. Leave one out and two different bags can answer to the same label.
Bags do not live on the shelf forever. A prescription can be changed by the doctor, cancelled, or superseded by a new dose, and the bag sitting in will-call is now wrong. So the pharmacy runs two rules. Any bag older than a set number of days is pulled and re-checked automatically, whether or not anyone noticed a problem -- a blunt safety net. And when the pharmacist knows a specific script has changed, they pull that exact bag at once rather than waiting for the timer. The timer bounds how long any mistake can sit unnoticed; the deliberate pull fixes the ones they catch.
Now the failure. One overwhelmed afternoon a technician starts labelling bags by surname only, because it is faster. The first Okafor's bag goes up labelled "Okafor". A second Okafor arrives, the technician pulls the bag that matches, and hands over someone else's medication -- with that person's full name, home address, and drug list printed on the front -- to a complete stranger. Nothing about the shelf looks broken. The bag was found instantly, the counter was fast, the system behaved exactly as built. It failed only because the label omitted an input that mattered, and the two requests that exposed it happened to arrive in the wrong order. A cache that keys a private page on nothing but its URL fails in precisely this way.
Syntax or Core Structure
Django's cache is one object, django.core.cache.cache, with a small dictionary-like API: get, set, delete, and get_or_set. The stand-in below is that API reduced to an in-process dictionary with two counters, so you can watch exactly when the expensive work runs and when it is skipped. get_or_set is the whole pattern in one call: look up the key, and only if it is absent compute the value, store it, and return it.
MISS = object()
class Cache:
def __init__(self):
self.store = {}
self.reads = 0
self.computes = 0
def get(self, key, default=None):
self.reads = self.reads + 1
return self.store.get(key, default)
def set(self, key, value):
self.store[key] = value
def get_or_set(self, key, maker):
found = self.get(key, MISS)
if found is MISS:
self.computes = self.computes + 1
value = maker()
self.set(key, value)
return value
return found
def top_products():
return ["pump", "hose", "valve"]
cache = Cache()
print("first: " + ", ".join(cache.get_or_set("catalog:top:v1", top_products)))
print("second: " + ", ".join(cache.get_or_set("catalog:top:v1", top_products)))
print("computes: " + str(cache.computes))
print("reads: " + str(cache.reads))
Output:
first: pump, hose, valve
second: pump, hose, valve
computes: 1
reads: 2
The first call is a miss: the key is absent, so get_or_set runs top_products(), stores the list, and returns it. The second call finds the key and returns the stored list without calling top_products() again -- computes stays at 1, which is the entire point of the cache. reads is 2 because each get_or_set performs exactly one lookup. The MISS sentinel matters more than it looks: get returns it only when the key is genuinely absent, so a value that is legitimately None (a product with no price yet) still counts as a hit. Use None as your miss marker instead and every cached None recomputes forever, defeating the cache for exactly the values you cached on purpose.
Technical Depth: Where the Key Comes From, and Why an Incomplete Key Leaks
Django gives you three levels of caching, and they differ mainly in what forms the key. The cache is only ever correct when the key contains every input the value depends on, so choosing a level is really a choice about what you are willing to put in the key.
The three levels of caching
Each level trades control for convenience. The higher you go, the less code you write and the less you decide about the key.
| Level | What forms the key | What it caches | The catch |
|---|---|---|---|
| Per-site | The full request path | Every rendered page | One switch caches pages you never meant to |
| Per-view | The URL, via cache_page | One view's response | The key omits the user unless you vary it |
| Low-level | Whatever string you pass | Any picklable value | You own the correctness of every key by hand |
Per-view caching is where most leaks are born. cache_page keys on the URL and nothing else, so two different users requesting /orders/ hit the same cache entry. The first user's rendered order list is served to the second. You fix it by adding the user's identity to the key (via vary_on_headers or a custom key function), which is exactly the low-level discipline the decorator was trying to hide from you.
Backends and the per-process trap
The backend decides where the stored value physically lives, and that decides whether your workers even share a cache.
| Backend | Where it lives | Shared across workers | Survives restart |
|---|---|---|---|
| LocMemCache | The worker process itself | No | No |
| Memcached | A separate daemon | Yes | No |
| Redis | A separate daemon | Yes | Yes, if persisted |
| DatabaseCache | A table in your database | Yes | Yes |
| FileBasedCache | Files on one host's disk | Only on that host | Yes |
LocMemCache is the default, and it is per-process. Run four Gunicorn workers and you have four independent caches: a value set by worker 1 is a miss on worker 2, an invalidation sent to worker 3 leaves the other three serving the stale copy, and your hit rate silently drops to a quarter of what you measured in development with one process. The demo below uses a single shared dict precisely so the leak it shows is about the key, not the backend -- but in production the backend is the second trap waiting behind the first.
Here is the leak, reduced to its essentials. A page cache serves /orders/, and each visitor should see their own orders. The only difference between the two runs is the function that builds the key.
class PageCache:
def __init__(self, key_of):
self.key_of = key_of
self.store = {}
self.renders = 0
def render_for(self, user):
key = self.key_of(user)
if key in self.store:
return self.store[key]
self.renders = self.renders + 1
page = "orders for " + user
self.store[key] = page
return page
def url_only(user):
return "/orders/"
def url_and_user(user):
return "/orders/:" + user
VISITS = ["ada", "bob", "ada", "cara"]
def run(label, key_of):
cache = PageCache(key_of)
print(label + ":")
for user in VISITS:
served = cache.render_for(user)
print(" " + user.ljust(5) + "sees -> " + served)
print(" renders: " + str(cache.renders))
run("url-only keying", url_only)
run("url+user keying", url_and_user)
Output:
url-only keying:
ada sees -> orders for ada
bob sees -> orders for ada
ada sees -> orders for ada
cara sees -> orders for ada
renders: 1
url+user keying:
ada sees -> orders for ada
bob sees -> orders for bob
ada sees -> orders for ada
cara sees -> orders for cara
renders: 3
Under url-only keying the page renders exactly once, and that single render belongs to ada. Every visitor after her -- bob, ada again, cara -- is handed ada's order list. The cache looked healthy: one render for four requests is a superb hit rate, and in a load test with identical users it would sail through. It is also a straightforward data breach, and nothing in the cache layer will ever warn you. Add the user to the key and the count rises to 3 (ada's second visit is the only legitimate hit), each person sees their own page, and the "worse" hit rate is the correct one. The lesson is blunt: a cache key that omits an input the output depends on does not make the cache faster, it makes it wrong.
Real World Example: A Product Cache With TTL, Versioning and Invalidation
A catalog page reads prices thousands of times a minute and changes them rarely, which is the textbook case for caching. The three mechanisms that keep such a cache honest are a TTL so a missed invalidation self-heals, a version segment so a deploy can retire every old entry at once, and an explicit delete so a known change takes effect immediately instead of waiting out the TTL. The program below models all three on a logical clock so the timing is exact and reproducible.
VERSION = 3
TTL = 300
PRICES = {"pump": 1500, "hose": 400}
class TtlCache:
def __init__(self):
self.store = {}
self.now = 0
self.hits = 0
self.misses = 0
def tick(self, t):
self.now = t
def key(self, name):
return "price:v" + str(VERSION) + ":" + name
def get_price(self, name):
k = self.key(name)
entry = self.store.get(k)
if entry is not None and entry["expires"] > self.now:
self.hits = self.hits + 1
return entry["value"]
self.misses = self.misses + 1
value = PRICES[name]
self.store[k] = {"value": value, "expires": self.now + TTL}
return value
def invalidate(self, name):
k = self.key(name)
if k in self.store:
del self.store[k]
cache = TtlCache()
def show(t):
cache.tick(t)
print("t=" + str(t).ljust(4) + "pump: " + str(cache.get_price("pump")))
show(0)
show(100)
PRICES["pump"] = 1800
show(200)
cache.invalidate("pump")
show(210)
show(520)
print("hits: " + str(cache.hits))
print("misses: " + str(cache.misses))
Output:
t=0 pump: 1500
t=100 pump: 1500
t=200 pump: 1500
t=210 pump: 1800
t=520 pump: 1800
hits: 2
misses: 3
Walk the clock. At t=0 the key is absent, so the cache misses, reads 1500 from the source, and stores it with an expiry of 300. At t=100 the entry is live, so the read is a hit. Between then and t=200 the real price changes to 1800, but the cache does not know: at t=200 the entry is still unexpired, so the cache returns the stale 1500. That is the hit that costs money. Then invalidate deletes the key, so t=210 misses and recomputes the fresh 1800 with a new expiry of 510. At t=520 that second entry has expired (510 is not greater than 520), so even with no explicit invalidation the cache misses and re-reads -- the TTL has quietly healed the entry on its own.
The three mechanisms each cover a different failure. The explicit invalidate is the fast path: when your code knows the price changed, it removes the entry so the very next read is correct, with no waiting. The TTL is the safety net for the invalidation you forgot to write or that failed to run on one of four workers -- the entry cannot be wrong for longer than 300 ticks no matter what. The VERSION segment is the blunt instrument: bump it in one place and every old key becomes unreachable at once, which is how you retire a cache whose shape changed in a deploy without hunting down individual keys.
The stale window between the price change and t=210 is the honest weakness, and it is worth naming the flaws in this code rather than pretending it is production-ready. The window itself is a real defect: for as long as it lasts the system quotes a price that is simply wrong, and for money that is not acceptable -- a price shown at checkout should be read from the source of truth, never from a TTL cache. The version is bumped by hand, so a developer who changes the cached shape and forgets to bump it ships a cache that serves yesterday's structure to today's code. There is no stampede protection: when a hot key expires, every worker misses at the same instant and all of them recompute, hammering the source exactly when it is busiest. And the store is a single in-process dict, so in a real deployment it neither survives a restart nor is shared between workers, and a full flush to reclaim memory silently drops every entry at once.
Common Mistakes
- Caching a private page on the URL alone.
cache_pagekeys on the request path and nothing else, so two users requesting the same URL share one entry and the first user's rendered page is served to the second. Vary the key on the user's identity for anything authenticated.
- Leaving the TTL off because "we invalidate on write." Invalidation is best-effort and fails quietly -- a signal that did not fire, a worker that missed the message. The TTL is the only thing that bounds how long a missed invalidation can keep serving stale data, so it is a safety net, not an optimization.
- Assuming LocMemCache is shared. It lives inside one worker process, so N workers means N independent caches: a value set on one is a miss on the others, and an invalidation reaches only the worker that handled it. Use Redis or Memcached for anything that must be consistent across requests.
- Expecting post_save signals to fire for bulk operations.
queryset.update(),bulk_update()andbulk_create()go straight to SQL and never callsave(), so signal-based invalidation silently skips them and the cache keeps the pre-update values.
- Using None as the miss marker.
cache.getreturnsNonefor a miss, so a value that is legitimatelyNoneis indistinguishable from absent and recomputes on every single read. Pass a unique sentinel object as the default and compare against it.
- Building an incomplete key. If the output depends on locale, currency, or a feature flag and the key does not mention them, the cache serves one variant to everyone who asks. The key must contain every input the value depends on -- that is the whole contract.
- Caching whole model instances or large querysets. They bloat the store, pickle and unpickle slowly, and freeze stale copies of related rows. Cache the specific scalar values a page needs, not the ORM objects behind them.
- Leaving hot keys unprotected against stampedes. When a popular key expires, every worker misses in the same instant and all of them recompute at once, spiking load on the database exactly when traffic is heaviest. Add a short lock or a probabilistic early refresh.
- Never versioning the cache. After a deploy changes the shape of a cached value, old entries deserialize into the new code and cause bugs that look nothing like a cache problem. A
KEY_PREFIXorVERSIONsegment retires every stale entry the moment you bump it.
Best Practices
- Make the key a function of every input. Write an explicit key-building function that takes each varying input -- user, locale, currency, flags -- as an argument. If you cannot list what the value depends on, you cannot key it correctly, and that is a signal not to cache it yet.
- Always set a TTL, even when you invalidate. Choose it from how long stale data is tolerable, and treat it as the backstop that limits the damage of any invalidation that does not run. A cache with no expiry turns one missed signal into permanent corruption.
- Use a shared backend in production. Redis or Memcached give every worker one consistent view; keep LocMemCache for a single-process development box where its per-process nature cannot bite you.
- Use a sentinel object for misses. Pass
object()as the default tocache.getso a legitimatelyNonevalue is stored and served like any other, instead of masquerading as a miss forever.
- Invalidate on known writes, and handle bulk operations by hand. Wire
post_saveandpost_deletefor ordinary saves, but rememberupdate()and thebulk_methods skip signals -- clear their keys explicitly at the call site.
- Version the cache namespace. Give keys a
KEY_PREFIXandVERSION, and bump the version whenever a deploy changes the shape of what you store, so stale entries become unreachable rather than mis-deserialized.
- Cache the smallest correct thing. Prefer scalars and rendered fragments over whole model instances and querysets, and measure the real hit rate rather than assuming the cache helps -- a cache that never hits is pure overhead.
- Never cache values that must be exact when used. Prices at checkout, account balances, and authorization decisions must be read from the source of truth at the moment of use; a fast wrong answer is worse than a slow right one.
Practice Exercises
- Close the per-view leak. Start from a page cache that keys
/orders/on the URL alone and serves the first user's page to everyone. Change the key function to include the requesting user, then feed it a sequence of visits from three different users and assert that each receives their own page and that the render count equals the number of distinct users, not one.
- Prove the None-as-miss bug. Implement
get_or_settwice: once with a unique sentinel object as the miss marker and once withNone. Cache a value that is genuinelyNone(a product with no price yet) and read it several times. Show that the sentinel version computes exactly once while theNoneversion recomputes on every read.
- Catch the bulk-update gap. Build a cache invalidated by a
post_save-style hook, warm it, then change the underlying rows two ways: once through a per-row save and once through a bulkupdate(). Show that only the per-row path invalidates the entry, then add an explicit invalidation to the bulk path and show the stale read disappears.
- Version and guard the TtlCache. Extend the
TtlCacheso that bumpingVERSIONmakes every existing entry unreachable in a single step, and verify that a read after the bump is a miss. Then add single-flight protection so that when a hot key expires and several requests miss at once, the underlying value is computed only one time; count the computes to prove it.