How do caching and the ETag / Cache-Control headers work in REST APIs?
How HTTP caching works in REST APIs: Cache-Control freshness, ETag validation, If-None-Match, and 304 Not Modified to cut latency and bandwidth.
Expected Interview Answer
HTTP caching lets clients and intermediaries reuse previous REST responses instead of re-fetching them, controlled by Cache-Control (how long and where a response may be cached) and ETag (a validator used to check whether a cached copy is still fresh).
Cache-Control directives like max-age, no-cache, private, and public set freshness and scope. An ETag is a fingerprint of the resource; the client stores it and later sends If-None-Match, so the server can return 304 Not Modified with no body when nothing changed. This distinguishes strong caching (serve straight from cache until it expires) from validation (revalidate cheaply with a conditional request), cutting bandwidth and latency.
- Reduces latency by serving from cache
- Saves bandwidth via empty 304 responses
- Lowers server and database load
- Improves perceived performance for users
- Keeps data fresh through conditional validation
AI Mentor Explanation
Think of a printed scorecard you keep in your pocket. As long as no wicket has fallen, you trust your copy and do not ask the scorer again — that is max-age freshness. When you do check, you just ask 'has anything changed since my last score?' and the scorer nods without rewriting the whole card. An ETag is that quick change-check: the server replies 304 'nothing new' instead of resending the full scorecard.
Step-by-Step Explanation
Step 1
Set Cache-Control
Choose directives like max-age, public/private, and no-cache to define freshness and where caching is allowed.
Step 2
Generate an ETag
The server computes a fingerprint (hash or version) of the resource and returns it in the ETag header.
Step 3
Client stores the response
The browser or cache saves the body plus the ETag and honours max-age before reusing it.
Step 4
Revalidate conditionally
After expiry the client sends If-None-Match with the stored ETag to ask if the copy is still valid.
Step 5
Return 304 or 200
If unchanged the server replies 304 Not Modified with no body; otherwise it sends fresh 200 content and a new ETag.
What Interviewer Expects
- Difference between freshness (max-age) and validation (ETag)
- Knows the If-None-Match / 304 Not Modified flow
- Understands common Cache-Control directives
- Can explain strong vs weak ETags at a high level
- Knows caching reduces latency and bandwidth
Common Mistakes
- Confusing no-cache with no-store
- Assuming ETag alone caches without Cache-Control freshness
- Marking user-specific responses as public instead of private
- Forgetting that 304 responses must carry no body
- Never invalidating caches after the resource changes
Best Answer (HR Friendly)
“Caching lets an app reuse a previous API response instead of downloading it again. Cache-Control says how long a copy stays fresh, and the ETag is a quick fingerprint the app sends to ask 'has this changed?' — if not, the server replies 'nothing new,' saving time and data.”
Code Example
const crypto = require('crypto')
app.get('/api/article/:id', (req, res) => {
const article = getArticle(req.params.id)
const body = JSON.stringify(article)
const etag = crypto.createHash('md5').update(body).digest('hex')
res.set('Cache-Control', 'private, max-age=60')
res.set('ETag', etag)
if (req.headers['if-none-match'] === etag) {
return res.status(304).end() // not modified, no body
}
res.type('application/json').send(body)
})Follow-up Questions
- What is the difference between no-cache and no-store?
- How do strong and weak ETags differ?
- When would you use Last-Modified / If-Modified-Since instead of ETag?
- What does the private directive mean and when do you use it?
- How do you invalidate or bust a cache after an update?
MCQ Practice
1. What does a 304 Not Modified response contain?
A 304 carries no body; it tells the client its cached copy is still valid, saving bandwidth.
2. Which request header carries an ETag for revalidation?
The client sends its stored ETag in If-None-Match so the server can compare and return 304 if unchanged.
3. What does Cache-Control: max-age=60 mean?
max-age is expressed in seconds, so the response is considered fresh for 60 seconds.
Flash Cards
What is an ETag? — A fingerprint of a resource used to validate whether a cached copy is still current.
What does max-age set? — How many seconds a cached response stays fresh before it must be revalidated.
no-cache vs no-store — no-cache: may cache but must revalidate before use; no-store: never store the response at all.
Meaning of a 304 — Not Modified — the cached copy is valid, so the server sends headers with no body.
Continue Learning
Related Interview Questions
How do you prevent lost updates in a REST API using conditional requests?
hard
How do you cache REST API responses at a CDN without leaking data between users?
hard
What is rate limiting and throttling in a REST API and why are they important?
medium
What should a rate-limited REST response tell the client, and how should the client react?
medium