CS › Web-Network

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.

Designing HTTP caching with Cache-Control and ETag headers

HTTP caching lets browsers and CDNs reuse responses to cut latency and protect your origin servers. This post covers Cache-Control directives under RFC 9111, ETag conditional requests, how ShallowEtagHeaderFilter actually 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.

DirectiveScopeCore behaviorTypical use case
max-age=NAllReuse a fresh copy for N secondsStatic assets, short-lived read APIs
s-maxage=NShared cacheOverrides max-age on CDNs/proxiesLong CDN TTL with short browser TTL
no-cacheAllStore, but revalidate with origin every timeindex.html, dynamic APIs
no-storeAllNever store anywherePayments, tokens, sensitive PII
publicShared cacheExplicitly permits shared cachingPublic catalogs, static files
privateBrowser onlyForbids shared caches, allows browser cacheUser profiles, personalized APIs
immutableBrowser onlySkips reload revalidation while freshContent-hashed JS/CSS bundles
stale-while-revalidate=NAllServes stale copy for N seconds while refreshing asyncLatency-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 for Range requests and If-Match optimistic 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 for If-None-Match cache 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 public or s-maxage on 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.

  1. Leaking personalized responses into shared caches: Endpoints backed by session cookies or Authorization headers (like /api/me) must return private, no-cache. Sensitive responses like payment receipts or OAuth tokens need no-store.
  2. Missing Vary headers: If your response changes based on Accept-Encoding (gzip vs. Brotli), Accept-Language, or Origin, omitting Vary makes the CDN serve the wrong compressed payload or a mismatched CORS header to other clients.
  3. Long max-age on unhashed static files: Attaching max-age=31536000, immutable to a fixed filename like app.js traps users on old code after a release. Reserve long-lived immutable caching for content-hashed filenames (app.8f3a2c.js), and serve index.html with no-cache.

HTTP caching checklist

  • Mark personalized endpoints private, no-cache and sensitive endpoints no-store.
  • Set Vary whenever responses differ by encoding, language, or Origin.
  • Use explicit version-based ETag + checkNotModified() instead of relying on ShallowEtagHeaderFilter for origin load relief.
  • Apply immutable only to content-hashed asset URLs, never to index.html.
  • Test 200 and 304 responses directly with curl -i before rolling out CDN rules.

References

This post is licensed under CC BY 4.0 by the author.