Part 06
Caching, Scalability and Performance
Make a system faster and keep it stable under heavy or sudden load.
6.1 Caching Strategies
Chapter outcomes and context
Topics covered: 82 Caching fundamentals: cache hierarchy, hit ratio (Core) · 83 Cache-aside and read-through (Core) · 84 Write-through and write-back (Core) · 85 Cache invalidation and TTL (Core) · 86 Cache eviction policies: LRU, LFU (Core)
Learning outcomes
- Place caches along the hierarchy — browser → CDN → gateway → application → distributed cache → database buffer pool — each layer trading freshness for latency and load; reason about hit ratio from the access distribution, and measure it.
- Apply the strategies with their trade-offs:
- Cache-aside (application reads cache; on miss, reads the database and fills) — the default. Read-through — the cache itself loads on miss.
- Write-through — write cache and database synchronously: consistent, slower writes.
- Write-back — write cache, flush asynchronously: fast writes, data-loss risk.
- Handle invalidation — the genuinely hard problem: TTL as the safety net, explicit invalidation on write, event-driven invalidation (→ 119). A cache is by definition possibly stale; design the acceptable staleness window, don't discover it.
- Choose eviction: LRU (default), LFU (stable popularity) — implementation → Chapter 1.1 exercise.
6.2 Distributed Caching and CDNs
Chapter outcomes and context
Topics covered: 87 Redis and distributed caching (Core) · 88 Cache stampede (thundering herd) and hot keys (Advanced) · 89 Content delivery networks: push vs pull, edge caching (Core)
Learning outcomes
- Use Redis as the canonical example: data structures beyond strings (hashes, sorted sets, sets), TTLs, persistence options, cluster mode and key hashing (→ 74); shared state for rate limiters (Project 4).
- (Advanced) Defend against cache stampede (a popular key expires and a thundering herd hits the database): request coalescing, probabilistic early refresh, stale-while-revalidate. Handle hot keys: local near-cache, key replication, key splitting (Projects 2 and 13).
- Use CDNs: edge points of presence, pull (origin fetch on first miss — the default) vs. push (pre-populated — predictable large assets), origin shielding, cache keys, invalidation vs. versioned URLs (Project 18).
6.3 Scaling Services
Chapter outcomes and context
Topics covered: 90 Vertical and horizontal scaling (Core) · 91 Stateless and stateful services (Core) · 92 Load balancing and its algorithms (Core) · 93 Layer 4 and Layer 7 load balancing (Core) · 94 Global traffic routing: GeoDNS and Anycast (Advanced) · 95 Auto scaling (Core)
Learning outcomes
- Compare vertical scaling (bigger machine: simple, has a ceiling, single point of failure) with horizontal scaling (more machines: needs statelessness or state partitioning).
- Make services stateless — session data to a shared store or tokens (→ 162) — so any instance serves any request; recognize unavoidable state (WebSocket connections) and plan sticky routing or handoff.
- Design load balancing: round robin, least connections, consistent hashing (→ 74); health checks; no single balancer or gateway instance as a hidden single point of failure (Project 4). L4 routes by IP/port — fast, protocol-blind; L7 routes by path/header/cookie — enables canary routing and TLS termination at higher CPU cost.
- (Advanced) Route traffic globally: GeoDNS (answer DNS by client location) and Anycast (one IP announced from many sites; BGP routes to the nearest). Boundary: this topic is steady-state global routing mechanics; failover orchestration across regions is topic 196.
- Configure auto scaling on a leading metric (CPU, RPS, queue depth) with cooldowns; it lags spikes, so pair it with load shedding (→ 97).
6.4 Traffic Control and Workload Shaping
Chapter outcomes and context
Topics covered: 96 Rate limiting: token bucket, leaky bucket, sliding window (Core) · 97 Backpressure, load shedding and admission control (Advanced) · 98 Graceful shutdown and connection draining (Core) · 99 Fan-out on write vs fan-out on read (Advanced)
Learning outcomes
- Design rate limiting (primary home) per user, IP, or API key: token bucket
(allows bursts up to bucket size; refill rate = sustained rate), leaky bucket
(smooths to constant outflow), sliding window (accurate, slightly costlier);
distributed enforcement in Redis (→ 87); return 429 with
Retry-After(Project 4; abuse control in Projects 2 and 16). - (Advanced) Apply backpressure (bounded queues pushing slowdown upstream), load shedding (reject cheap and early, dropping low-priority work to protect what you accept), and admission control (decide at the front door how much enters — the waiting-room mechanism of Project 16). Overload behavior is a design decision.
- Implement graceful shutdown (primary home): stop accepting new work, finish or hand off in-flight requests, drain connections, then exit — the difference between a deploy (→ 187) and a mini-outage. Readiness probes gate this in Kubernetes (→ 183).
- (Advanced) Choose fan-out on write (push to each consumer's materialized view — cheap reads, expensive popular writers) vs. fan-out on read (compute at request time) vs. the hybrid, with cost arithmetic at stated scale (the defining decision of Project 13).
6.5 Performance Analysis
Chapter outcomes and context
Topics covered: 100 Latency, throughput and tail latency (Core) · 101 Little's Law, queueing fundamentals and Amdahl's Law (Advanced) · 102 Capacity planning (Advanced) · 103 Profiling and bottleneck analysis: utilization, saturation, thread and connection pool exhaustion, query amplification (Advanced) · 104 Performance optimization and benchmarking (Core)
Learning outcomes
- Reason with percentiles: averages lie; p99 matters because high-fan-out requests make one-in-a-hundred latency hit almost every user (tail latency amplification).
- (Advanced) Apply Little's Law (L = λW: concurrency = arrival rate × latency) to size pools, queues, and instance counts; know that queueing delay explodes as utilization approaches 1 (why systems are planned below ~70–80%); apply Amdahl's Law — speedup is capped by the serial fraction, so find the serial part before adding machines.
- (Advanced) Run capacity planning for live systems: measured baselines, growth projection, headroom policy, scheduled load tests (→ 199). Boundary: design-time estimation is topic 20.
- (Advanced) Find bottlenecks by measuring — profilers, flame graphs, traces (→ 201) — and know the classic hidden ones: utilization vs. saturation, thread and connection pool exhaustion (→ 77), and query amplification (one request fanning into N+1 queries). Fix the biggest, re-measure.
- Benchmark honestly: warmed caches, realistic data sizes and distributions, sufficient duration, percentiles reported — never means alone.
Done when you can
- Add caching with an explicit staleness window and a stampede defense.
- Design the scaling story end to end: stateless tier, balancing, autoscaling, limits, shedding, graceful shutdown.
- Choose fan-out strategy from cost arithmetic, not instinct.
- Produce a defensible capacity model and find a real bottleneck with a profiler.