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.

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

Layers we can clearBrowseremptyCDN edgeemptyAPI serviceRedisemptyDatabase

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

Layers we can clearBrowser300 sCDN edge300 sAPI serviceRedisemptyDatabase

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

    critical

    The next person with the same URL gets someone else's answer.

    Wrong
    key = request.pathheaders["Cache-Control"] = "public, max-age=300"
    Right
    key = f"user:{user.id}:{request.path}"headers["Cache-Control"] = "private, no-cache"
  • Using no-cache to forbid storing

    major

    no-cache allows storing and only demands a check. A secret stays on disk.

    Wrong
    headers["Cache-Control"] = "no-cache"   # card data
    Right
    headers["Cache-Control"] = "no-store"
  • Storing errors

    major

    One bad second is repeated to everyone for the whole lifetime.

    Wrong
    body = handler(request)cache.put(key, body, ttl=300)
    Right
    status, body = handler(request)if status == 200:    cache.put(key, body, ttl=300)
  • Deleting before the commit

    major

    A reader between the two steps stores the old answer again.

    Wrong
    cache.purge("products")db.update(product)
    Right
    db.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.