AlgoViz

API caching

easy 25 min

API 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

0:00 / 4:33

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

  1. 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.

  2. January 1997

    RFC 2068, the first HTTP/1.1 standard, adds Cache-Control, ETag and Vary.

  3. May 2010

    RFC 5861 defines stale-while-revalidate and stale-if-error.

  4. September 2017

    RFC 8246 adds the immutable directive, for files whose name changes when their content changes.

  5. 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.

Step 1 of 3

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.

One dairy, one fridge
DAIRYday5Fresh until day 5The fridge is emptyDay 1

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

A request from a user passes the browser cache on their device, then a CDN edge outside our system, then inside our system the API gateway cache, the API service, the Redis cache and last the database. A hit at any layer ends the trip.
Blue is the read path. Only misses travel on. Everything inside the dashed outline is ours to clear at once; the browser is not.

Cache layers of a shop

LayerHoldsTypical lifetimeWho can clear it
BrowserStatic files, the person's own settings1 day to 1 week; a year for versioned filesOnly the person. Use a new file name instead
CDNProduct images, scripts, public responses1 hour to 1 dayWe can, through the CDN's purge
API gatewayPublic endpoints1 to 5 minutesWe can
Application cache, such as RedisSessions, carts, product lists5 to 60 minutesWe can, per key or tag
DatabasePages in its memory, materialized viewsManaged by the databaseThe database
Lifetimes are starting points, not rules. Do not count on a query cache in the database: MySQL 8.0 removed its own and PostgreSQL never had one.

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

t=h tcache+(1−h)(tcache+torigin)h=0.9:;0.9⋅5+0.1⋅205=25 mst = h\,t_{cache} + (1-h)(t_{cache}+t_{origin}) \qquad h=0.9:; 0.9\cdot 5 + 0.1\cdot 205 = 25\ \text{ms}
Assume 5 ms for the cache and 200 ms for the full path. One hit is 40 times faster than the full path. At 90% hits the average falls from 200 to 25 ms, which is 8 times, because misses still cost 205.

What reaches the origin

10,000,000100,000=100/s;→;3×=300/s at peak;→;(1−0.95)⋅300=15/s\frac{10{,}000{,}000}{100{,}000} = 100/\text{s} ;\to; 3\times = 300/\text{s at peak} ;\to; (1-0.95)\cdot 300 = 15/\text{s}
Ten million reads a day, divided by 100,000 in your head, with a peak of three times the average. At 95% hits the origin sees 15 requests a second. Falling to 90% doubles that to 30.

Headers

Cache-Control: the server's instructions

The directives you will use

DirectiveExampleMeaning
max-agemax-age=3600Fresh for 3600 seconds, which is one hour
s-maxages-maxage=600Fresh for 600 s in shared caches; overrides max-age there
no-cacheno-cacheMay be stored, but must be checked with the server before every use
no-storeno-storeMust not be stored at all
privateprivateOnly the person's own cache may store it, not a CDN or proxy
publicpublicAny cache may store it, even when the request had an Authorization header
stale-while-revalidatestale-while-revalidate=300May be served stale for 300 s more while a refresh runs
stale-if-errorstale-if-error=600May be served stale for 600 s if the server fails
immutableimmutableWill not change while fresh, so do not check even on reload
Without any lifetime, a cache may guess one. That is called heuristic freshness. Say what you mean instead.

Which header for this response?

Start with who may see it. How long comes second.
HTTP
# 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-store
Four responses of the same shop. 31,536,000 seconds is 365 days. For the payment page no-store alone is enough. Pragma was never defined for responses.

Checking

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

The client app keeps a copy with ETag abc123. It asks the API service with If-None-Match. The API service compares with the current version in the database and answers 304 with no body when they match, or 200 with the new body when they differ.
Pink dashes are the two possible answers. A 304 saves the body. It saves server work only if the version can be found without building the whole response.

First request, check, change

The quotes around an ETag belong to the value. A weak ETag starts with W/ and means same meaning, not same bytes.
  • 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.

HeaderWhat the cache keepsUse it when
Vary: Accept-EncodingOne copy per compressionYou serve gzip and brotli
Vary: Accept-LanguageOne copy per language valueThe text is translated. Better: put the language in the URL
Vary: Accept-Encoding, Accept-LanguageOne copy per pairBoth change the body
Vary: AuthorizationOne copy per credentialAlmost never. Use private instead, so no shared cache holds it at all
Three encodings times five languages is fifteen copies of every URL, so each one gets fewer hits. Varying on User-Agent makes the cache nearly useless.

Good keys

  • products:category:electronics:page:1
  • user:123:profile:v2
  • search:q=phone:sort=price:page=1
  • Specific, versioned, every parameter that changes the answer, in a fixed order

Bad keys

  • products
  • user_data
  • search_results
  • Too generic: two different questions collide and one person gets another's answer

Filling it

Four ways to keep the copy filled

StrategyStepsGoodBad
Cache-aside (lazy loading)Check cache, on a miss query the database, store, returnKeeps only what is asked forThe first request is slow
Write-throughWrite to cache, cache writes to the database, confirmCache and database in step, if every write goes this waySlower writes
Write-behind (write-back)Write to cache, answer at once, write batches laterFast writesA crash can lose writes
Refresh-aheadWhen about 20% of the lifetime is left, refresh in the backgroundPopular keys never missMay refresh what nobody asks for
API responses usually use cache-aside. The patterns and their races are drawn in caching.

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

Delete after the commit. If the purge fails, put it on a queue and retry; the lifetime is the safety net.

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 copyStateWhat happens
0 to 60 sFreshServed, nobody asks the server
60 to 360 sStale, allowedServed at once, refreshed in the background
after 360 sExpiredThe request waits for the server
60 plus 300 is 360. A page that nobody opens for an hour is still slow for the first visitor.

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. 1

    Lock

    The first request refreshes. The others wait for it or take the old copy. One query instead of 100.

  2. 2

    Early refresh

    Refresh popular keys before they expire.

  3. 3

    Jitter

    Add a random part to each lifetime, for example plus or minus 10%, so keys do not expire together.

  4. 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.

Sources