Frontend System Design · Lesson 15 of 86 · 5 min
HTTP Caching: Cache-Control, ETag, Last-Modified
This is how you explain reducing latency and server load by avoiding unnecessary network requests.
In an interview, you need to show you understand two fundamental caching concepts: freshness and validation. Freshness means the browser can use a cached resource without asking the server. Validation means the browser has to ask the server if its cached copy is still good. Get this right, and you demonstrate a core competency in web performance.
Control freshness with Cache-Control
The Cache-Control response header is the main directive. It tells the browser and any intermediate caches (like a CDN) how to handle a resource.
The most important directive is max-age=<seconds>. This tells the browser how long, in seconds, a resource is "fresh." While it's fresh, the browser will not make a network request for it. It will serve it directly from the disk or memory cache.
Cache-Control: public, max-age=31536000, immutable
For versioned static assets like main.a4b2c1.js, use a long max-age (e.g., one year) and add immutable. The immutable directive tells the browser the file will never change, preventing revalidation requests even after a user hard-refreshes the page. This is the ideal strategy for cache-busted assets.
Other key Cache-Control directives:
private: The response is for a single user and can be stored by their browser, but not by a shared cache like a CDN. Use this for user-specific API responses.public: The response can be stored by any cache. This is the default for most assets.
The trap: Candidates constantly mix up no-cache and no-store.
no-cachedoes not mean "don't cache." It means the browser must revalidate with the server every single time before using the cached version. It's useful for resources like an application's mainindex.htmlfile, where you want the user to always check for a new version but can still benefit from a304 Not Modifiedresponse if nothing has changed.no-storeis the one that means "do not cache this at all." The browser is forbidden from storing the file. Use this for responses containing highly sensitive data.
Validate stale caches with ETag and Last-Modified
When a resource's max-age expires, it becomes "stale." The browser won't use it without first checking if it's still valid. This check is called a conditional request.
The browser sends the server a fingerprint of the version it has, and the server replies with either the new version or a confirmation that the old one is still good.
ETag (Entity Tag) is the preferred mechanism. The server provides an ETag header, which is a unique identifier for the resource's content (often a hash).
ETag: "a4b2c1d3e5f6"
When the browser revalidates, it sends this value back in an If-None-Match request header. If the server's current ETag for the file matches, it sends back a 304 Not Modified status with an empty body. This saves downloading the entire resource again.
Last-Modified is the fallback. The server sends the date the file was last changed. The browser sends this back in an If-Modified-Since header. It's less reliable than ETag because timestamps aren't always granular enough and don't change if a file is regenerated with the same content. If both ETag and Last-Modified are present, ETag takes precedence.
In an interview, explaining the
304 Not Modifiedflow is crucial. It shows you understand that even a "stale" cache can save significant bandwidth. The cost is a small HTTP request for validation, but you avoid re-downloading a potentially large payload.
The complete caching and validation flow
This is the decision process a browser goes through for every subresource on a page.
How to answer "Design a caching strategy"
Structure your answer by resource type. This shows you understand there's no one-size-fits-all solution.
-
Versioned Static Assets (JS/CSS bundles, fonts): "For assets with a fingerprint in the filename, like
app.1a2b3c.js, I'd use an aggressive caching strategy:Cache-Control: public, max-age=31536000, immutable. The longmax-ageandimmutabletell the browser to never request it again. Cache invalidation is handled by changing the filename during the build process, which forces a download." -
Unversioned Static Assets (e.g.,
logo.png): "For a static asset that doesn't have a versioned filename, I'd use a shortermax-age, maybe a few hours:Cache-Control: public, max-age=7200. I would also ensure the server sends anETagheader. This allows the browser to efficiently revalidate after the cache expires." -
Main HTML Document (
index.html): "For the main entry point of a single-page app, I'd useCache-Control: no-cache. This forces the browser to always revalidate with the server, ensuring the user gets the latest HTML which might reference new JS/CSS bundles. If the HTML hasn't changed, the server can just return a304." -
Dynamic API Responses (e.g.,
/api/user/profile): "For authenticated API calls that return user-specific data, I'd useCache-Control: private, no-cache.privateprevents CDNs from caching it, andno-cacheensures the data is revalidated on every request, providing freshness while still allowing304 Not Modifiedresponses for data that hasn't changed."
Code: A server that handles validation
This Node.js/Express example shows a server implementing ETag and Last-Modified for a resource that can be updated. It correctly handles conditional requests and returns 304 Not Modified when appropriate.
import express from 'express';
import crypto from 'crypto';
const app = express();
const PORT = 3001;
let resourceContent = 'Initial content of my resource.';
let lastModifiedTime = new Date();
function generateETag(content: string): string {
const hash = crypto.createHash('md5').update(content).digest('hex');
return `"${hash}"`; // ETags are typically quoted strings
}
app.get('/my-resource', (req, res) => {
const currentETag = generateETag(resourceContent);
const currentLastModified = lastModifiedTime.toUTCString();
// ETag takes precedence
if (req.headers['if-none-match'] === currentETag) {
return res.status(304).send();
}
// Fallback to Last-Modified
const ifModifiedSince = req.headers['if-modified-since'];
if (ifModifiedSince && new Date(ifModifiedSince) >= lastModifiedTime) {
return res.status(304).send();
}
res.setHeader('Cache-Control', 'public, max-age=60');
res.setHeader('ETag', currentETag);
res.setHeader('Last-Modified', currentLastModified);
res.status(200).send(resourceContent);
});
// Endpoint to simulate updating the resource
app.post('/update-resource', (req, res) => {
resourceContent = `Updated content at ${new Date().toISOString()}`;
lastModifiedTime = new Date();
res.status(200).send('Resource updated successfully.');
});
app.listen(PORT, () => {
console.log(`Server at http://localhost:${PORT}`);
console.log(`1. Access http://localhost:${PORT}/my-resource`);
console.log(`2. Refresh to see a 304 response.`);
console.log(`3. To update: curl -X POST http://localhost:${PORT}/update-resource`);
});
Try it
Open your browser's DevTools to the Network tab. Visit a content-heavy site like a news outlet. Find a request for a static image. Inspect its response headers for Cache-Control, ETag, and Last-Modified. Refresh the page and find the same request; observe if the status is 304 or 200 (from disk cache).
Next: Browser-Level Caching Mechanisms
Lock it in — apply this lesson under interview conditions.