Caching API Responses with Cache-Control
Learn how to set appropriate Cache-Control headers for REST API endpoints, balancing data freshness with server load reduction and response speed.
Detailed Explanation
API Response Caching Strategies
API responses vary widely in how cacheable they are. The key is matching the Cache-Control header to the data's change frequency and sensitivity.
Public API Data (Same for All Users)
Cache-Control: public, max-age=60, s-maxage=300, stale-while-revalidate=30
Example: Product catalog, blog posts list, public search results
- Browser caches for 1 minute
- CDN caches for 5 minutes (instant purge available)
- 30-second SWR window for seamless transitions
Authenticated User Data
Cache-Control: private, max-age=0, must-revalidate
Example: User profile, account settings, order history
- Only browser can cache (private)
- Always revalidate before serving
- Pair with ETag for efficient 304 responses
Rapidly Changing Data
Cache-Control: no-cache
Example: Real-time notifications, unread message count
- Always check with origin before serving
- Benefits from 304 responses when data hasn't changed
Sensitive Data
Cache-Control: no-store
Example: Payment information, password reset tokens
- Never stored in any cache
- Full response on every request
Pagination and Filtering
Cache-Control: public, max-age=300
Vary: Accept, Accept-Encoding
For APIs that vary by query parameters, ensure the Vary header is set correctly so caches don't serve the wrong variant.
API Versioning and Cache
When you version your API (v1, v2), different versions can have different caching strategies. Older, stable versions might use longer cache times, while newer versions use shorter times during their stabilization period.
Use Case
A headless CMS API serves product data to 50 e-commerce storefronts. Setting 'public, max-age=60, s-maxage=600, stale-while-revalidate=60' on the /api/products endpoint means the CDN handles 99% of requests. The origin server goes from handling 10,000 req/s to fewer than 100 req/s, reducing infrastructure costs by 90% while ensuring products are never more than 11 minutes stale.