Cache TTL
easy 24 minA 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=0 | t=30 | t=59 | t=60 | t=80 | |
|---|---|---|---|---|---|
| event | store | ||||
| seconds left | 60 |
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
- 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
criticalOne missed delete leaves a wrong value until somebody notices.
Wrongcache.set(key, value)Rightcache.set(key, value, ttl=3600) # safety netSet and expire in two steps
majorA crash between them leaves a key that lives for ever.
Wrongr.set(key, value)r.expire(key, 60)Rightr.set(key, value, ex=60)Sliding TTL on a copy
criticalA busy key is renewed all the time and never sees the new data.
Wrongif hit: cache.touch(key, 60)Rightif hit and age(key) < 300: # maximum age cache.touch(key, 60)One TTL for a bulk load
majorKeys stored together expire together.
Wrongfor k in keys: cache.set(k, load(k), ttl=600)Rightfor 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?