Playground: cache hits, misses and LRU evictionPlayground: cache hits, misses aur LRU eviction
Capacity is 4. Request keys and watch hits (green), misses (yellow) and which key gets evicted. Watch the hit rate climb when you repeat keys.Capacity 4 hai. Keys request karo aur dekho hits (green), misses (yellow) aur kaunsi key evict hoti hai. Repeat karne pe hit rate kaise badhta hai, dekho.
Why caching is the highest-ROI technique in this course
The physics from lesson 3: RAM ~100 ns, SSD ~100 us, network round trip ~0.5-150 ms. A cache keeps the result of expensive work in RAM, close to the app. A 90% cache hit rate on a read-heavy system removes 90% of database load: often the difference between one DB server and ten. Caches exist at every layer: CPU cache, browser cache, CDN, application cache (Redis/Memcached), database buffer pool. The principle is identical everywhere; the eviction and invalidation details differ.
Cache-aside (the default pattern), step by step
- Read: ask the cache. Hit: return, done (~1 ms total).
- Miss: read the DB (~5 ms), write the value into the cache with a TTL, return.
- Write: update the DB, then delete the cache key (next read repopulates it).
Why delete instead of update on writes? Updating risks race conditions (two concurrent writes leave the cache with the older value); deleting is idempotent and simple. The cost: the first read after each write is a miss.
Write-through and write-back
- Write-through: writes go to cache and DB together, synchronously. Cache is always fresh; writes are slower (two writes per operation). Good for read-heavy spots where stale data is dangerous.
- Write-back: write only to the cache, flush to the DB later in batches. Very fast writes, but a cache crash loses unflushed data. Use for counters and metrics where small loss is acceptable, never for money.
Eviction: what leaves when the cache is full
- LRU (Least Recently Used): evict what was read longest ago. The default; matches most workloads' recency bias.
- LFU (Least Frequently Used): evict what is used least. Better when old items can stay hot (a classic video from 2015).
- TTL: every entry expires after N seconds regardless. A staleness safety net; always set one even with LRU.
The failure modes that separate juniors from seniors
- Thundering herd / cache stampede: a hot key expires; 10,000 concurrent requests all miss and hammer the DB. Fixes: request coalescing (first requester fetches, others wait for that same result), stale-while-revalidate (serve the old value while refreshing in background), TTL jitter (random +/- so keys do not expire together).
- Cache penetration: queries for keys that do not exist (e.g. user id -1) always miss and hit the DB; an attacker can exploit this. Fix: cache negative results briefly, or a Bloom filter in front.
- Cache avalanche: many keys set at the same time (deploy, warmup) expire at the same time. Fix: TTL jitter.
- Hot key: one celebrity key does 30% of traffic; one Redis shard melts. Fix: replicate the hot key across slots, or keep a local in-process cache for it.
Worked example: session store at 50k reads/sec
Sessions: 1 KB each, 10M active users = 10 GB: fits one Redis node, but run a replica for failover. Cache-aside with 24h TTL (sliding), LRU eviction, delete-on-write when the user logs out or changes roles. Session reads hit ~99% because every authenticated request reads the session.
Common interview traps
- "Add Redis" with no invalidation strategy.
- No answer for "what happens when a very hot key expires?"
- Caching per-user data on a shared key (user A sees user B's page).
- Caching everything: rapidly changing data cached long is worse than no cache.
Interview Q&A
Q: How do you keep cache and DB consistent?
A: You do not, perfectly; you bound the staleness. Cache-aside with delete-on-write plus a TTL gives a small stale window. Stricter needs use write-through, or a change-data-capture stream (Debezium) that invalidates cache keys from the DB log.
Q: Redis vs Memcached?
A: Redis: richer data structures (lists, sorted sets for feeds and leaderboards), persistence options, replication, Lua scripts, pub-sub. Memcached: simpler, multi-threaded, pure LRU cache. Modern default is Redis.
Caching is course ki highest-ROI technique kyun hai
Lesson 3 ki physics: RAM ~100 ns, SSD ~100 us, network round trip ~0.5-150 ms. Cache mehenge kaam ka result RAM mein rakhta hai, app ke paas. Read-heavy system par 90% hit rate database load ka 90% kaat deta hai: aksar ek DB server aur dus servers ka farak yehi hota hai. Caches har layer par hain: CPU cache, browser cache, CDN, application cache (Redis/Memcached), DB buffer pool. Principle sabka same hai; eviction aur invalidation ke details alag hain.
Cache-aside (default pattern), step by step
- Read: pehle cache se maango. Hit: return, khatam (~1 ms).
- Miss: DB se padho (~5 ms), value cache mein TTL ke saath daalo, return karo.
- Write: DB update karo, phir cache key delete karo (agli read dobara bhar degi).
Writes par update ki jagah delete kyun? Update mein race conditions ka risk hai (do concurrent writes cache mein purani value chhod sakti hain); delete idempotent aur simple hai. Keemat: har write ke baad pehli read ek miss hoti hai.
Write-through aur write-back
- Write-through: writes cache aur DB dono mein saath, synchronously. Cache hamesha fresh; writes slow (har operation par do writes). Read-heavy jagah jahan stale data khatarnak hai.
- Write-back: sirf cache mein likho, DB mein baad mein batches mein flush. Writes bahut fast, par cache crash to unflushed data lost. Counters aur metrics ke liye jahan chhota loss chale; paison ke liye kabhi nahi.
Eviction: cache full ho to kya nikle
- LRU (Least Recently Used): jo sabse purani read hua, wo nikalo. Default; zyadatar workloads ki recency bias se match karta hai.
- LFU (Least Frequently Used): jo sabse kam use hota hai, wo nikalo. Behtar jab purana data bhi hot rahe (2015 ka classic video).
- TTL: har entry N seconds baad expire, chahe use ho rahi ho. Staleness ka safety net; LRU ke saath bhi hamesha lagao.
Failure modes jo junior ko senior se alag karte hain
- Thundering herd / cache stampede: hot key expire hui; 10,000 concurrent requests sab miss hue aur DB par tut pade. Fixes: request coalescing (pehla requester fetch kare, baaki usi result ka wait karein), stale-while-revalidate (purana value serve karte hue background mein refresh), TTL jitter (random +/- taaki keys saath expire na hon).
- Cache penetration: aise keys ki queries jo exist hi nahi karte (jaise user id -1) hamesha miss hongi aur DB par girengi; attacker iska fayda utha sakta hai. Fix: negative results briefly cache karo, ya aage Bloom filter.
- Cache avalanche: bahut saari keys ek hi time set hui thi (deploy, warmup) to ek saath expire bhi hongi. Fix: TTL jitter.
- Hot key: ek celebrity key par 30% traffic; ek Redis shard melt. Fix: hot key ko slots par replicate karo, ya uske liye local in-process cache.
Worked example: 50k reads/sec ka session store
Sessions: 1 KB each, 10M active users = 10 GB: ek Redis node mein fit, par failover ke liye replica. Cache-aside, 24h TTL (sliding), LRU eviction, logout ya role change par delete-on-write. Session reads ~99% hit hoti hain kyunki har authenticated request session padhti hai.
Common interview traps
- "Redis laga do" bina invalidation strategy ke.
- "Bahut hot key expire hui to kya hoga?" ka jawab na hona.
- Per-user data ko shared key par cache karna (user A ko user B ka page dikh gaya).
- Sab kuch cache karna: tez badalta data lambe time cache karna no-cache se bura hai.
Interview Q&A
Q: Cache aur DB ko consistent kaise rakhte ho?
A: Perfectly nahi rakhte; staleness ko bound karte hain. Cache-aside + delete-on-write + TTL ek chhota stale window deta hai. Stricter zaroorat ho to write-through, ya change-data-capture stream (Debezium) jo DB log se cache keys invalidate kare.
Q: Redis vs Memcached?
A: Redis: rich data structures (feeds aur leaderboards ke liye lists, sorted sets), persistence options, replication, Lua scripts, pub-sub. Memcached: simple, multi-threaded, pure LRU cache. Aaj kal default Redis hai.