Caching

Lesson 3.3 · 4 min read · by Vinay C

We'll cover the following

Keep hot data in fast memory so you do not hit the slow DB every time.

Where caches sit

Browser, CDN, application cache (Redis), then the DB.

Write strategies

StrategyHowTrade-off
Cache-aside (default)Read: check cache, on miss read DB and fill cache with a TTL. Write: update DB, then delete the cache entry.App manages it; simple; delete (not update) avoids stale-write races
Write-throughWrite cache and DB togetherAlways fresh, slower writes
Write-backWrite cache only, flush to DB laterVery fast, can lose data if the cache dies first. Fine for view counters.

Eviction and sizing

  • LRU is the default answer for eviction; TTL handles staleness.
  • 80/20 rule: cache the hot 20% of data and it serves ~80% of reads.

Failure modes (the senior-level part)

ProblemWhat happensFix
StampedeA hot key expires and thousands of requests hit the DB at onceRequest coalescing (one request refills), a lock, or refresh before expiry
PenetrationRequests for keys that do not exist always miss the cache and always hit the DBCache the "not found" result with a short TTL, or put a Bloom filter in front
Hot keyOne key (a celebrity profile) gets huge traffic and all of it lands on the one node that owns it; other nodes idleSmall local in-process cache on each app server, replicate the key as key#1..#5 across nodes, or read replicas
Cold startEmpty cache after a restart floods the DBWarm the cache first

Hot key insight: adding more cache nodes does not help, because the key still lives on only one of them. Sharding spreads keys evenly, not traffic. The same idea returns as a hot partition in DynamoDB.

Staleness

A TTL of one hour means users can see stale data for up to an hour after the source changes. Choose: a short TTL, explicit invalidation on write, or accept staleness for data that does not matter.

Check yourselfA celebrity key expires at noon and 10K requests arrive at once. What happens?

Cache stampede: all 10K miss and hit the DB together. Fix with request coalescing or a lock so one request refills it, or refresh the key before it expires.

Summary: say it in the interview

  • "Cache-aside with delete-on-write: simple, and it avoids stale-write races."