Handbooks / System Design / Chapter 5
Caching
7 pages · ~5 min✓ Reviewed
Builds on API Design and Gateways. Next up: Databases, Replication and Sharding.
Cache Layers Mental Model
1. What a Cache Is
- Cache = small fast copy of slow data
- Hit: skips the origin. Miss: full cost, then fills the cache
- Hit ratio = hits / (hits + misses)
2. Layers Outward to Inward
- Clientbrowser
- CDNedge
- Applocal or Redis
- Databasebuffer pool
| Layer | Controlled by | Note |
|---|---|---|
| Client | Cache-Control, ETag |
Read and Write Caching Patterns
1. Read path: cache-aside
- Cache-aside (lazy loading): the app owns the logic
- Read cache, on miss read DB, then write cache
- Only requested data is cached
- Most common pattern
python
def get(k): v = cache.get(k) if v is None: v = db.get(k) cache.set(k, v, ttl=300) return v
pseudo-code: miss fills the cache
2. Write patterns
Eviction Policies
1. When and Who
- Eviction runs when the cache is full to free space
- The policy decides the victim
2. LRU, LFU, TTL
| Policy | Evicts | Weak spot |
|---|---|---|
| LRU | least recently used | scan of one-off keys |
| LFU |
Invalidation Strategies
1. What Invalidation Is
- Invalidation = deciding when a cached copy is no longer valid
- The hardest part of caching
- TTL expiry: simplest, tolerates bounded staleness
- Pick the TTL from how stale the data may be
2. Delete on Write
- DB update
- cache.delete
- Next read misses
- Refill
python
db.update(key, value) cache.delete(key)
delete, do not set
Thundering Herd and Common Mistakes
1. Cache Stampede
- 1Hot key expires
- 2Many requests miss
- 3All hit the DB
- 4DB overloaded
2. Fixes and Penetration
- Request coalescing: per-key lock or single-flight, one rebuilds, others wait or serve stale
- TTL jitter spreads expiry so keys do not die together: ttl = base + random
- Also pre-warm or refresh early, before expiry
python
import random ttl = 300 + random.randint(0, 60) cache.set(k, v, ttl=ttl)
call-site fragment: 300 to 360 s
Caching Cheat Sheet
1. Layers and Write Patterns
- Clientbrowser
- CDNedge
- Applocal or Redis
- Databasebuffer pool
- Cache as close to the user as correctness allows
- Each layer outward is faster but staler
| Pattern | Pick for | Catch |
|---|---|---|
| Cache-aside |
Check yourself
Writers A and B update key k. Order: A writes DB, B writes DB, B sets cache, A sets cache. What do DB and cache hold?
- DB holds B's value, cache holds A's, so it is stale until the TTL.
- Fix: delete the key after the DB write; the next read refills it.
5,000 hot keys are cached at startup with ttl=300. What happens at 300 s?
- All expire together, so the misses hit the DB at once: a stampede.
- Fix: TTL jitter (base + random) and a single-flight lock per key.