Cache is where teams accidentally invent distributed consistency problems while thinking they're solving performance problems. This guide is the discipline that keeps caching maintainable: invalidation-first design (not tool-first), tier framework (browser through DB), TTL policy per data class, stampede + herd prevention, cross-tier coherence, observability that catches drift. Turns caching from source-of-incidents into infrastructure-that-works.
What caching discipline is (invalidation-first, not tool-first)
Caching discipline is designing invalidation before deciding on cache tools. Without discipline, teams pick Redis, wrap read queries with cache-aside, ship “cache invalidation on write,” discover stale data six months later. Cache is easy; correct cache is hard because staleness is silent.
Framed differently: cache is a tool for absorbing read load; the interesting design question is when to invalidate. Get invalidation right, TTL is a safety net. Get invalidation wrong, TTL is your primary defense against showing users incorrect state.
Not about “which cache to use.” Redis vs. Memcached vs. CDN are minor decisions compared to which tier caches which data and how invalidation propagates. Discipline includes: tier selection, invalidation strategy, TTL policy, stampede prevention, observability. Tools follow.
When to cache (and when not)
Decision framework:
Cache helps when:
- Reads dominate writes (typical ratio > 5:1).
- Same data read many times between changes.
- Read is expensive (complex query, slow external API, computation).
- Staleness within TTL window acceptable to business.
- Load reduction goal is meaningful (10%+ of DB load).
Cache hurts when:
- Reads are unique per user + rare (low hit rate; cache overhead exceeds benefit).
- Data changes on every read (invalidation storm negates cache).
- Strong consistency required in narrow window (transactions simpler).
- Cache adds latency (Redis network hop can exceed DB response for trivial queries).
- Cache infrastructure ops cost exceeds DB scaling cost.
Common mistake: caching before profiling. Cache solves specific slow-read problems; not universal fix. Profile first; diagnose bottleneck; cache if diagnosis confirms cache helps.
The cache-tier framework
Cache tiers from user to source of truth:
Browser cache (per-user, per-device). Fastest; hardest to invalidate. Versioned URLs (main.abc123.js) enable safe long TTLs. HTTP cache-control headers govern. Best for: static assets, per-user data with acceptable staleness.
CDN cache (Cloudflare, Fastly, Akamai, CloudFront). Global edge; per-URL invalidation supported but slow (30s-5m propagation). Vary header discipline critical for user-scoped responses. Best for: assets, cacheable dynamic responses, geographically distributed traffic.
Reverse-proxy cache (Varnish, nginx). Shared per-region cache. Fast invalidation; less global than CDN. Best for: dynamic responses cached at origin edge; simpler than CDN for internal.
Application cache (in-memory, per-instance). Fastest read; hardest coherence (each instance sees different data). Best for: single-instance deploys, hot lookups where staleness OK.
Distributed cache (Redis, Memcached, DynamoDB Accelerator). Shared across service instances. Coherent by construction; network overhead per read. Best for: multi-instance services needing shared cache state.
Database cache (Postgres shared_buffers, MySQL InnoDB buffer pool). DB-managed; matters for query plan cost. Tune via config; not application-controlled directly.
Selection heuristic: match cache location to access pattern. Global reads: CDN. Per-user reads: browser or CDN with vary. Cross-instance shared: distributed. Single-instance hot lookup: application. Layer as needed.
Invalidation strategy selection
Six strategies, different trade-offs:
Write-through: cache updated on every write. Simplest; write latency includes cache update. Good when: write path can afford cache-write latency; small ratio writes:reads.
Write-behind (write-back): cache updated immediately; DB updated asynchronously. Fast writes; risk of loss on failure. Rare; usually not worth complexity.
Cache-aside (lazy): app reads cache first; falls through to DB on miss; populates cache. Most common; explicit control. Good default.
TTL-only: entry expires after fixed duration; no explicit invalidation. Simple; acceptable if staleness within TTL tolerable. Good for: reference data with predictable rate of change.
Event-driven invalidation: publish invalidation event on writes; caches subscribe. Coherent; distributed system complexity. Good when: multiple services cache same data; consistency mid-window matters.
Versioned keys: encode version in key (users:v3:123); write bumps version. Old entries auto-orphan; no explicit invalidation. Good for: deploy-based invalidation, snapshot semantics.
Selection guide:
- Simple + single-service: cache-aside + TTL.
- Multi-service coherence needed: event-driven invalidation.
- Deploy-based shape changes: versioned keys.
- Write-heavy narrow consistency: write-through.
TTL policy per data class
TTL should match staleness tolerance per data class. Common taxonomy:
Personal user data: seconds. User profile fields, notifications, cart. Users notice stale personal data immediately.
Product catalog: minutes. Product details, pricing, availability. Changes hourly; user tolerance for minutes.
Reference data: hours. Countries, currencies, tax rates, categories. Rarely changes.
Session-aggregated computed: seconds to minutes. Recommendation lists, personalized homepage. Recomputable; short TTL OK.
Static assets: 1 year with versioned URLs. Immutable content; versioning invalidates.
External API responses: minutes to hours. Third-party data; often rate-limited; caching beneficial.
Search results: minutes. Result freshness expectation moderate.
Not one TTL policy; per-data-class discipline. Establish taxonomy; document; enforce via review.
Stampede prevention patterns
Cache stampede: entry expires; many concurrent requests miss simultaneously; all hit DB. Common failure at high traffic.
Probabilistic early recomputation: before TTL expires, some percentage of requests (e.g., 10% when 80% of TTL elapsed) recompute + refresh cache. Others get cached value. Load spread; stampede avoided.
Mutex around recomputation: first miss acquires lock; others wait for lock; first request populates cache. Only one recompute. Latency for waiters; no stampede.
Background refresh: separate process refreshes cache before expiry. Requests never miss; always hit fresh cache. More infra; best for hot keys.
Stale-while-revalidate: return stale value; recompute in background. Fresh cache next request. Bounded staleness; no user-facing latency.
Selection: hot keys benefit most from background refresh; general reads served by probabilistic early recomputation. Mutex safest but adds latency.
Thundering herd prevention
Thundering herd: cache infrastructure fails; all traffic falls through to origin. Broader failure than stampede.
Redundancy: multiple cache nodes (Redis Cluster, Memcached with mcrouter). One node failure loses partition; not all traffic. Failure isolation.
Graceful degradation: on cache errors, application falls through to DB with slower response; doesn't fail. User sees slow; not down.
Circuit breaker: if origin under strain, cache errors trigger circuit; short return of last-known-good or default response. Protects origin from herd.
DB read replicas: multiple DB instances absorb fall-through load. Prevents single DB from bottleneck during cache outage.
Rate limiting at origin: during herd event, throttle to sustainable rate; some requests fail with 429; others succeed. Prevents cascading failure.
Cache warming vs. lazy fill
When to pre-populate cache vs. lazy-populate on first request:
Lazy fill (default): cache populates on first miss. Simple; no warm infrastructure. First user pays latency; subsequent hit. Fine for: unpredictable traffic, moderate volume, cost-sensitive.
Cache warming: pre-populate expected hot keys. Batch job runs pre-traffic; hot keys ready. More complex; needs prediction. Fine for: predictable spikes (Black Friday, product launches), first-user experience critical.
Selection: lazy default; warm for specific known-hot-key scenarios. Not universal; adds ops complexity.
Cross-tier coherence
Multiple cache tiers create coherence risk. CDN caches for 5m; app cache for 1m; DB is truth. What does user see?
Coherence discipline:
- TTL layering: shorter TTL at edges (CDN 5m); longer near source (app cache 1m; DB indefinite). Prevents outer tiers holding stale beyond inner refresh.
- Invalidation propagation: writes invalidate all tiers explicitly. Not just DB; also purge CDN + app cache. Requires purge tooling per tier.
- Version-based coherence: URL version bumps invalidate all layers automatically (product.abc123.json → product.def456.json). No purge needed.
- Vary discipline: user-scoped responses need Vary: Cookie or Vary: Authorization to prevent CDN serving one user's data to another.
Common mistake: CDN + app cache with same TTL and unclear invalidation. Users see different data across request patterns; hard to debug.
Cache observability (hit rates, freshness, cost)
Cache without observability = flying blind. Instrument at multiple levels:
Per-tier hit rate: not overall (hides tier-specific drops). Per key pattern (product:*, user:*, session:*). Drop in specific pattern signals issue.
Freshness sampling: background job pulls cached value + DB value; compares. Unexpected divergence → alert. Bounded by TTL + invalidation SLA; discrepancy beyond bounds indicates bug.
Cache infrastructure metrics: Redis memory usage, eviction rate, connection count, latency. Under-provisioned = eviction spike + hit-rate drop; over-provisioned = wasted cost.
Downstream impact: DB CPU, connection pool, slow query count. Caching should reduce all three; measure both before + after.
User-facing latency: p50 + p99 on cached vs. uncached endpoints. Cache hit should be dramatically faster. Widening gap = misconfiguration.
Cost metrics: per-tier compute cost of cache infrastructure. If cache cost exceeds DB savings, cache is net negative.
Failure patterns to prevent
Common failures in mature cached systems:
Cache stampede. Entry expires; concurrent requests all recompute. Fix: probabilistic early recomputation or mutex.
Thundering herd. Cache fails; all traffic hits DB. Fix: redundancy + graceful degradation.
Cache poisoning. Bad data cached; every user sees it. Fix: validation before caching; TTL as safety net.
Stale data past acceptable window. TTL too long or invalidation broken. Fix: per-data-class TTL policy; invalidation monitoring.
Cross-tier incoherence. CDN + app + DB each have different snapshot. Fix: consistent TTL layering; explicit invalidation propagation.
Cost/hit-rate misalignment. Caching wrong things = memory cost without hit-rate benefit. Fix: per-pattern metrics; drop low-hit-rate patterns.
Silent memory exhaustion. Cache fills; LRU eviction; hit rate drops without alert. Fix: memory + eviction monitoring; alarms.
Version-key drift. Multiple services use different version schemes; incompatible invalidation. Fix: centralized versioning convention.
Migration: adding cache to existing system
Adding cache to previously-uncached system:
Phase 1: profile. pg_stat_statements or equivalent identifies top queries by total_time. Usually pareto: 10-20 queries = 70%+ of load. Cache candidates.
Phase 2: pilot one query. Cache-aside on one query. Measure: hit rate, latency improvement, DB load reduction. Validate assumptions before broader rollout.
Phase 3: tier by data class. Group queries by staleness tolerance; apply TTL + invalidation strategy per class. Don't cache everything the same way.
Phase 4: cross-service invalidation. When multiple services cache same data, add event-driven invalidation. Prevents drift.
Phase 5: observability. Per-tier hit rate, freshness sampling, cost tracking. Discipline enforcement infrastructure.
Duration: weeks not months for moderate scope. Larger systems: quarter.
Metrics that matter
Track these:
Hit rate per tier: per key pattern. Target: 85%+ for productive tiers; below signals design issue.
Freshness sampling accuracy: percentage of samples matching source. Target: 99%+ within TTL window.
DB load reduction: before + after cache introduction. Signal of cache value.
Cache latency (p99): should be dramatically less than DB latency. Cache slow = cache misconfigured.
Eviction rate: should be low for stable working set. High + hit-rate drop = memory under-provisioned.
Cache cost per query saved: ratio of cache infrastructure cost to compute cost saved. Should favor cache dramatically.
Cross-tier consistency: automated checks confirm CDN + app + DB return consistent (within tolerance) data.
What to do next
If not caching yet and DB is stressed: profile first. Top 10 queries usually dominate; cache those specifically. Don't cache-everything.
If caching but hit rate under 80%: audit per-pattern. Overall averages hide tier-specific issues.
If caching but invalidation unclear: this guide's invalidation strategy section is the framework. Pick per data class; document; enforce.
If caching but no observability: instrument. Per-tier hit rate; freshness sampling; cost tracking. Can't tune what you can't see.
Combined with caching-architect subagent for design decisions and the caching case study in how we cut DB load 60%, this is the discipline for making cache infrastructure that ships value rather than incidents.