How do HTTP caching headers (Cache-Control, ETag) set by an ASP.NET Core API interact with browser and CDN caching, complementing server-side caching?
Short answer
Cache-Control directives (max-age, public/private) tell browsers and CDNs how long a response can be reused without re-requesting, while ETag provides a version identifier clients can send via If-None-Match, letting the server respond with a lightweight 304 Not Modified if…
Advertisement
AModel answer
Cache-Control directives (max-age, public/private) tell browsers and CDNs how long a response can be reused without re-requesting, while ETag provides a version identifier clients can send via If-None-Match, letting the server respond with a lightweight 304 Not Modified if unchanged -- these HTTP-layer mechanisms reduce load even before a request reaches your application's server-side caching logic, forming a complementary, multi-layered caching strategy from browser to CDN to server.
[HttpGet("{id}")]
public IActionResult GetProduct(int id) {
var product = _service.GetProduct(id);
var etag = ComputeETag(product);
if (Request.Headers.IfNoneMatch == etag) return StatusCode(304);
Response.Headers.ETag = etag;
Response.Headers.CacheControl = "public, max-age=300";
return Ok(product);
}Real-world example
A public API serving rarely-changing reference data sets long Cache-Control max-age values and ETags, letting a CDN and client browsers serve repeat requests without the request ever reaching the origin server or its own caching layers.
Likely follow-ups
- How does a CDN's cache differ from browser caching in terms of who benefits?
- What's the risk of overly aggressive Cache-Control settings for frequently-changing data?
Related topics