Invalidation, TTLs, HTTP revalidation and the staleness budget
Understand cache invalidation mechanics, staleness budgets across multi-tier caching architectures, and conditional HTTP revalidation semantics.
Contentsand lesson path
On this page
- Why it matters
- Invalidation and the staleness budget
- HTTP revalidation: headers, ETags and status codes
- Check your understanding
- Apply it
- Review prompt
Lessons of Caching Strategies
- Cache layers, from HTTP caching to the database Concept · 20 min
- Cache-aside, read-through, write-through, write-behind and refresh-ahead Concept · 25 min
- Invalidation, TTLs, HTTP revalidation and the staleness budget Concept · 20 min
- Hit-ratio math and sizing a cache tier Worked example · 25 min
- Surviving stampedes and hot keys Lab · 30 min
- Caching check Knowledge check · 8 questions
What you will learn
- Design invalidation, TTL and HTTP caching rules (Cache-Control, ETag revalidation) for API responses, and state the maximum staleness users can observe.
01. Why it matters
Imagine a user renames their organisation, reloads the dashboard, and still sees the old name for four minutes. Nothing is broken: Redis, a CDN and the browser each kept a copy for as long as they were allowed to. The support ticket raises the three questions this lesson answers. How does a change reach every cache? How long can the delay really be when several caches are stacked? And how can a client check cheaply that its copy is still good, instead of downloading it again?
02. Invalidation and the staleness budget
Phil Karlton's well-known quip names cache invalidation as one of the two hard problems in computer science. It is hard because a change in the database has to reach several independent caches, with no shared clock between them, before every user sees the new value.
There are two main ways to retire stale entries:
- TTL-based expiry. Every cached entry gets a time-to-live (TTL). When it elapses, the cache evicts the entry or marks it expired. This is simple and survives lost messages, but it accepts staleness for up to the length of the TTL.
- Event-driven invalidation. Whenever the data changes in the database, the application publishes an invalidation event (through a message queue, Redis pub/sub, or change data capture such as Debezium) that deletes or overwrites the cached entries. Staleness is much shorter, but a dropped message, a network partition or a lagging consumer can leave a stale entry in place until its TTL expires, or indefinitely if it has none. That is why event-driven invalidation is usually combined with a TTL as an upper bound.
The staleness budget: which TTLs add up. In a multi-tier system the caches do not work in isolation. Two shortcuts are both wrong: taking the largest single TTL in the stack, and subtracting one timer from another. The honest calculation asks, for every tier, when does its clock start?
Consider three tiers:
- Tier 1, application cache. A backend service caches user preferences in Redis with a TTL of 180 seconds.
- Tier 2, edge proxy or CDN. An edge proxy caches the serialised JSON response with
s-maxage=60(60 seconds). - Tier 3, browser. The browser caches the response with
max-age=30(30 seconds).
Now trace the worst case. At second 179.9 the service reads the Redis entry just before it expires and builds a new HTTP response from it: the data is almost 180 seconds old, but the response itself starts at age zero. Because the application rebuilds the response, the Redis TTL adds. The edge proxy then stores that response for its full 60 seconds. HTTP caches, however, do not restart the clock: RFC 9111 has every cache pass the response's age along (the Age header, with the Date header as a fallback), and each downstream cache measures freshness from when the origin generated the response. A browser that receives the copy at proxy second 59.9 sees Age: 59 against max-age=30, so the copy is already too old to reuse: the browser shows it for this request and asks again next time.
The worst case is therefore 180 + 60 = 240 seconds: the TTLs of application caches that rebuild responses, plus the largest max-age or s-maxage among the HTTP tiers, plus any stale-while-revalidate or stale-if-error window, because those really do let a cache serve content past its freshness lifetime. Summing every TTL (180 + 60 + 30 = 270 seconds) is a safe over-estimate, and it becomes the right answer only when a tier restarts the clock — for example an app-level cache in the client that keeps payloads for its own 30 seconds whatever their Age, or a proxy that strips both Age and Date. When you write a staleness target into an SLA, list every tier, mark whether it resets the age, and add accordingly.
03. HTTP revalidation: headers, ETags and status codes
HTTP caching is defined once for every HTTP version, in RFC 9111, and a few headers coordinate browsers, shared caches and origin servers. Two directives used in this lesson, stale-while-revalidate and stale-if-error, are extensions defined in RFC 5861; RFC 9111 allows such extensions but does not define them.
Cache-Control directives. Four of them come up in almost every API:
no-cache. Despite its name,no-cachedoes not mean "do not cache". A cache may store the response, but must revalidate it with the origin before using it to answer a request.no-store. Tells every cache not to store any part of the request or the response. Use it for secrets and one-time data (credentials, authorisation tokens, one-time codes) and for personal data that must not persist on shared devices. It depends on caches obeying it, and RFC 9111 warns that it is not a reliable way to guarantee privacy on its own. For personal data where cheap revalidation matters and the device is the user's own,private, no-cachewith an ETag is the usual compromise: nothing is stored in shared caches, and the browser copy is revalidated on every use. The second practice question below shows what goes wrong when a personal response leaves outprivate.privateandpublic.privateallows only a private cache, such as one user's browser, to store the response; shared caches (a CDN such as Cloudflare or Akamai, a reverse proxy) must not.publicsays the response may be stored by shared caches even where they would not store it by default, for example on a request that carried anAuthorizationheader.stale-while-revalidate(RFC 5861). Lets a cache answer with a stale response for a limited extra time while it fetches a fresh one in the background. Readers then rarely wait for the origin, at the price of seeing data that is up to that window older.
Conditional requests. When a cached response expires, downloading the whole body again wastes bandwidth if nothing changed. Conditional validation avoids that:
- ETag. The origin returns an
ETagheader, an opaque validator such as a hash or a version number of the representation (for exampleETag: "9f3a1b"). When the client's copy is stale, it sends a conditional request withIf-None-Match: "9f3a1b". The header may list several tags, or be*, andIf-None-Matchuses the weak comparison of RFC 9110:W/"9f3a1b"matches"9f3a1b". That matters in practice, because a proxy that compresses responses, such as nginx with gzip on, turns a strong ETag into a weak one. - 304 Not Modified. If the validator still matches, the origin answers
304 Not Modifiedwith no body. The client updates its copy's freshness and reuses the body it already has. - 200 OK. If the resource changed, the origin answers
200 OKwith the new body and a newETag. - Other status codes.
412 Precondition Failedbelongs toIf-Matchon state-changing requests (optimistic locking on PUT or PATCH), not to read revalidation.204 No Contentreports success with no body, whereas304 Not Modifiedtells the client to reuse its stored body.
import hashlib
import json
from fastapi import FastAPI, Request, Response, status
app = FastAPI()
# Mock database record
ORGANIZATION_DATA = {
"org_id": "org_7721",
"name": "Global Logistics Corp",
"plan": "enterprise",
"seat_count": 140,
}
def etag_matches(if_none_match: str | None, etag: str) -> bool:
"""If-None-Match uses weak comparison: ignore W/, accept a list or *."""
if if_none_match is None:
return False
if if_none_match.strip() == "*":
return True
# A simple split is enough here: these ETags never contain a comma
tags = [tag.strip().removeprefix("W/") for tag in if_none_match.split(",")]
return etag.removeprefix("W/") in tags
@app.get("/api/v1/organizations/{org_id}")
async def get_organization(org_id: str, request: Request, response: Response):
# 1. Serialise the representation and derive a deterministic ETag
payload = json.dumps(ORGANIZATION_DATA, sort_keys=True).encode("utf-8")
etag = f'"{hashlib.sha256(payload).hexdigest()[:16]}"'
headers = {"ETag": etag, "Cache-Control": "private, no-cache"}
# 2. The client's copy is still current: 304 with no body
if etag_matches(request.headers.get("if-none-match"), etag):
return Response(status_code=status.HTTP_304_NOT_MODIFIED, headers=headers)
# 3. No copy, or an outdated one: 200 with the body and the same headers
response.headers.update(headers)
return ORGANIZATION_DATA04. Check your understanding
05. Apply it
Put the invalidation and header rules into practice in a service you know:
- Calculate the worst-case staleness of your stack. For a service behind CDNs, reverse proxies and application caches, add the TTLs of every cache that rebuilds the response, the largest HTTP
max-ageors-maxageon the path, and anystale-while-revalidateorstale-if-errorwindow. Check that every HTTP tier forwardsAgeandDate; if one does not, fall back to summing all TTLs. Then check the result against what the business can accept. - Add ETags to read-heavy JSON APIs. For endpoints serving configuration objects, organisation settings or product catalogues, compute an ETag (a hash of the serialised body, or a row
versioncolumn that every write bumps). Answer a matchingIf-None-Matchwith304 Not Modifiedand no body, which saves the body bytes whenever nothing changed. - Use
no-storefor sensitive responses. For authentication tokens, payment details and other secrets, returnCache-Control: no-store, so that well-behaved browsers and proxies do not keep the response at all. - Use
stale-while-revalidatefor semi-static content. For blog posts or marketing pages,Cache-Control: public, max-age=60, stale-while-revalidate=300lets shared caches answer from their copy while they refresh it in the background.
The next lesson covers hit-ratio arithmetic, working-set sizing, and what a cold cache restart does to the database.
06. Review prompt
Without looking back: when a response passes through several caches, which TTLs add up, which do not, and what does the Age header change? How old can the data be, at worst, behind three caches? What is the difference between Cache-Control: no-cache and no-store? Walk through a conditional request with ETag and If-None-Match: why can the server answer 304 Not Modified with an empty body?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.