Caching
Caching is the most common answer to "how does this scale?", and the most common source of subtle bugs. Interviewers expect you to place caches deliberately, choose a write strategy, and handle invalidation, stampedes and hot keys.
Learning objectives
- Place caches at the right layer: client, CDN, application, database.
- Compare cache-aside, read-through, write-through and write-back.
- Choose an eviction policy and TTLs, and handle invalidation.
- Prevent cache stampedes and spread hot keys.
Where caches live
| Layer | Example | Caches |
|---|---|---|
| Client | Browser cache, app memory | Static assets, recently viewed data |
| CDN / edge | Edge caches | Images, video segments, public API responses |
| Application | Redis or Memcached cluster | Objects, query results, sessions, counters |
| Database | Buffer pool, query cache | Hot pages, managed by the database |
Write strategies
| Strategy | Read | Write | Good for | Risk |
|---|---|---|---|---|
| Cache-aside (lazy) | App reads cache, on miss reads DB and fills cache | App writes DB, then deletes the cache key | General default | Brief staleness; first read after a change is slow |
| Read-through | Cache library loads from DB on miss | — | Same as cache-aside, less app code | Library coupling |
| Write-through | — | Write cache and DB together | Data read right after write | Write latency; caches cold data |
| Write-back (write-behind) | — | Write cache, flush to DB later | Very high write rates, counters | Data loss if the cache dies before flushing |
Text description
Read: the app asks the cache for user 42, gets a miss, queries the database, receives the row and stores it in the cache with a 10-minute time to live. Write: the app updates user 42 in the database and then deletes the cache key so the next read loads fresh data.
Why delete rather than update the cache on writes? Two concurrent writers can update the cache in the opposite order to the database and leave it permanently wrong; deleting means the next read loads the truth.
Eviction and TTLs
- LRU (least recently used) is the usual default; LFU suits stable popularity; TTL bounds staleness.
- Choose TTLs from the business tolerance: product price 1 minute, profile 10 minutes, static content days (with versioned URLs).
- Add jitter to TTLs so keys written together don't expire together.
Failure modes and fixes
| Problem | What happens | Fix |
|---|---|---|
| Cache stampede (thundering herd) | A hot key expires; thousands of requests miss at once and hit the DB | Request coalescing (one loader, others wait), a lock per key, or refresh-ahead before expiry |
| Hot key | One key (a celebrity's profile) overloads one cache node | Replicate the key across nodes (key#1..#N, read a random copy), or a small local in-process cache |
| Cold start | An empty cache after a deploy or failure sends all traffic to the DB | Warm the cache; ramp traffic gradually |
| Staleness | Users see old data | Delete-on-write, short TTLs for volatile data, version keys |
| Penetration | Requests for keys that don't exist always miss | Cache negative results briefly; bloom filter |
"I'll cache short-code → long-URL in Redis, key url:{code}, no TTL because mappings never change, LRU eviction. With a 90% hit rate the database sees ~4K reads/s instead of 40K."
Self-check
Where would you add caching to a read-heavy social app, and how would you keep it correct?
- CDN for media, Redis for profiles, posts and feed pages; cache-aside with delete-on-write; TTLs with jitter; coalescing for hot keys; replicate celebrity keys.
What is a cache stampede and how do you prevent it?
- Many simultaneous misses on an expired hot key overload the DB; coalescing, per-key locks, refresh-ahead, TTL jitter.