Sub topic 12
Making sure caches and CDNs serve the new facts
You can fix a price in your database and still show the old one for hours. Browsers, CDNs, and reverse proxies each keep copies of your pages. This chapter shows how to make those copies refresh when a fact changes, and how to confirm that they did.
It assumes you know the earlier chapters on single source of truth, JSON-LD, and the basic Cache-Control, ETag, and Last-Modified headers. It also assumes you can read HTTP response headers with curl -I or browser dev tools.
Where stale copies live
A request can be answered by any of several layers, and each can hold its own old copy.
| Layer | Who controls it | How it refreshes |
|---|---|---|
| Browser cache | The visitor's browser, following your headers | Waits for `max-age` to expire, then revalidates |
| CDN edge | The CDN, following your headers and its own rules | Expiry, purge, or revalidation |
| Origin cache or reverse proxy | Your infrastructure | Expiry or an explicit delete |
| Application cache (Redis, rendered fragments) | Your code | Key deletion or a TTL |
| Crawler's stored copy | The search engine or AI crawler | You cannot control it. You can only make the live page and sitemap correct |
The last row matters. Crawlers decide when to return. What you control is that every response they fetch carries the current facts, and that the lastmod and ETag values change when the content changes.
The freshness budget
Every cached page has a worst-case age: the longest a changed fact can stay invisible. For a response with max-age=300 and stale-while-revalidate=60, a visitor can see a copy up to about six minutes old. Decide that number per fact type, then set headers to fit it.
- Prices and stock: minutes, or immediate through purge.
- Product descriptions and specifications: hours.
- Article body text: hours to a day.
- Legal and policy text: a day, plus a purge when it changes.
The headers can give browsers and the CDN different lifetimes:
HTTP/1.1 200 OK
Cache-Control: public, max-age=60, s-maxage=86400, stale-while-revalidate=30
Surrogate-Key: product-TR2-BLK-42 category-trail-shoes
ETag: "v43"
Last-Modified: Sun, 29 Nov 2026 10:30:00 GMT
Content-Type: text/html; charset=utf-8max-age applies to every cache, including browsers. s-maxage applies only to shared caches such as CDNs and overrides max-age there. This response lets the CDN keep the page for a day, because you will purge it on change. Browsers keep it for only one minute, because you cannot purge a visitor's browser.
Surrogate-Key is the Fastly name for a tag that you attach to a response. Cloudflare calls it Cache-Tag. Other CDNs use similar names, so check your provider's documentation.
Purge strategies
A long CDN lifetime is safe only if every change triggers a purge. There are three ways to purge.
- Purge by URL. It is simple, but one product appears on many URLs: its page, category listings, search results, and comparison pages. Missing one leaves a stale price.
- Purge by tag. Tag each response with the IDs of the records it displays, then purge the tag. A category page lists thirty products and carries thirty tags, so changing any one of them clears it.
- Purge everything. Use this only as an emergency tool. It sends the whole traffic load to your origin at once.
Tag purging matches the single-source-of-truth idea. The same product record that renders the price also names the tag, so the page and its cache entry cannot disagree about which product they belong to.
Many CDNs offer a soft purge, which marks the object stale instead of deleting it. The edge then serves the old copy once while it fetches a new one. That protects your origin from load spikes, but a visitor can still see the old price during that one request. For price and stock use hard purge. For long articles with a corrected typo, soft purge is fine.
Purge from the change event
Purge inside the code path that saves the fact, not as a manual step. This example purges one product tag after a price update commits:
import os
import urllib.request
FASTLY_API = "https://api.fastly.com"
def purge_key(service_id: str, token: str, key: str) -> int:
"""Hard-purge every cached object tagged with `key`."""
req = urllib.request.Request(
f"{FASTLY_API}/service/{service_id}/purge/{key}",
method="POST",
headers={"Fastly-Key": token, "Accept": "application/json"},
)
with urllib.request.urlopen(req, timeout=10) as resp:
return resp.status
def after_product_saved(sku: str) -> None:
"""Call this only after the database transaction has committed."""
status = purge_key(
os.environ["FASTLY_SERVICE_ID"],
os.environ["FASTLY_API_TOKEN"],
f"product-{sku}",
)
print(f"purge product-{sku}: HTTP {status}")
if __name__ == "__main__":
after_product_saved("TR2-BLK-42")Two details decide whether this works.
- Order. Purge after the commit. If you purge first, the CDN can refetch from your origin before the new row is visible and cache the old price again for a full day. If your database uses read replicas, also wait until the replica has caught up, or have the origin read from the primary for that request.
- Failure handling. A purge request can fail. Put it in a retry queue and alert if it keeps failing. A silent failure means a day of stale prices with no error anywhere.
The sequence of a price change
The diagram shows the order of events and where a stale copy can slip in.
One response, several copies of the fact
The HTML body holds the visible price and the JSON-LD together, so one purge refreshes both. Problems begin when these are cached separately:
- Prices loaded by JavaScript from
/api/pricemay have a different cache lifetime than the page. Give them the same tag, or a shorter TTL. - If the JSON-LD comes from a different endpoint or fragment cache than the visible text, they can disagree. Render both from the same product object in the same request.
- Sitemaps and product feeds are cached files too. A
lastmodthat your sitemap generator caches for a day is wrong for a day. Purge or regenerate them from the same event.
Edge cases
Varyheaders.Vary: Accept-LanguageorVary: Cookiecreates one cached copy per value. Tag purges clear all variants, but URL purges might clear only one. Avoid varying on cookies for pages that show public prices.- Personalised prices. If logged-in users see member prices, send
Cache-Control: privatefor those responses, or serve the public page from cache and fetch the personal price separately. A shared cache that stores a member price and serves it to everyone shows a wrong fact. - Query strings. Some CDNs ignore query strings in the cache key, and others include them. Learn which one yours does.
?utm_source=...URLs can multiply cached copies that a URL purge misses. - Cached errors and redirects. A cached 404 for a product you just published, or a cached redirect for a retired product, outlives the change. Give error responses a short TTL, and purge the tag when a product's status changes.
- Ignored origin headers. Some CDN rules override your
Cache-Controlwith a fixed TTL. If your headers seem to have no effect, check the CDN configuration. - Request collapsing. After a purge, many simultaneous visitors can all miss the cache and hit your origin. Enable request collapsing, or use
stale-while-revalidatefor content that tolerates it.
Verify instead of trusting
After a change, fetch the public URL and compare what comes back with the source of truth. This script reads the JSON-LD price from the live page and reports the cache age:
import json
import re
import sys
import urllib.request
LD_JSON = re.compile(
r'<script type="application/ld\+json">(.*?)</script>', re.S
)
def fetch(url):
req = urllib.request.Request(url, headers={"User-Agent": "freshness-check/1.0"})
with urllib.request.urlopen(req, timeout=10) as resp:
return resp.headers, resp.read().decode("utf-8")
def jsonld_price(html):
for block in LD_JSON.findall(html):
data = json.loads(block)
if data.get("@type") == "Product":
return data["offers"]["price"]
return None
def check(url, expected_price):
headers, html = fetch(url)
seen = jsonld_price(html)
print("Age:", headers.get("Age", "n/a"))
print("Cache-Control:", headers.get("Cache-Control", "n/a"))
print("JSON-LD price:", seen, "expected:", expected_price)
return seen == expected_price
if __name__ == "__main__":
ok = check(sys.argv[1], sys.argv[2])
sys.exit(0 if ok else 1)Run it as python check_price.py https://example.com/p/trail-runner-2 89.00. Fetch the exact public URL. If you add a random query string to bypass the cache, you test your origin and learn nothing about what the edge serves. A large Age value right after a purge means the purge did not reach that object.
Putting it together
- Choose a maximum staleness for each fact type.
- Give browsers a short
max-ageand the CDN a longers-maxagebacked by purges. - Tag every response with the records it shows.
- Purge by tag from the code that saves the fact, after the commit, with retries.
- Keep the HTML, JSON-LD, API responses, sitemap, and feed on the same tags.
- Run an automated check after each change, and on a schedule to catch purges that failed.
Exercise
Your CDN uses Cache-Control: public, max-age=300, s-maxage=86400. An editor lowers a product price at 10:00, and the application purges the tag at 09:59 just before the database commit. At 10:05 a visitor still sees the old price. Give two reasons this can happen and one fix for each.
Show answer
First, the purge ran before the commit. Between 09:59 and the commit, a request missed the cache, fetched the old price from the origin, and the CDN stored it for up to 86400 seconds. Fix: purge only after the transaction commits (and after replicas catch up). Second, browsers that fetched the page earlier keep it for up to 300 seconds, and you cannot purge a browser. Fix: keep max-age as short as the freshness budget for prices allows, and revalidate with ETag.