SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
  • What is Caching?
  • Caching Strategies
  • Cache Eviction Policies
  • Cache Invalidation
  • HTTP Caching (Cache-Control, ETag)
  • Redis vs Memcached
  • Local Cache vs Distributed Cache
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Caching/Caching Basics

HTTP Caching (Cache-Control, ETag)

Let browsers and proxies reuse a response, and ask cheaply whether it is still fresh.

⏱ 14 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

HTTP caching lets browsers, proxies and CDNs keep a copy of a response and reuse it, so the same file is not downloaded again and again.

  • The server controls it with headers. Cache-Control says how long a copy is fresh and who may keep it.
  • When a copy is old, a cheap check can ask “has it changed?” using an ETag. If not, the server answers 304 Not Modified with no body.
  • The best request is the one that never leaves the browser.

02Concept: What is it?

Every time you open a page, the browser needs files: HTML, scripts, styles, images. Downloading them all each time is slow and costs bandwidth. HTTP has a built-in way to avoid that. The server adds headers to each response that tell every cache on the way what it may do.

There are two ideas. Freshness: for the next N seconds the copy is good, so use it without asking anyone. Validation: the copy is old, so ask the server a short question, and reuse the copy if the answer is “nothing changed”.

Three ways a reload can end
Fresh copy
🌐Browser
→↓uses own copy
💾Cachestill fresh
Data over the network0 KB, no round trip
Old copy, but unchanged
🌐Browser
→↓If-None-Match
🗄️Server304, no body
Data over the networkheaders only
Changed or missing
🌐Browser
→↓GET
🗄️Server200 + full body
Data over the networkthe whole file
Cache hit: no network at all. 304: a tiny round trip. 200: the full file again.
🧠no-cache does not mean “do not cache”
no-cache means: you may store it, but ask the server before you reuse it. To forbid storing, use no-store. This is the most common mix-up with these headers.

03Real-Life Example

🍵The newspaper at your door
You get a newspaper every morning. If you already read today’s paper, you do not call the shop to ask for it again. That is a fresh copy. Sometimes you are unsure if there is a new edition, so you call and ask: “Is edition 4821 still the latest?” The shop says “yes” in one word. That is a 304. Only if there is a new edition do they send you a whole new paper.
Newspaper
HTTP caching
Today’s paper on the table
A fresh copy in the browser cache
“Good for today”
max-age (how long the copy is fresh)
The edition number on the front page
ETag (a version label for the content)
Calling to ask if your edition is still current
A conditional request (If-None-Match)
“Yes, that is still the latest”
304 Not Modified (no body)
A new paper delivered
200 with the full body
A paper with your private mail inside
private or no-store: never share it

04Why Do We Need It?

⚡Faster pages
A cached file loads in a moment. There is no network, no waiting.
📉Less bandwidth
Fewer bytes move, which saves money and helps people on slow mobile networks.
🛡️Less server load
Requests answered by the browser or a CDN never reach your servers.
🌍Works at every layer
Browser, company proxy and CDN all follow the same rules, with no special code.
🔁Cheap freshness checks
A 304 is tiny, so even checking every time costs far less than downloading.
📶Offline tolerance
With stale-if-error a stale copy can be shown while the server is down.
HTTP already has caching built in. Set the headers well, and most of your traffic never reaches your servers.

05Where Do We Use It?

🌐Browser cache
Each browser keeps its own private copy on the user’s device.
🏢Company or ISP proxy
A shared cache for many users on one network.
🌍CDN
Servers in many cities that follow your Cache-Control headers.
🧱Reverse proxy
Nginx, Varnish and similar tools cache in front of your app.
🖼️Static assets
Scripts, styles, fonts and images are the best candidates.
🔌GET APIs
Public, rarely changing API answers, such as a country list.

06Types / Parts / How It Works

The headers you will meet

Header or directiveWhat it doesGood to know
max-age=NThe copy is fresh for N secondsCounted from when the response was made.
s-maxage=NLike max-age, but only for shared caches (CDN, proxy)Lets a CDN keep it longer than a browser does.
no-cacheStore it, but check with the server before each reuseOften paired with an ETag, so the check is a cheap 304.
no-storeDo not keep any copy anywhereFor secrets and sensitive data.
public / privateAnyone may store it / only the user’s own browser mayUse private for anything personal.
must-revalidateOnce stale, never reuse without checkingStops caches from serving old copies when the server is down.
immutableThis file will never change at this URLPair with a long max-age and a fingerprinted file name.
stale-while-revalidateShow the old copy now and refresh it in the backgroundFast pages, a little staleness.
stale-if-errorIf the server is failing, an old copy may be usedSupport depends on the cache. Check your CDN docs.

Validators: how a stale copy is checked

ValidatorSent by serverSent back by clientNotes
ETagETag: “v42”If-None-Match: “v42”An opaque label for the content. Strong means byte-for-byte equal. Weak (W/) means equal in meaning.
Last-ModifiedLast-Modified: a dateIf-Modified-Since: that dateOnly second-level accuracy. Simple, but less exact than an ETag.

What a revalidation looks like

Conditional request and a 304 answer (illustrative)
GET /app.js HTTP/1.1
If-None-Match: "v42"

HTTP/1.1 304 Not Modified
ETag: "v42"
Cache-Control: no-cache
📝Note
The Vary header tells caches which request headers change the answer. Vary: Accept-Encoding means a gzip copy and a plain copy are stored separately. Too many Vary values hurt hit rates.
VisualizerReload six times: cache, 304 or full download?Pick a resource, then change Cache-Control and the ETag. Try a script file with a long max-age and a fingerprinted name, then try an HTML page with no-cache. Make the private page public and see the leak warning.
What is being cached?

A big file that rarely changes by itself. Illustrative size: 200 KB.

Cache-Control
max-age
Who may store it?
Content changes on the server at
Cache-Control: public, max-age=300
ETag: "v1"
Six reloads of the same page, at these times after the first visit:
at 0 s
200 Full download
200 KB · 1 trip
at 10 s
From cache
0 KB · 0 trips
at 45 s
From cache
0 KB · 0 trips
at 3 min
From cache
0 KB · 0 trips
OLD content shown
at 15 min
200 Full download
200 KB · 1 trip
at 1.1 h
304 Not Modified
0.5 KB · 1 trip
Data downloaded
400.5 KB
vs 1200 KB with no cache
Network round trips
3
of 6 reloads
Old content shown
1
stale reloads
Shared-cache risk
none
personal data in a CDN
1 reload(s) showed OLD content. The browser trusted its copy until max-age ran out and never asked the server. Fix it with a fingerprinted file name (new content means a new URL), a shorter max-age, or no-cache with an ETag.

A simplified model. File sizes (200, 30, 5 and 20 KB), the 0.5 KB size of a 304 and the reload times are made-up teaching numbers. It follows one browser cache and one URL, and ignores the Vary header, heuristic freshness and the reload button.

07How to Use It / Steps / Implementation

A simple plan that works for most sites

  1. 1
    Fingerprint your static files
    Build tools add a hash to the name (app.3f9a1c.js). New content means a new URL, so old copies can never be wrong.
  2. 2
    Give fingerprinted files a very long life
    Cache-Control: public, max-age=31536000, immutable. The browser will not even ask again.
  3. 3
    Make HTML revalidate every time
    Cache-Control: no-cache plus an ETag. A reload costs a tiny 304, and a deploy shows up at once.
  4. 4
    Mark personal pages private or no-store
    Anything with a user’s own data must never sit in a shared cache.
  5. 5
    Cache public API answers briefly
    A short max-age (seconds or minutes) plus an ETag can remove most repeat traffic.
  6. 6
    Set Vary correctly
    If the body depends on a request header such as Accept-Encoding or Accept-Language, say so.
  7. 7
    Test with the browser’s network tab
    It shows “disk cache”, “memory cache” or 304 for each file. Check what really happens.
💡Heuristic caching
If a response has no Cache-Control at all, some caches guess a lifetime from the Last-Modified date. Do not leave it to chance. Always send an explicit header.
⚠️You cannot recall a long max-age
If you tell the browser a file is good for a year, you cannot force it to ask again. That is why the file name must change when the content changes.

08Key Terms to Know

TermMeaning in easy words
Cache-ControlThe main header that says how a response may be cached
FreshnessThe time during which a cached copy can be used without asking the server
ValidationAsking the server whether an old copy is still current
max-ageHow many seconds the copy stays fresh
ETagA version label the server puts on a response
304 Not ModifiedThe server’s answer: your copy is still good, no body sent
Conditional requestA request with If-None-Match or If-Modified-Since
Shared cacheA cache used by many people, such as a CDN or proxy
Private cacheA cache for one user only, such as the browser
VaryA header listing the request headers that change the response
FingerprintingPutting a hash of the content in the file name, so a change means a new URL

09Pros, Cons and Trade-offs

✅ Pros
  • Huge speed gain for repeat visits
  • Saves bandwidth and server work
  • Standard and understood by browsers, proxies and CDNs
  • A 304 is a cheap way to stay correct
  • No extra infrastructure needed
⚠️ Cons
  • Stale content if freshness is too long
  • You cannot recall a copy once it is in a browser
  • Wrong headers on personal data can leak it
  • Behaviour differs a little between caches
  • Hard to test all the layers in between

Trade-offs

ChoiceWe gainWe lose
Long max-ageNo requests at allUpdates are slow to appear, unless the URL changes
no-cache + ETagAlways correct, and cheap checksOne round trip on every load
no-storeNothing is ever keptNo speed benefit at all
publicA CDN can serve everyoneRisk if the content is personal
privateSafe for personal dataA CDN cannot help
Weak ETagCheaper to computeNot exact to the byte

10Common Problems and Mistakes

Common mistakes

  1. Using no-cache when you mean no-store. The data is still stored, which is a problem for secrets.
  2. A long max-age on a file with a fixed name. Users keep the old script for weeks after a deploy.
  3. Caching HTML for too long. The page then points at old script names that may be gone.
  4. Public on personal pages. A shared cache may show one person’s page to another.
  5. No ETag and no Last-Modified. The server cannot answer with a 304, so revalidation turns into a full download.
  6. Cookies and Vary ignored. A cached answer that depends on a cookie is served to the wrong user.
  7. Different ETags on each server. If every server builds its own ETag, 304s never match behind a load balancer.

Things to watch

🕰️Stale after a deploy
Check that HTML is revalidated and assets are fingerprinted.
🔐Leaks
Look at the headers on every logged-in page.
📉Low hit rate
Check Vary, query strings and cookies that split the cache.
🧪Different layers
A CDN may use s-maxage while the browser uses max-age.

11Real-World Examples

🧱Build tools
Modern front-end tools fingerprint file names, so assets can be cached for a very long time.
🌍CDNs
They read your Cache-Control and s-maxage to decide how long to keep each file.
📰News sites
Often use short freshness plus stale-while-revalidate, so pages stay fast and fairly fresh.
🛒Shops
Product images are cached for long. Cart and account pages are private.
📦Package registries
Versioned files never change, so they are cached as immutable.
🔌Public APIs
Often send ETags, so clients can poll cheaply with conditional requests.
📝Note
Defaults and support for newer directives differ between browsers and CDNs. Check the documentation of the ones you use.
Mini case: a deploy day
📄index.htmlno-cache + ETag
→↓points to
📜app.9c1e.js1 year, immutable
⇢⇣old name
🗑️app.3f9a.jsnever asked for
Always checked Cached for long Left to expire
The HTML is revalidated and points to new file names. Old copies are simply never asked for again.

12Related Topics to Read Next

CDN→

A CDN follows your Cache-Control headers and is the biggest shared cache.

Cache Invalidation→

What to do when content changes before the copy expires.

What is Caching?→

The general idea behind every cache.

HTTP / HTTPS→

The protocol that carries these headers.

Cookies and CORS→

Cookies and Vary decide whether a cached answer can be shared.

Caching Strategies→

Cache-aside and others, for caches you control yourself.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Fresh: max-age says how long to reuse a copy without asking.
  • ✔Stale: ask the server with If-None-Match (ETag). Answer 304 means keep your copy.
  • ✔no-cache: store, but always check. no-store: never keep.
  • ✔Assets: fingerprinted names + max-age=1 year + immutable.
  • ✔HTML: no-cache + ETag, so deploys show up at once.
  • ✔Personal data: private or no-store. Never public.
  • ✔Vary: list headers that change the answer, such as Accept-Encoding.
  • ✔One line: “The fastest request is the one that never leaves the browser.”
← Previous
Cache Invalidation
Next →
Redis vs Memcached