Caching Strategies and Eviction
medium 25 minPlace fast memory between applications and persistent storage to slash read latency and protect databases.
See it run
Follow one value: where a copy is kept, who answers, what is thrown out, and what happens when a popular copy disappears.
Operations
A miss, then hits
The first reader pays for the copy. Everybody after that gets it quickly.
Step 1 of 5
Ask the cache
A reader wants profile 42. The app looks in Redis first.
Step 1: Ask the cache
def read(key): value = cache.get(key) # 1 ms if value is not None: return value # hit value = db.read(key) # 10 ms cache.set(key, value, ttl=300) return value- Reader waits
- 11 ms, then 1 ms
- Database work
- 1 query, then 0
- No cache
- 10 ms every time (assumed)
Say both numbers: how fast a hit is, and how many reads no longer reach the database.
In the real world
The same caching doing real jobs. Pick one and step through it.
10,000 reads a second. Watch how many reach the database.
Step 1 of 3
No cache
- Reads at database
- 100%
Overloaded
All 10,000 reads a second reach a database that can do 2,000 (assumed).
Step 1: No cache
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Caching without saying how old a copy may be
criticalA key with no expiry lives until memory is short. If one delete is lost, the wrong value can stay for weeks.
Wrongcache.set("price:7", price)Rightcache.set("price:7", price, ttl=300) # at most 5 minutes oldDeleting the copy before writing the database
majorA reader in between misses, reads the old row and stores it again after your delete.
Wrongcache.delete(key)db.write(key, value)Rightdb.write(key, value)cache.delete(key)One key for different people
criticalIf the user is missing from the key, one person is shown another person's data.
Wrongcache.set("orders:latest", orders)Rightcache.set(f"orders:{user_id}:latest", orders, ttl=60)Sizing the database for the hits
majorAfter a restart or a flush the cache is empty, and the full load arrives at once.
Wrongdb_capacity = normal_missesRightdb_capacity = normal_misses * headroomlimit_concurrent_misses(db_capacity)
Interview tips
How to explain it
- A cache keeps copies of popular data somewhere faster or nearer.
- It cuts waiting time and protects the store behind it.
- The price is a second version that can be old.
Numbers to give
- Hit rate, and reads per second that still reach the database.
- The oldest copy you accept, in seconds.
- Memory: hot items times size, plus room.
Reach for it when
- The same data is read many times.
- Computing or fetching it is slow.
- A few seconds of age is fine.
Think again when
- Every read must be exact.
- Almost every request asks for something different.
- The real problem is a missing index.