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

# 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`** (`django/middleware/cache.py:UpdateCacheMiddleware`) at the **very top** of `"MIDDLEWARE"` and **`FetchFromCacheMiddleware`** (`django/middleware/cache.py: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` (`django/utils/cache.py:learn_cache_key`):** On a cache miss, `UpdateCacheMiddleware.process_response` (`django/middleware/cache.py:UpdateCacheMiddleware.process_response`) inspects the finished response's `"Vary"` header, hashes the URL plus active language and timezone via `_i18n_cache_key_suffix` (`django/utils/cache.py:_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` (`django/utils/cache.py:_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` (`django/utils/cache.py:get_cache_key`):** On the next `"GET"` or `"HEAD"` request, `FetchFromCacheMiddleware.process_request` (`django/middleware/cache.py: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:

- **Request entry (`FetchFromCacheMiddleware` LAST):** `SessionMiddleware`, `LocaleMiddleware`, and any middleware that populates `"request.LANGUAGE_CODE"` or activates a user timezone MUST run **before** `FetchFromCacheMiddleware.process_request` computes `_i18n_cache_key_suffix`. If you place `FetchFromCacheMiddleware` above `LocaleMiddleware`, `"request.LANGUAGE_CODE"` does not exist yet — every French request looks up the `"en-us"` cache key and either misses forever or gets served English HTML!
- **Response exit (`UpdateCacheMiddleware` FIRST):** Because response hooks unwind bottom-to-top, putting `UpdateCacheMiddleware` at index `0` guarantees it runs **dead last**, *after* `SessionMiddleware` has stamped `"Vary: Cookie"` / `"Set-Cookie"` and `LocaleMiddleware` has stamped `"Vary: Accept-Language"`. Look at lines 99–113 and 132–133 of `django/middleware/cache.py`: `UpdateCacheMiddleware.process_response` **refuses to cache** any response that has `"response.cookies"` alongside `"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 put `UpdateCacheMiddleware` *below* `SessionMiddleware`, `UpdateCacheMiddleware` caches a logged-in user's personalized HTML *before* `SessionMiddleware` even 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:

```text recording=ch12-services
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!)
```

```text recording=ch12-bench
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](signals.md).
