12.2 Caching, signals, tasks, and files
Page caching and the middleware ordering trap
Why does Django split whole-site caching into two separate middleware (UpdateCacheMiddleware first, FetchFromCacheMiddleware last), and what breaks when they are placed beside each other?
Every developer setting up Django’s whole-site cache stops and blinks at the documentation: put UpdateCacheMiddleware at the very top of "MIDDLEWARE" and FetchFromCacheMiddleware at the very bottom! That looks backward until you recall Chapter 3’s middleware onion: request hooks run top-to-bottom, while response hooks unwind bottom-to-top!
Two keys per URL: learn_cache_key and get_cache_key
Why can a single URL like "/ produce different responses for different visitors? Because middleware and views add HTTP "Vary" headers ("Vary: Accept-Language" from LocaleMiddleware, "Vary: Cookie" from SessionMiddleware, or "Vary: Accept-Encoding" from GZipMiddleware). During process_request, however, Django has not called the view yet — so it does not know which request headers that URL varies on!
Django solves that chicken-and-egg problem in django/ by storing two cache entries per URL:
- Header registry via
learn_cache_key: On a cache miss,UpdateCacheMiddlewareinspects the finished response’s.process_response "Vary"header, hashes the URL plus active language and timezone via_i18n_cache_key_suffix, and stores the list of varied header names under"views. Then it computes the page cache key via.decorators .cache .cache_header.<prefix>.<url_md5>.<lang>.<tz>" _generate_cache_keyby hashing each varied header’s value using RFC 9111 netstring framing (b"-,"for absent headers vs.b"%d:%s,"for present headers so an absent header never collides with an empty one!) and stores the response under"views(deferring via.decorators .cache .cache_page.<prefix>.<method>.<url_md5>.<headers_md5>.<lang>.<tz>" SimpleTemplateResponseif it is an unrendered.add_post_render_callback TemplateResponse!). - Request lookup via
get_cache_key: On the next"GET"or"HEAD"request,FetchFromCacheMiddlewarefetches that header list first, hashes the incoming request’s values for those exact headers, and fetches the cached response — computing an estimated.process_request "Age"header and setting"requestso._cache_update_cache = False" UpdateCacheMiddlewaredoes not overwrite the cache on exit!
What breaks when the two middleware sit side by side
Now trace why placing them at opposite ends of "MIDDLEWARE" is mandatory — and what fails when they are moved together:
- Request entry (
FetchFromCacheMiddlewareLAST):SessionMiddleware,LocaleMiddleware, and any middleware that populates"requestor activates a user timezone MUST run before.LANGUAGE_CODE" FetchFromCacheMiddlewarecomputes.process_request _i18n_cache_key_suffix. If you placeFetchFromCacheMiddlewareaboveLocaleMiddleware,"requestdoes not exist yet — every French request looks up the.LANGUAGE_CODE" "en-us"cache key and either misses forever or gets served English HTML! - Response exit (
UpdateCacheMiddlewareFIRST): Because response hooks unwind bottom-to-top, puttingUpdateCacheMiddlewareat index0guarantees it runs dead last, afterSessionMiddlewarehas stamped"Vary: Cookie"/"Set-Cookie"andLocaleMiddlewarehas stamped"Vary: Accept-Language". Look at lines 99–113 and 132–133 ofdjango/:middleware/ cache .py UpdateCacheMiddlewarerefuses to cache any response that has.process_response "responsealongside.cookies" "Vary: Cookie", any response with"Cache-Control"directives"private","no-cache", or"no-store", or"Vary: *", and automatically adds"Vary: Authorization"whenever an"Authorization"header was present without"Cache-Control: public". If you accidentally putUpdateCacheMiddlewarebelowSessionMiddleware,UpdateCacheMiddlewarecaches a logged-in user’s personalized HTML beforeSessionMiddlewareeven adds"Vary: Cookie"— leaking one user’s page to every visitor!
Watch "desk/"'s "edition_front" view run through the canonical UpdateCacheMiddleware + FetchFromCacheMiddleware stack (dropping from 3 SQL queries to 0 and speeding up 24.50x), plus UpdateCacheMiddleware refusing to cache a "Vary: Cookie" + "Set-Cookie" response:
2. Page cache middleware ordering and Vary key learning
canonical_stack: miss_sql=3 hit_sql=0 view_calls=1 same_body=True
cache_headers: cache_control='max-age=600' key_suffix=['en-us', 'UTC']
vary_cookie_with_set_cookie: view_calls_after_2_gets=2 (never cached!)
1. Edition page render: uncached vs Update/FetchFromCacheMiddleware (7 trials, us)
cache_path median_us speedup
uncached edition_front (DB+tmpl) 2231.6 1.00x
cache miss (render + learn + set) 2386.8 0.93x
cache hit (FetchFromCacheMiddleware) 91.1 24.50x
Notice "key_suffix=['en-us', 'UTC']" right on the learned key — confirming that both active language and active timezone partition page caches automatically.
Caches speed up read paths; the next horizontal service — signals — looks like a decoupled event bus for write paths, yet executes strictly synchronously inside the caller’s stack and transaction. We dissect Signal next in Signal.send, weak references, and synchronous cost.