CDNs and HTTP Caching: Cache-Control, Versioned Assets, Edge Caching, and Cache Attacks
System Design series · Part 2 From one machine to many (4 of 4)
- Vertical Scaling, Horizontal Scaling, and Stateless Services: Where Sessions, Files, Scheduled Jobs, and Local State Should Go
- Load Balancing in Depth: L4 and L7, Algorithms, Health Checks, and Connection Draining
- Caching in Depth: Hit Ratio Math, Write-Order Races, Penetration, Breakdown, Avalanche, and Multi-Level Caches
- CDNs and HTTP Caching: Cache-Control, Versioned Assets, Edge Caching, and Cache Attacks
System Design series Part 2-4 | Previous: Caching in Depth | Next: SQL vs NoSQL | Series map
Read first: Part 2-3 Caching in Depth.
Scenario and problem
Your e-commerce site’s origin is in Taiwan. After you start selling overseas, these reports come in one after another:
- Users in US West wait more than 3 seconds for the home page to open; in Taiwan it takes only 0.8 seconds
- During a big sale, the 2.4 Gbps peak image bandwidth estimated in Napkin Math for Capacity Estimates really shows up, and the origin’s network card and the cloud traffic bill both max out
- After every deploy, a small group of users always sees a blank page, and the console shows JavaScript failing to load
- The worst one: to lower the origin’s load, someone made all of
/api/**cacheable, and then user A opened “My orders” and saw user B’s orders
- A 3-second home page in US WestThe origin is in Taiwan. Every round trip from a US West user has to cross the Pacific, and the home page takes more than 3 seconds; Taiwan users need only 0.8 seconds.
- Image bandwidth in the big saleDuring the big sale the peak image bandwidth really reaches 2.4 Gbps, all served straight from the origin, and the network card and the cloud traffic bill both max out.
- A blank page after a deployThe deploy switched the HTML first and uploaded the new JS afterwards. Users who got the new HTML in that gap tried to load a file that did not exist yet, and saw a blank page.
- Seeing someone else's ordersTo lower the origin's load, all of /api/** was made cacheable. B opens "My orders" and the CDN stores the response; A opens the same URL and gets B's orders.
The first two are problems of distance and bandwidth, exactly what CDNs were made for. The last two are problems of caching semantics: what can be cached by whom, for how long, and how it gets updated. This post covers both.
The simplest approach and its limits
The simplest approach is to have the origin serve every file directly and let browsers cache them with Cache-Control. Its limits:
- Distance cannot be optimized away: as Part 1 worked out, the RTT from Taipei to US West is about 130–160 ms. The TCP and TLS handshakes plus the first request take at least 3 RTTs, so the first byte alone takes close to 0.5 seconds
- Every user’s first visit goes to the origin: the browser cache only helps “the same user’s second visit”, so all the new users who flood in during a big sale hit the origin
- Bandwidth is concentrated at one point: all 2.4 Gbps goes out from the origin; add the attack traffic during a DDoS, and a single data center can hardly take it
Core mechanism
How a CDN works
flowchart LR
U1[US West user] --> E1["Edge node (Los Angeles)"]
U2[Tokyo user] --> E2["Edge node (Tokyo)"]
U3[Taiwan user] --> E3["Edge node (Taipei)"]
E1 -- miss --> S["Origin Shield<br/>(regional cache tier)"]
E2 -- miss --> S
E3 -- miss --> S
S -- miss --> O[(Origin<br/>Taiwan)]
- Route to the nearest node: through DNS or Anycast, users connect to the geographically nearest edge node (PoP)
- Edge caching: on a hit, the node responds directly, without going through the origin at all
- Origin Shield: when edge nodes miss, they all ask the same regional cache tier first, instead of each going to the origin. Without this tier, when a new file goes live, hundreds of nodes around the world each miss, and the origin receives hundreds of requests
- Request collapsing: when many requests for the same file miss at the same time, the node sends only one request upstream and the others wait for its result. This is the single-flight from Caching in Depth, only it happens at the CDN
The bandwidth math: assume a byte hit ratio of 95%; of 2.4 Gbps of image traffic, only 2.4 × 5% = 120 Mbps reaches the origin. As in the caching post, the number to watch is the miss ratio: raising the hit ratio from 95% to 99% cuts origin bandwidth by another factor of 5.
Even when the content cannot be cached, a CDN still speeds things up. The user handshakes with the edge node (RTT about 10 ms), while the edge node keeps an already established, continuously reused connection to the origin. An estimate for a US West user calling an API that cannot be cached:
| Direct to origin | Through a CDN | |
|---|---|---|
| TCP + TLS 1.3 handshake | 2 × 150 = 300 ms | 2 × 10 = 20 ms |
| Send the request, get the response | 150 ms | 10 + (reused edge-to-origin connection) 150 = 160 ms |
| First byte at about | 450 ms | 180 ms |
(Excludes DNS and server processing time; RTTs are order-of-magnitude estimates.)
HTTP caching semantics: fresh, stale, and revalidation
RFC 9111 defines the rules shared by all HTTP caches (browsers, CDNs, reverse proxies). There are only two core ideas:
- Fresh: the response’s age has not exceeded its freshness lifetime, so it can be used directly without asking the origin. The freshness lifetime is taken in this order of priority:
s-maxage(shared caches only) >max-age>Expires> heuristic estimate - Stale: past the freshness lifetime, it must in principle be revalidated with the origin before it can be used
Revalidation relies on conditional requests: the cache sends the ETag of the version it holds, and if the origin decides the content has not changed, it returns only a 304 Not Modified with no body.
sequenceDiagram
participant B as Browser
participant C as CDN
participant O as Origin
B->>C: GET /api/products/42
C->>O: GET /api/products/42
O-->>C: 200, ETag "7", Cache-Control: s-maxage=60
C-->>B: 200 (the CDN stores it and answers directly for 60 s)
Note over C: Stale after 60 s
B->>C: GET /api/products/42
C->>O: GET, If-None-Match: "7"
O-->>C: 304 Not Modified (no body)
C-->>B: 200 (from the cached copy, the 60 s timer restarts)
A 304 saves bandwidth and the origin’s cost of producing the response body, but it does not save a round trip. So to be really fast, you still need a long enough freshness lifetime.
Cache-Control directives
| Directive | Meaning | Common misconception |
|---|---|---|
max-age=N |
Fresh for N seconds | — |
s-maxage=N |
Applies only to shared caches (CDNs, proxies) and takes precedence over max-age |
— |
public |
Shared caches may store it, even when the request carries Authorization |
— |
private |
May be stored only in the user’s own browser | Thought to stop browser caching |
no-cache |
May be stored, but must be validated with the origin before every use | Thought to mean “do not cache” |
no-store |
No cache may store it | — |
must-revalidate |
Once stale, it must be validated; using the old copy directly is not allowed | — |
immutable (RFC 8246) |
The content will never change while fresh, so it needs no validation even when the user reloads | — |
stale-while-revalidate=N (RFC 5861) |
For N seconds after going stale, the old copy can be served while it is updated in the background | — |
stale-if-error=N (RFC 5861) |
When the origin returns an error, old data up to N seconds stale can still be used | — |
stale-while-revalidate corresponds to “logical expiry” in the caching post, and stale-if-error lets the CDN keep serving while the origin has a brief outage. Together they do at the CDN layer what the caching post needed your own code for. Actual support varies by CDN, so check each vendor’s documentation.
Cache key: what counts as “the same thing”
By default a CDN uses “host name + path + query string” as the cache key. Two requests with the same key get the same cached copy. Things to watch in the design:
- Irrelevant query parameters:
?utm_source=fband?utm_source=lineare treated as two different objects, which breaks the hit ratio into pieces. In the CDN settings, keep only the parameters that actually affect the content - The
Varyheader:Vary: Accept-Encodingmeans separate copies per compression method, which is reasonable.Vary: User-AgentorVary: Cookieis almost the same as one copy per user, and the hit ratio approaches zero - Inputs that are not in the key but affect the response: this is the root of cache poisoning; see the security section later
Versioning: caches you never have to clear
The hardest part of caching is not “storing it” but “getting everyone the new version after a change”. The most reliable approach is to tie the content to the URL:
| Resource | URL | Cache-Control |
|---|---|---|
| JS, CSS, images | File name contains a content hash: app.3f9a1c.js |
public, max-age=31536000, immutable |
| HTML entry point | Fixed: /index.html |
no-cache (validated every time, 304 if unchanged) |
Change the content and the hash changes, so the URL changes. The cache for the old URL is always correct, and the new URL has never been cached, so there is no need to clear the cache at all. HTML is the only fixed entry point and is validated every time, so after a deploy, the user’s next load gets HTML that references the new files.
The blank page in scenario 3 came from deploying in the wrong order:
flowchart TB
A["1. Upload the new JS and CSS<br/>(new file names, live site unaffected)"] --> B["2. Switch the HTML<br/>(starts referencing the new file names)"]
B --> C["3. Keep the old files for at least a few days<br/>(users who still have the old page open<br/>need them when lazy loading)"]
Switch the HTML before uploading the assets, and users get HTML that references files that do not exist. Delete the old files during a deploy, and users who still have an old tab open fail when the single-page app switches pages and lazy-loads code.
Purging the cache is only an emergency measure
Every CDN offers a purge API, but it should not be part of your everyday deploy process:
- It takes time to take effect across nodes worldwide, anywhere from seconds to minutes, and there are often rate or quantity limits
- It cannot clear browser caches: content already stored in users’ browsers whose
max-agehas not run out is completely beyond the CDN’s reach
So use purge only in emergencies where “the content is wrong and must come down now”; everyday updates rely on versioned URLs and sensible TTLs.
APIs can go on a CDN too: micro-caching
Popular public APIs that are the same for every user (product details, leaderboards, campaign page data) can also be cached by the CDN, just with a very short TTL. Suppose an API gets 10,000 requests a second:
Cache-Control: public, max-age=0, s-maxage=1, stale-while-revalidate=5- The browser does not cache it (
max-age=0) and asks the CDN every time - The CDN caches it for 1 second. With origin shield and request collapsing, the origin gets roughly 1 request a second instead of 10,000
- Data is at most about 1 second old (plus the background update time of
stale-while-revalidate)
As long as the business can accept 1 second of delay, this approach has a very high return on investment. Flash sale stock counts and live leaderboards can be handled this way, while the write requests that actually decrement stock do not go through the cache.
Comparing options
Ways to update cached content
| Method | How fast it takes effect | Can it update browser caches? | Good for |
|---|---|---|---|
| Wait for the TTL to expire | Slow, up to one TTL | Yes (naturally, after expiry) | Content that can tolerate delay |
| Purge | Seconds to minutes | No | Emergency takedowns |
| Versioned URLs | Immediate (new URL) | Yes (the new URL is not in any cache) | Static assets, the default approach |
| Short TTL + revalidation | One short TTL | Yes | HTML entry points, micro-cached APIs |
Push and pull
| Pull | Push | |
|---|---|---|
| How | The node goes back to the origin only on a miss | Upload files to the CDN in advance |
| Pros | Simple to set up, stores only what someone actually requests | Hit from the very first request; the origin can stay completely private |
| Cons | The first request at each node goes back to the origin | You manage uploads and deletions yourself |
| Good for | The vast majority of websites | Distributing large files (installers, game update packages) |
A common compromise in practice: put static assets in object storage (S3 and the like) as the origin, and have the CDN fetch from it in pull mode. Object storage can take heavy reads on its own, and there are no servers to manage.
What each cache layer can store
| Layer | Shared by | Can it store personalized content? | Controlled by |
|---|---|---|---|
| Browser | A single user | Yes (private) |
Cache-Control |
| CDN | All users | No | Cache-Control, s-maxage, CDN settings |
| Reverse proxy (Nginx) | All users | No | Same as above |
| Application cache (Redis) | All instances | Yes, but the key must include the user’s identity | Code |
In Java
1. Static assets
Modern frontends mostly have a bundler (such as Vite) generate hashed file names and deploy straight to object storage plus a CDN, with Spring Boot handling only the API. If Spring Boot renders the pages on the server (Thymeleaf), you can have Spring add content hashes to static assets:
spring:
web:
resources:
chain:
strategy:
content:
enabled: true
paths: "/**" # /css/app.css becomes /css/app-2a2d595e6ed9.css
cache:
cachecontrol:
max-age: 365d
cache-public: trueThymeleaf and FreeMarker automatically rewrite asset links in templates to the hashed versions (through ResourceUrlEncodingFilter). The cachecontrol properties in Spring Boot 4.1 have no immutable; if you need it, set it yourself in a WebMvcConfigurer.
2. Public APIs: Cache-Control plus ETag
@RestController
@RequestMapping("/api/products")
public class ProductController {
private final ProductDetailQuery productQuery;
public ProductController(ProductDetailQuery productQuery) {
this.productQuery = productQuery;
}
@GetMapping("/{id}")
public ResponseEntity<ProductDetail> detail(@PathVariable long id) {
ProductDetail product = productQuery.findDetail(id);
if (product == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(Duration.ofSeconds(10)) // browser: 10 s
.sMaxAge(Duration.ofSeconds(60)) // CDN: 60 s
.staleWhileRevalidate(Duration.ofSeconds(30))
.staleIfError(Duration.ofHours(1))
.cachePublic())
.eTag(String.valueOf(product.version())) // quotes are added if missing
.body(product);
}
}The headers it actually produces:
Cache-Control: max-age=10, public, s-maxage=60, stale-if-error=3600, stale-while-revalidate=30
ETag: "7"Use the data’s version number for the ETag (for example a JPA @Version field), not a hash of the response body. That way every instance computes the same ETag for the same data, and no matter which origin instance the CDN revalidates against, the result is the same. When a ResponseEntity carries an ETag, Spring MVC automatically compares it with the request’s If-None-Match and returns 304 if they match.
The code above still loads the full record first. If producing the response is expensive (a report, for example), you can query only the version number first and return 304 right away if it has not changed:
@GetMapping("/api/stores/{id}/sales-report")
public ResponseEntity<SalesReport> report(@PathVariable long id, WebRequest request) {
String eTag = String.valueOf(reportQuery.currentVersion(id)); // only the version number, cheap
if (request.checkNotModified(eTag)) {
return null; // 304 already set, no report built
}
return ResponseEntity.ok().eTag(eTag).body(reportQuery.build(id));
}Spring also has ShallowEtagHeaderFilter, which hashes the entire response body into an ETag. It saves bandwidth but not server work, because the response still has to be fully produced once before it can be hashed.
3. Personalized APIs: forbid caching explicitly
@GetMapping("/api/me/orders")
public ResponseEntity<List<OrderSummary>> myOrders(Principal principal) {
return ResponseEntity.ok()
.cacheControl(CacheControl.noStore()) // personal data: no layer may store it
.body(orderQuery.findByMember(Long.parseLong(principal.getName())));
}By default Spring Security adds Cache-Control: no-cache, no-store, max-age=0, must-revalidate to every response, but as soon as the application sets Cache-Control itself, Spring Security no longer overwrites it. This is by design, so that static assets can be cached. In other words, this is exactly how scenario 4 happened: for performance, someone set public, max-age=60 for all of /api/** in an interceptor, and Spring Security’s protection disappeared along with it.
There is also an API trap: noCache() is a static method, so CacheControl.empty().cachePrivate().noCache() creates a brand-new object, the earlier private is lost, and the output is only no-cache. Write CacheControl.noCache().cachePrivate() instead, and the output is no-cache, private. Compiling with -Xlint:static produces a warning for the former.
4. Checking whether the CDN hits
Look at the response headers with curl -sI <url>:
| Header | Meaning |
|---|---|
Age |
How many seconds this response has been in the cache; missing or always 0 usually means no hit |
X-Cache |
CloudFront marks it Hit from cloudfront, Miss from cloudfront, or RefreshHit from cloudfront (validated successfully after expiry) |
cf-cache-status |
Cloudflare’s hit status, such as HIT, MISS, EXPIRED |
Cache-Control, ETag |
Confirm that the directives the origin sends are what you expect |
Pitfalls and gotchas
- Treating
no-cacheas “do not cache”: it means “may be stored, but must be validated every time”. To really forbid storing, useno-store - No
Cache-Controldoes not mean it will not be cached: RFC 9111 lets caches estimate a freshness lifetime fromLast-Modified(a common approach is 10% of the time since the last modification); CDNs also have their own default TTLs, for example CloudFront’s CachingOptimized policy caches for 24 hours by default when the origin does not specify one. Every response should declare it explicitly - A long
max-ageon HTML: after a deploy, users keep the old HTML and reference the old assets forever. Always useno-cachefor HTML - Deleting old asset versions during a deploy: users who still have an old tab open fail when lazy loading
- Putting purge in the deploy process: slow to take effect, limited in number, and it cannot clear browser caches
- Error responses get cached: CDNs also briefly cache errors by default (CloudFront caches 4xx and 5xx for 10 seconds by default). A 1-second blip at the origin can show users 10 seconds of errors; and when a file is requested before it has finished uploading, the 404 gets cached too
Vary: User-Agent,Vary: Cookie: the hit ratio approaches zero- CORS responses without
Vary: Origin:Access-Control-Allow-Originis generated from the request’s origin, so once the version for domain A is cached, requests from domain B are blocked by the browser because the origin does not match - ETags that differ per instance: different instances compute different ETags, so a 304 never happens
Security
- Web cache deception: the CDN is configured to “cache every path ending in
.css”, while the origin still returns the profile page for/account/profile/x.css. An attacker lures a victim into clicking that URL, the profile page is cached by the CDN as if it were CSS, and the attacker then requests the same URL and gets the victim’s data. Defense: decide whether to cache based only on the origin’sCache-Control, not on the file extension; always useno-storefor personal pages; have the origin return 404 for paths it does not recognize. Spring MVC turns off suffix pattern matching by default from 5.3 and trailing slash matching from 6.0, which also helps reduce cases of “one handler answering too many kinds of paths” - Cache poisoning: the origin builds response content from a header that is not part of the cache key, for example building an absolute script URL from
X-Forwarded-Host. An attacker sends one request with a malicious host, and the poisoned response is cached and served to every user. Defense: build content only from a fixed, configured domain and never trust the host a request brings; put every input that affects the response into the cache key. Theserver.forward-headers-strategymentioned in Load Balancing in Depth makes the application trustX-Forwarded-Host, so the CDN and the LB must overwrite any such headers the client sends itself - Personalized responses get cached: every API that requires login must explicitly send
privateorno-store; do not rely on the CDN’s default behavior. Configure the CDN side too: do not cache when the request carriesAuthorizationor a session cookie - The origin gets hit directly: once the origin’s IP leaks, attackers can bypass the CDN’s cache, WAF, and rate limiting and take the origin down directly. Allow only the CDN’s sources at the origin (for example CloudFront’s managed prefix list), and for S3 use Origin Access Control so that only the CDN can read it
- Paid or private content: use the CDN’s signed URLs or signed cookies with a short validity period, rather than relying on URLs being hard to guess
When to use it, and when not to
- A good fit for a CDN: users spread across multiple regions, static assets or images and video making up most of the bandwidth, a need to absorb heavy traffic or DDoS, popular public APIs that can be micro-cached
- Limited benefit: internal systems used in a single region only, services that are almost entirely personalized content (they still benefit from terminating TLS at the edge, but caching does not help), APIs that must return the latest data every time
- When to re-evaluate: the CDN hit ratio is low (check the cache key and
Vary); the origin’s egress traffic cost keeps rising; latency metrics in remote regions lag noticeably behind
References
- RFC 9111, HTTP Caching: https://www.rfc-editor.org/rfc/rfc9111
- RFC 9110, HTTP Semantics (Conditional Requests, ETag): https://www.rfc-editor.org/rfc/rfc9110
- RFC 8246, HTTP Immutable Responses: https://www.rfc-editor.org/rfc/rfc8246
- RFC 5861, HTTP Cache-Control Extensions for Stale Content: https://www.rfc-editor.org/rfc/rfc5861
- MDN — HTTP caching: https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Caching
- Spring Framework Reference — HTTP Caching: https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-caching.html
- Spring Boot Reference — Static Content: https://docs.spring.io/spring-boot/reference/web/servlet.html
- Spring Security Reference — Security HTTP Response Headers: https://docs.spring.io/spring-security/reference/features/exploits/headers.html
- Amazon CloudFront Developer Guide: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/
- Omer Gil, “Web Cache Deception Attack”, Black Hat USA 2017
- James Kettle, “Practical Web Cache Poisoning”, PortSwigger Research, 2018: https://portswigger.net/research/practical-web-cache-poisoning
- Further interactive diagrams: Dilum Sanjaya, System Design — an interactive course: https://designed-to-scale.vercel.app/
Comments