AlgoViz

Cache TTL

easy 24 min

A time to live (TTL) says how long a cached copy may be used.

See it run

Follow the seconds that are left: what a read changes, what it does not, and what happens at zero.

Operations

Absolute

60 seconds from the moment of storing, whatever happens.

Step 1 of 5

Store

t=0t=30t=59t=60t=80
eventstore
seconds left60

expires at 60

The value is stored at 0 and may be used until 60.

Step 1: Store

def set(key, value, ttl):    data[key] = (value, now() + ttl)def get(key):    value, until = data.get(key, (None, 0))    return value if now() < until else None
Limits
Age
A read
changes nothing
Good for
prices, catalogues

The promise is easy to say: never older than 60 seconds.

In the real world

The same cache ttl doing real jobs. Pick one and step through it.

One hot key, 2,000 reads a second, 200 ms to rebuild.

Step 1 of 3

Hits

Our systemreadrebuildReaders2,000 a secondAPICachefreshDatabasecalm
Database load
10%

0 rebuilds

Every read is answered by the cache.

Step 1: Hits

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • No TTL at all

    critical

    One missed delete leaves a wrong value until somebody notices.

    Wrong
    cache.set(key, value)
    Right
    cache.set(key, value, ttl=3600)   # safety net
  • Set and expire in two steps

    major

    A crash between them leaves a key that lives for ever.

    Wrong
    r.set(key, value)r.expire(key, 60)
    Right
    r.set(key, value, ex=60)
  • Sliding TTL on a copy

    critical

    A busy key is renewed all the time and never sees the new data.

    Wrong
    if hit: cache.touch(key, 60)
    Right
    if hit and age(key) < 300:   # maximum age    cache.touch(key, 60)
  • One TTL for a bulk load

    major

    Keys stored together expire together.

    Wrong
    for k in keys: cache.set(k, load(k), ttl=600)
    Right
    for k in keys:    cache.set(k, load(k), ttl=600 + random.uniform(-60, 60))

Interview tips

  • How to explain it

    • A copy with a best-before time.
    • Shorter is fresher, longer is cheaper.
    • It heals every mistake after a known time.
  • Memory trick: ASA

    • Absolute: a birthday countdown.
    • Sliding: a snooze button.
    • Adaptive: attention is rewarded.
  • Prevention: JELS

    • Jitter and early refresh.
    • Locking.
    • Stale while revalidate.
  • Check

    • How old can it be at the user?
    • How many refreshes a second remain?
    • What expires at the same moment?