Designing HTTP caching with Cache-Control and ETag headers
How private browser caches and CDN shared caches work under RFC 9111, key Cache-Control directives, ETag 304 revalidation, and Spring Boot caching pitfalls.
HTTP caching lets browsers and CDNs reuse responses to cut latency and protect your origin servers. This post covers
Cache-Controldirectives under RFC 9111,ETagconditional requests, howShallowEtagHeaderFilteractually works in Spring Boot, and the production caching bugs I watch out for.
Reference environment: RFC 9111 (HTTP Caching), Spring Boot 3.x / Kotlin 1.9 / Java 21
Private browser caches vs. shared CDN caches
HTTP caches operate in two distinct tiers based on who can read the stored response: private caches and shared caches. A private cache lives inside a single user’s browser and holds personalized responses meant only for that session. A shared cache sits at a CDN edge or reverse proxy (such as CloudFront, Cloudflare, or Nginx) and serves the same cached copy to many users.
When a browser cache hits, the client skips the network request completely. When the browser copy expires but the CDN holds a fresh copy, the edge responds without touching your application servers or database.
Every cache policy balances freshness against origin load. Long TTLs keep origin traffic flat, but updates take longer to reach users. Short TTLs surface changes faster, but drop hit ratios. That’s why I split cache headers by two questions: how often the resource changes, and whether the response varies per user.
Key Cache-Control directives and when to avoid them
Cache-Control replaced the legacy Expires header, which broke easily when client and server clocks drifted. It expresses relative lifetimes, storage scope, and revalidation behavior in one header.
| Directive | Scope | Core behavior | Typical use case |
|---|---|---|---|
max-age=N | All | Reuse a fresh copy for N seconds | Static assets, short-lived read APIs |
s-maxage=N | Shared cache | Overrides max-age on CDNs/proxies | Long CDN TTL with short browser TTL |
no-cache | All | Store, but revalidate with origin every time | index.html, dynamic APIs |
no-store | All | Never store anywhere | Payments, tokens, sensitive PII |
public | Shared cache | Explicitly permits shared caching | Public catalogs, static files |
private | Browser only | Forbids shared caches, allows browser cache | User profiles, personalized APIs |
immutable | Browser only | Skips reload revalidation while fresh | Content-hashed JS/CSS bundles |
stale-while-revalidate=N | All | Serves stale copy for N seconds while refreshing async | Latency-tolerant feeds and lists |
The directive pair I see misconfigured most often is no-cache vs. no-store. Under RFC 9111, no-cache does not disable caching. It tells the browser or CDN that it may store the response, as long as it sends a conditional revalidation request before reusing it. If a response contains sensitive data that must never touch disk or memory caches, use no-store.
Combining max-age and s-maxage is also handy when you control CDN invalidation. Setting Cache-Control: public, max-age=10, s-maxage=300 keeps browsers fresh within 10 seconds while letting the CDN shield your origin for 5 minutes (and you can purge the CDN immediately on publish).
When not to rely on HTTP caching: Don’t use shared HTTP caches for real-time inventory counts, account balances, or authenticated endpoints where a stale or cross-user read causes data corruption. For high-churn internal data that still needs low latency, handle caching inside the backend with a two-tier Caffeine and Redis cache where you control exact invalidation.
ETag and 304 conditional requests
Once a cached entry becomes stale, the client doesn’t have to download the full response body again if nothing changed on the server. Instead, it sends a conditional request using a validator—either ETag (matched via If-None-Match) or Last-Modified (matched via If-Modified-Since). If the resource matches, the server returns 304 Not Modified with an empty body.
RFC 9111 favors ETag over Last-Modified because Last-Modified only has one-second resolution and often changes spuriously when a CI/CD pipeline redeploys identical files with new timestamps.
sequenceDiagram
participant Client as Browser
participant CDN as CDN Cache
participant Origin as Origin Server
Client->>CDN: GET /api/products/42
CDN->>Origin: GET /api/products/42
Origin-->>CDN: 200 OK, ETag v1
CDN-->>Client: 200 OK, ETag v1
Note over Client,CDN: Revalidate after max-age expires
Client->>CDN: GET + If-None-Match v1
CDN-->>Client: 304 Not Modified
ETags come in two strengths:
- Strong ETag (
"v42-9f86d08"): Guarantees byte-for-byte equivalence. Required forRangerequests andIf-Matchoptimistic locking on writes. - Weak ETag (
W/"v42"): Means the representations are semantically equivalent even if bytes differ (for example, gzip vs. Brotli compression). Weak ETags work fine forIf-None-Matchcache revalidation.
Implementing ETag in Spring Boot and ShallowEtagHeaderFilter
In Spring Boot, the cleanest way to save both bandwidth and server CPU is to return CacheControl and eTag on ResponseEntity and short-circuit with WebRequest.checkNotModified() before serializing the full DTO.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// src/main/kotlin/com/example/catalog/ProductController.kt
package com.example.catalog
import java.util.concurrent.TimeUnit
import org.springframework.http.CacheControl
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.context.request.WebRequest
@RestController
@RequestMapping("/api/products")
class ProductController(
private val productQueryService: ProductQueryService,
) {
@GetMapping("/{id}")
fun getProduct(@PathVariable id: Long, webRequest: WebRequest): ResponseEntity<ProductResponse> {
// Lightweight version lookup (e.g., updated_at or entity version column)
val etag = "\"product-$id-v${productQueryService.findVersion(id)}\""
val cacheControl = CacheControl.maxAge(10, TimeUnit.SECONDS)
.cachePublic()
.sMaxAge(60, TimeUnit.SECONDS)
if (webRequest.checkNotModified(etag)) {
return ResponseEntity.status(304)
.cacheControl(cacheControl)
.eTag(etag)
.build()
}
return ResponseEntity.ok()
.cacheControl(cacheControl)
.eTag(etag)
.body(productQueryService.findDetail(id))
}
}
Many teams register Spring’s ShallowEtagHeaderFilter globally for convenience, but you need to know what it does under the hood. The filter wraps the response in a ContentCachingResponseWrapper, lets the controller run in full, buffers the entire serialized response body in memory, hashes it with MD5, and only then compares it against If-None-Match to swap the status to 304.
In other words, ShallowEtagHeaderFilter saves network bandwidth, not origin compute. Your database queries, JSON serialization, and heap buffering still happen on every request. If your goal is reducing origin load, use an explicit version-based ETag like the controller above, or pair it with CDN and Redis caching.
You can verify the 200-to-304 transition locally with curl:
1
2
3
4
5
# 1. Initial request (returns 200 OK with ETag)
curl -i http://localhost:8080/api/products/42
# 2. Conditional revalidation (returns 304 Not Modified with no body)
curl -i -H 'If-None-Match: "product-42-v3"' http://localhost:8080/api/products/42
Common HTTP caching pitfalls and checklist
Warning: Putting
publicors-maxageon an authenticated, personalized endpoint can cause a CDN shared cache to serve User A’s response to User B. That’s a severe data leak, not just a stale cache bug.
- Leaking personalized responses into shared caches: Endpoints backed by session cookies or
Authorizationheaders (like/api/me) must returnprivate, no-cache. Sensitive responses like payment receipts or OAuth tokens needno-store. - Missing
Varyheaders: If your response changes based onAccept-Encoding(gzip vs. Brotli),Accept-Language, orOrigin, omittingVarymakes the CDN serve the wrong compressed payload or a mismatched CORS header to other clients. - Long
max-ageon unhashed static files: Attachingmax-age=31536000, immutableto a fixed filename likeapp.jstraps users on old code after a release. Reserve long-livedimmutablecaching for content-hashed filenames (app.8f3a2c.js), and serveindex.htmlwithno-cache.
HTTP caching checklist
- Mark personalized endpoints
private, no-cacheand sensitive endpointsno-store. - Set
Varywhenever responses differ by encoding, language, orOrigin. - Use explicit version-based
ETag+checkNotModified()instead of relying onShallowEtagHeaderFilterfor origin load relief. - Apply
immutableonly to content-hashed asset URLs, never toindex.html. - Test
200and304responses directly withcurl -ibefore rolling out CDN rules.