API caching
easy 25 minAPI caching keeps a copy of a response nearer to the caller, so the same question does not travel to the database again.
Video lesson · Chapter 1 of 6
The second public read can be cheaper
API caching in 75 seconds
1:15Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
An API answers the same question many times: the product list, the category tree, the profile of the same person. API caching means keeping a copy of the answer somewhere closer than the database and serving that copy while it is still good enough.
The copy can live in the browser, in a content delivery network, at the gateway, or in a shared store such as Redis. HTTP has its own language for this: the server sends headers that say who may keep the answer, how long it stays fresh, and how to check it later.
Why it exists
Without a cache every request walks the whole path to the database and back. With one, most requests stop early, so people wait less and the database works less. It can also keep answering for a while when something behind it is down.
The price is a second version of the truth. A copy can be out of date, can be shown to the wrong person if the key is wrong, and needs a plan for removal. So the question is never only how to cache, but how old may this answer be, and who may see it.
A short history
May 1996
RFC 1945 describes HTTP/1.0 with Expires and If-Modified-Since: a first way to say until when a copy is good and to ask whether it changed.
January 1997
RFC 2068, the first HTTP/1.1 standard, adds Cache-Control, ETag and Vary.
May 2010
RFC 5861 defines stale-while-revalidate and stale-if-error.
September 2017
RFC 8246 adds the immutable directive, for files whose name changes when their content changes.
June 2022
RFC 9111 replaces the earlier caching standard. It is the text to read today.
Words to know
- Fresh
- Young enough to use without asking.
- Stale
- Older than its allowed time. It may still be right, but must normally be checked.
- TTL
- Time to live: how long a copy stays fresh.
- ETag
- A label for one version of a response.
- Revalidation
- Asking the server whether a stored copy is still current.
- Cache key
- The name a copy is stored under. Same key, same answer.
- Private and shared cache
- A cache for one person, such as a browser, and a cache for many, such as a CDN.
- Purge
- Removing a copy before its time is up.
How it works
Step through the idea, or press Play.
Ask the nearest copy. Browser, CDN, gateway, then Redis, each answers what it can
Understand it
Start here
The milk in the fridge
Imagine the dairy is across town and milk comes with a date on the carton. A carton in your fridge saves the walk. The date tells you when to stop trusting it, and a phone call to the dairy is much cheaper than a new trip.
The same shop, the same three ideas: a date, a check and a recall. The library story in caching shows how a cache chooses what to throw out.
The whole path
Where an answer can be kept
A request stops at the first copy it finds
Cache layers of a shop
| Layer | Holds | Typical lifetime | Who can clear it |
|---|---|---|---|
| Browser | Static files, the person's own settings | 1 day to 1 week; a year for versioned files | Only the person. Use a new file name instead |
| CDN | Product images, scripts, public responses | 1 hour to 1 day | We can, through the CDN's purge |
| API gateway | Public endpoints | 1 to 5 minutes | We can |
| Application cache, such as Redis | Sessions, carts, product lists | 5 to 60 minutes | We can, per key or tag |
| Database | Pages in its memory, materialized views | Managed by the database | The database |
Why
What caching buys, and what it costs
Benefits
- Faster answers: served from memory, or from nearby.
- Less load: fewer database queries.
- Lower cost: less computing for the same traffic.
- More room to grow: repeat reads barely touch the origin.
- Resilience: an old answer during an outage, if you allow it.
Challenges
- Stale data: the copy may be out of date.
- Invalidation: knowing when to remove it.
- Memory: cache space is not free.
- Complexity: one more layer to run and debug.
- Consistency: several caches can disagree.
What the hit ratio does
What reaches the origin
Headers
Cache-Control: the server's instructions
The directives you will use
| Directive | Example | Meaning |
|---|---|---|
| max-age | max-age=3600 | Fresh for 3600 seconds, which is one hour |
| s-maxage | s-maxage=600 | Fresh for 600 s in shared caches; overrides max-age there |
| no-cache | no-cache | May be stored, but must be checked with the server before every use |
| no-store | no-store | Must not be stored at all |
| private | private | Only the person's own cache may store it, not a CDN or proxy |
| public | public | Any cache may store it, even when the request had an Authorization header |
| stale-while-revalidate | stale-while-revalidate=300 | May be served stale for 300 s more while a refresh runs |
| stale-if-error | stale-if-error=600 | May be served stale for 600 s if the server fails |
| immutable | immutable | Will not change while fresh, so do not check even on reload |
Which header for this response?
# Public product listCache-Control: public, max-age=300ETag: "products-v42"Vary: Accept-Encoding# A person's cartCache-Control: private, no-cacheETag: "cart-9f2"# Product image with a content hash in its nameCache-Control: public, max-age=31536000, immutable# Payment pageCache-Control: no-storeChecking
ETags and conditional requests
When a copy is stale it is not useless. The client asks: I have version abc123, is that still current? If yes, the server sends 304 Not Modified with no body, and the copy is fresh again.
Asking about a copy instead of fetching it again
First request, check, change
ETag from a version
Use the row's version or update time. Cheap: no need to build the body to answer 304.
ETag from a hash
Hash the body. Always right, but the server does the work and only the transfer is saved.
Last-Modified
A date in whole seconds, sent back as If-Modified-Since. Simple, but two changes in one second look the same.
Also for writes
PUT with If-Match refuses to overwrite a newer version and returns 412. See API error handling.
Same question?
Vary and the cache key
A cache needs to know which requests may share an answer. Its key starts with the method and the URL. Vary adds the request headers that change the response.
| Header | What the cache keeps | Use it when |
|---|---|---|
Vary: Accept-Encoding | One copy per compression | You serve gzip and brotli |
Vary: Accept-Language | One copy per language value | The text is translated. Better: put the language in the URL |
Vary: Accept-Encoding, Accept-Language | One copy per pair | Both change the body |
Vary: Authorization | One copy per credential | Almost never. Use private instead, so no shared cache holds it at all |
Good keys
products:category:electronics:page:1user:123:profile:v2search:q=phone:sort=price:page=1- Specific, versioned, every parameter that changes the answer, in a fixed order
Bad keys
productsuser_datasearch_results- Too generic: two different questions collide and one person gets another's answer
Filling it
Four ways to keep the copy filled
| Strategy | Steps | Good | Bad |
|---|---|---|---|
| Cache-aside (lazy loading) | Check cache, on a miss query the database, store, return | Keeps only what is asked for | The first request is slow |
| Write-through | Write to cache, cache writes to the database, confirm | Cache and database in step, if every write goes this way | Slower writes |
| Write-behind (write-back) | Write to cache, answer at once, write batches later | Fast writes | A crash can lose writes |
| Refresh-ahead | When about 20% of the lifetime is left, refresh in the background | Popular keys never miss | May refresh what nobody asks for |
Good candidates
- Product catalogues: read far more than changed
- Category lists: rarely change
- User profiles, in a per-person cache
- Search results: expensive queries
- Configuration and settings
- Static content: images, JS, CSS
Bad candidates
- Live prices where seconds matter
- Exact stock counts at checkout
- Payment transactions
- One-time tokens
- Heavily personalised data, which few requests share
- Anything that needs strict consistency
Bad does not always mean never. A public live price can be cached for one second: at 300 requests a second, that turns 300 reads into one.
Removing it
Invalidation
A well known saying, credited to Phil Karlton, calls cache invalidation one of the two hard things in computer science. Three approaches cover most APIs.
Time based
The entry expires after its lifetime. Simple, and it always ends, but it serves old data until then.
Event based
A change removes the copy. Accurate, but every write path must remember to do it.
Version based
Put the version in the key or file name. Nothing to delete, but old copies take space until they expire.
Purge by tag
Old but quick
Stale-while-revalidate
Cache-Control: max-age=60, stale-while-revalidate=300 gives three periods. The reader gets an answer at once in the first two.
| Age of the copy | State | What happens |
|---|---|---|
| 0 to 60 s | Fresh | Served, nobody asks the server |
| 60 to 360 s | Stale, allowed | Served at once, refreshed in the background |
| after 360 s | Expired | The request waits for the server |
One answer, refreshed behind it
Under load
The thundering herd
A popular copy expires at 12:00:00. At 12:00:01, 100 requests arrive together, all miss, and all 100 run the same expensive query. The database, sized for misses that come one by one, can fall over.
Four cures, used together
- 1
Lock
The first request refreshes. The others wait for it or take the old copy. One query instead of 100.
- 2
Early refresh
Refresh popular keys before they expire.
- 3
Jitter
Add a random part to each lifetime, for example plus or minus 10%, so keys do not expire together.
- 4
Stale-while-revalidate
Serve the old copy while one refresh runs.
Errors too
Caching what went wrong
A missing product can be cached for a short time, such as one minute for a 404, so that a broken link does not reach the database each time. Do not store 500 errors, or one bad second becomes a bad five minutes. When the origin fails, an old good answer is usually better than a new error: that is stale-if-error, and it is one of the choices in fallbacks.
Summary
The whole topic in one minute.
API caching stores answers close to the caller. Cache-Control says who may store and for how long, an ETag makes checking an old copy cheap, and Vary plus a careful key decide which requests may share one answer.
Give public data a short lifetime, keep personal data private, never store secrets, purge by tag when data changes, and let one request refresh a popular copy while the others wait or take the slightly old one.
- Decide who may see an answer before deciding how long to keep it.
- max-age is freshness, no-cache means check first, no-store means do not keep.
- An ETag turns a full reload into a short 304.
- The key must hold everything that changes the answer, including the person.
- Purge by tag on change, and keep a lifetime as the safety net.
- Let one request refresh a hot key.