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.
See it run
Follow one response: where it is kept, when it may be reused, how it is checked and how it is removed.
Operations
Miss, then hit
The first request walks the whole path. The second stops at the first copy it meets.
Step 1 of 6
Nothing stored yet
The browser and the CDN have no copy, so the request goes on.
Step 1: Nothing stored yet
def get(path): for layer in (browser, cdn, redis): copy = layer.lookup(path) if copy and copy.fresh(): return copy body = database.load(path) fill_all_layers(path, body, ttl=60) return body- Reader waits
- 200 ms, then 5 ms
- Origin work
- 1 query, then 0
- No cache
- 200 ms every time (assumed)
A layer only helps if the answer may be shared there. Personal answers skip the CDN.
In the real world
The same api caching doing real jobs. Pick one and step through it.
The same browser asks for four kinds of data.
Step 1 of 4
Product list
public, max-age=300
public, max-age=300. The CDN answers for everyone.
Step 1: Product list
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Personal data under a shared key
criticalThe next person with the same URL gets someone else's answer.
Wrongkey = request.pathheaders["Cache-Control"] = "public, max-age=300"Rightkey = f"user:{user.id}:{request.path}"headers["Cache-Control"] = "private, no-cache"Using no-cache to forbid storing
majorno-cache allows storing and only demands a check. A secret stays on disk.
Wrongheaders["Cache-Control"] = "no-cache" # card dataRightheaders["Cache-Control"] = "no-store"Storing errors
majorOne bad second is repeated to everyone for the whole lifetime.
Wrongbody = handler(request)cache.put(key, body, ttl=300)Rightstatus, body = handler(request)if status == 200: cache.put(key, body, ttl=300)Deleting before the commit
majorA reader between the two steps stores the old answer again.
Wrongcache.purge("products")db.update(product)Rightdb.update(product) # committedcache.purge("products")
Interview tips
How to explain it
- Who may see it, then how old it may be.
- Headers tell browsers and CDNs; keys and tags are for our own cache.
- A purge is fast, a lifetime is certain. Use both.
Memory trick: CACHE
- Check first, Age matters, Clear wisely.
- Hit ratio: watch it.
- Evict old: least recently used goes first.
Reach for it when
- Reads far outnumber writes.
- Many people get the same answer.
- A few seconds or minutes of age are fine.
Be careful when
- The answer depends on the person.
- Money, stock or permissions are decided.
- The system cannot survive an empty cache.