REST APIs in Depth · Correctness: Errors, Validation, Concurrency and Caching
HTTP Caching for APIs
Cache-Control, private vs shared caches, CDNs and stale-while-revalidate for API responses.
APIs benefit from HTTP caching too. Public, slowly changing data (catalogs, reference data, configs) can be cached by CDNs with s-maxage and stale-while-revalidate; per-user data should be private (browser only) or no-store when sensitive. Combine max-age with ETags so clients revalidate cheaply. Purge CDN caches by surrogate keys when data changes. GraphQL over POST can't use HTTP caches without persisted GET queries.
Caching policies for API responses
| Response type | Cache-Control | Notes |
|---|---|---|
| Public reference data | public, max-age=300, s-maxage=3600, stale-while-revalidate=600 | CDN + browser |
| Per-user, non-sensitive | private, max-age=0, must-revalidate + ETag | Browser revalidates cheaply |
| Sensitive (tokens, PII) | no-store | Never stored |
| Versioned static (e.g. /v1/countries?rev=42) | public, max-age=31536000, immutable | URL changes when data changes |
| Errors | no-store (or very short) | Avoid caching transient 5xx |
Common pitfalls
- CDN caching responses that vary by Authorization header.
- Long max-age without a purge strategy.
- Caching 5xx responses.
Key points
- public/private/no-store deliberately
- ETags for revalidation
- CDN purge by surrogate keys
Further reading: RFC 9111: HTTP Caching
Practice questions
Can a CDN cache authenticated API responses?
Answer
Only if the response is truly identical for all users with access (and the CDN keys on the relevant auth/tenant dimension); otherwise mark responses private or no-store. Shared caches don't cache requests with Authorization unless explicitly allowed.
What does stale-while-revalidate add?
Answer
Caches may serve a stale response for a window while fetching a fresh one in the background, hiding origin latency and smoothing load.
Open in the app to mark lessons complete, take notes and track your progress.