Django 6.1.3

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 "/editions/2026-11-25/" 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/utils/cache.py by storing two cache entries per URL:

  1. Header registry via learn_cache_key: On a cache miss, UpdateCacheMiddleware.process_response inspects the finished response’s "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.decorators.cache.cache_header.<prefix>.<url_md5>.<lang>.<tz>". Then it computes the page cache key via _generate_cache_key by 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.decorators.cache.cache_page.<prefix>.<method>.<url_md5>.<headers_md5>.<lang>.<tz>" (deferring via SimpleTemplateResponse.add_post_render_callback if it is an unrendered TemplateResponse!).
  2. Request lookup via get_cache_key: On the next "GET" or "HEAD" request, FetchFromCacheMiddleware.process_request fetches that header list first, hashes the incoming request’s values for those exact headers, and fetches the cached response — computing an estimated "Age" header and setting "request._cache_update_cache = False" so UpdateCacheMiddleware does 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:

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:

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