Video in progress
When caching API responses through a CDN, which Cache-Control directives matter, and what mistakes show personal data to other people?
s-maxage sets the lifetime for shared caches, max-age for the browser, and private means the CDN must not cache. The most dangerous mistake is marking a user-specific response public, or forgetting Vary.
📖 Answer
The classic case: someone carelessly put Cache-Control: public, max-age=60 on the /api/me endpoint. The CDN cached the first user's profile, and for the next minute everyone saw that profile. A cookie or Authorization header doesn't automatically mean "don't cache" for the CDN — that depends on the CDN's configuration.
The main directives:
| Directive | Meaning |
|---|---|
private |
only the browser may cache, not the CDN |
no-store |
nobody stores it (payments, personal documents) |
max-age=N |
fresh for N seconds for the browser |
s-maxage=N |
for the CDN/proxy, overrides max-age |
stale-while-revalidate=N |
return the stale one and refresh in the background |
stale-if-error=N |
serve the stale one if the origin is down |
A good combination for a public catalog:
Cache-Control: public, max-age=30, s-maxage=300, stale-while-revalidate=60, stale-if-error=86400
The browser keeps it for 30 seconds, the CDN for 5 minutes; if the origin goes down, the CDN keeps showing the catalog that's a day old.
Vary matters too: if the response changes based on Accept-Language and you don't set Vary: Accept-Language, a response in Russian gets shown to a user who wants Uzbek. But Vary: Cookie or Vary: User-Agent makes the cache almost useless — too many variants.
In Spring: ResponseEntity.ok().cacheControl(CacheControl.maxAge(30, SECONDS).sMaxAge(300, SECONDS).cachePublic()). And for safety it's better to make the default private, no-store and open up public endpoints explicitly.
Sign up to mark studied questions and save your progress.