Skip to main content

Caching Fundamentals

1. Executive Summary​

Caching stores copies of data closer to consumers or in faster storage tiers to reduce latency, database load, and cost. A cache trades freshness for speed—by definition, cached data may be stale relative to the authoritative source. Principal architects must choose cache placement (client, CDN, application, database), population strategy (lazy vs eager), consistency model (TTL, invalidation, write-through), and eviction policy under memory pressure.

Core patterns include cache-aside (application manages cache), read-through and write-through (cache library coordinates with backing store), write-behind (async write-back), and refresh-ahead. Metrics that matter: hit ratio, latency percentiles, staleness SLA, and thundering herd risk on expiry.

This chapter covers caching theory, pattern mechanics, consistency tradeoffs, failure modes, sizing, security, cost, production systems, and interview framing for systems from read-heavy APIs to global content delivery.

2. Why This Topic Matters​

Caching appears in virtually every system design interview: "Design Twitter's timeline", "Scale product catalog reads", "Reduce database load 10×." Weak answers say "add Redis."

Strong candidates explain:

  • Cache-aside is the default but requires careful invalidation on writes.
  • TTL alone does not guarantee consistency—it bounds staleness.
  • Hot keys can melt a single Redis shard.
  • Thundering herd on expiry causes latency spikes and DB overload.
  • CDN caches at the edge; application cache caches computed aggregates.

Production incidents include serving stale prices, cache stampede during viral traffic, OOM from unbounded caches, and security leaks from caching user-specific data in shared keys. Architects who cache without defining staleness SLAs create subtle correctness bugs.

3. Problems Being Solved​

ProblemWithout cacheWith cache
Read latencyEvery request hits DBHot data served from memory
DB loadLinear with trafficAbsorbed by hit ratio
Compute costRecompute aggregatesStore materialized results
Geographic latencySingle region DBCDN edge POPs
Spike trafficDB saturationBuffer hot keys

Caching solves read amplification and latency reduction. It does not solve write scaling alone, strong consistency without careful design, or correctness without invalidation strategy.

4. Assumptions and System Model​

Assume read-heavy workload with an authoritative data store (SQL, NoSQL, object storage):

  • Cache has finite capacity and faster but volatile storage (RAM).
  • Failures: Cache node crash (cold start), network partition to cache, stale data served.
  • Concurrent readers and writers—race between cache populate and invalidation possible.
  • Not assuming automatic coherence across all tiers unless using explicit protocol.

Cache hierarchy (typical):

TierLocationLatencyScope
L1In-process (Caffeine, Guava)μsSingle instance
L2Distributed (Redis, Memcached)sub-ms–msCluster-wide
L3CDNms–tens msGeographic
OriginDatabasems–hundreds msAuthoritative

5. Essential Terminology​

TermDefinition
Cache hitRequested key found in cache.
Cache missKey absent—fetch from origin required.
Hit ratioHits / (Hits + Misses)—primary efficiency metric.
TTL (Time To Live)Expiry after which entry is discarded.
Cache-asideApp reads cache; on miss loads DB and populates cache.
Read-throughCache loads from DB on miss transparently to app.
Write-throughWrite updates cache and DB synchronously.
Write-behindWrite updates cache; async flush to DB.
EvictionRemove entries when cache full (LRU, LFU, TTL).
Thundering herdMany requests miss simultaneously on hot key expiry.
Negative cachingCache "not found" to protect origin from repeat misses.

Mnemonic: Cache trades freshness for speed—define acceptable staleness.

6. Core Mechanism​

Cache-aside read path​

Figure 1: Application owns cache logic—most common pattern; invalidation on write is app responsibility.

Write-through vs write-behind​

Figure 2: Write-through keeps cache and DB synchronous; write-behind optimizes write latency at consistency risk.

Multi-tier cache hierarchy​

Figure 3: Each tier reduces origin load; invalidation must propagate or TTL-bound staleness accepted at each level.

7. Step-by-Step Walkthrough​

Scenario: Product catalog API—1M products, 10k hot products serve 80% traffic.

StepDesign choiceRationale
1Cache-aside with RedisTeam controls invalidation on product update
2Key: product:{id}Simple entity cache
3TTL: 300s + invalidate on writeBound staleness; immediate on admin update
4Local Caffeine cache 10k entriesSub-microsecond hot set per instance
5CDN for product imagesStatic asset edge cache
6Negative cache for missing IDsPrevent abuse scanning random IDs

Read flow with local + Redis:

StepAction
1Check local cache—hit → return
2Miss → Redis GET
3Redis hit → populate local, return
4Redis miss → DB query
5SET Redis + local with TTL

Write flow (price update):

StepAction
1UPDATE database
2DELETE product:{id} from Redis (not update-in-place)
3Local caches expire naturally or pub/sub invalidation
4Next read repopulates from DB

Why delete vs update cache on write: Concurrent writes may reorder—delete forces fresh read; avoids stale partial updates.

Cache hit ratio mathematics:

Understanding cache economics requires modeling the working set relative to cache capacity:

VariableMeaning
WWorking set size (unique keys accessed in window)
CCache capacity (keys)
αZipf skew parameter (higher = more concentrated)

For Zipf-distributed access, a small fraction of keys dominate traffic—often 20% of keys serve 80% of requests (Pareto principle). This means modest cache sizes achieve high hit ratios if keys are well-chosen. Conversely, uniform access patterns require cache size ≈ working set for high hit ratio.

Effective origin load = request_rate × (1 - hit_ratio). Improving hit ratio from 90% to 99% reduces origin load by 10×—not 9%. Architects present this non-linear benefit when justifying cache infrastructure spend.

Eviction policies compared:

PolicyBehaviorBest for
LRU (Least Recently Used)Evict coldest by access timeGeneral temporal locality
LFU (Least Frequently Used)Evict lowest access countStable hot set
TTL-onlyExpire by timeKnown freshness bounds
RandomEvict arbitrarySimplicity; approximate LRU
ARC (Adaptive Replacement Cache)Balance recency and frequencyMixed workloads (some libraries)

Redis maxmemory-policy options (volatile-lru, allkeys-lfu, etc.) combine TTL awareness with eviction—understand whether keys have TTL set before choosing policy.

HTTP caching layer (often overlooked):

Application caches are one tier; HTTP reverse proxies cache full responses:

HeaderEffect
Cache-Control: max-age=300CDN/browser cache 5 min
ETag + If-None-MatchConditional GET—304 Not Modified
Vary: Accept-EncodingSeparate cache entries per encoding
private vs publicUser-specific vs shared cacheability

Misconfigured Cache-Control: public on authenticated API responses is a common security and staleness bug—review in architecture sign-off.

Read-through and write-through in managed caches:

Some platforms (AWS ElastiCache with DAX for DynamoDB, Hibernate L2 with read-through) implement cache population transparently:

PatternWho loads on missInvalidation owner
Cache-asideApplicationApplication
Read-throughCache libraryLibrary + config
Write-throughCache library on writeSynchronous with DB

Read-through simplifies application code but couples you to cache provider semantics—understand failure behavior when cache and DB disagree during partial outages.

Cache warming strategies:

StrategyWhenRisk
Preload on deployKnown hot keysDeploy-time latency spike
Background refreshBefore TTL expiryComplexity
Traffic shiftBlue-green with gradual %Safer cold start
Predictive warmupML on access patternsEngineering cost

Black Friday and product launch runbooks should include explicit warmup steps—not discovered during incident.

Monitoring cache effectiveness:

MetricAlert threshold (example)
Hit ratio drop > 10% WoWInvestigate deploy or key pattern
Miss latency p99Compare to origin SLA
Eviction rate spikeMemory pressure
Redis used_memory > 80%Scale or trim TTL
Origin RPS increase with flat trafficCache degradation

Decision tree: should this data be cached?

Is read:write ratio > 10:1?
No → likely skip cache
Yes → Can data tolerate staleness > 0?
No → no cache OR read-through primary only
Yes → Is working set bounded?
No → sample/TTL + eviction policy
Yes → cache-aside with measured hit ratio target > 80%

Document the answer in the architecture decision record (ADR) for each entity type—prevents ad hoc caching in every microservice.

Cost modeling example:

AssumptionValue
Origin DB cost$2 per 1M read queries
Redis cost$500/month cluster
Hit ratio without cache0%
Hit ratio with cache95%
Read volume1B reads/month

Origin savings: 1B × 0.95 × $2/1M = $1,900/month. Net savings $1,400/month before engineering cost—positive ROI at this scale. Below ~100M reads/month, cache infrastructure may not justify dedicated Redis cluster—evaluate embedded local cache only.

Interview signal: Candidates who articulate hit ratio math, staleness SLAs per entity, and delete-on-write invalidation demonstrate production cache experience—not just familiarity with Redis commands.

8. Invariants and Guarantees​

PropertyTypeStatement
Eventual freshnessLiveness-orientedCache converges after TTL or invalidation
Strong consistency with originNot defaultRequires sync invalidation or no cache
Hit ratio stabilityOperationalDepends on workload skew—Zipf distribution common
DurabilityNot providedPure cache loss on crash—rebuild from origin

9. Failure Scenarios​

Scenario 1: Thundering herd on TTL expiry​

Setup: Hot product key expires; 10k concurrent requests miss.

Effect: DB overload; latency spike.

Mitigation: Probabilistic early expiration; request coalescing (single-flight); mutex per key.

Scenario 2: Cache penetration​

Setup: Attacker queries non-existent random IDs.

Effect: Every request hits DB.

Mitigation: Negative caching; bloom filter in front of cache.

Scenario 3: Cache avalanche​

Setup: Mass TTL expiry simultaneously (e.g., same deploy timestamp).

Effect: Cluster-wide miss storm.

Mitigation: Jitter on TTL; stagger warmup.

Scenario 4: Stale price displayed​

Setup: Price updated in DB; cache not invalidated.

Effect: Customer charged wrong amount—legal/compliance risk.

Mitigation: Write-path invalidation; short TTL for price keys; version in cache value.

Scenario 5: Redis node failure​

Setup: Shard master dies without persistence.

Effect: Cold cache—miss storm until repopulated.

Mitigation: Replication; multi-AZ; graceful degradation.

Scenario 6: Caching user-private data with wrong key​

Setup: Key profile without user ID—shared across users.

Effect: Critical security bug—data leak.

Mitigation: Key namespace includes tenant/user; security review checklist.

10. Performance Characteristics​

FactorImpact
Hit ratio 90%Origin load ÷ 10
Local vs remote cache100×+ latency difference
Serialization (JSON vs protobuf)CPU and payload size
Connection pooling to RedisAvoid per-request connect
Large valuesNetwork and memory pressure—consider chunking

Little's Law intuition: If cache serves 100k RPS at 1ms vs DB at 50ms, effective DB RPS drops with hit ratio H: DB_load = RPS × (1 - H).

11. Scalability Limits​

  • Memory bounds total cached working set.
  • Hot keys limit Redis shard throughput—single thread per key in cluster.
  • Invalidation fan-out grows with instance count for local caches.
  • CDN purge propagation delay limits global invalidation speed.

12. Operational Considerations​

  • Dashboards: hit ratio, miss latency, evictions, memory usage, connected clients.
  • Cache warming after deploy or failover.
  • Runbooks for Redis failover, memory max, slow commands.
  • Key naming conventions and TTL standards documented.
  • Load test with cache cold and hot scenarios.

13. Security Considerations​

  • TLS to Redis; ACLs per application.
  • No secrets in cache keys or values logged.
  • PII encryption; GDPR right-to-erasure requires cache purge.
  • Cache poisoning if write path compromised—authenticate cache writes.

14. Cost Considerations​

  • Redis memory is expensive vs disk—cache only high-value keys.
  • CDN egress savings vs origin bandwidth.
  • Miss cost still pays DB—low hit ratio wastes Redis spend.
  • Engineering invalidation complexity—factor into build vs buy.

15. Production Implementations​

Redis / ElastiCache​

In-memory data structure server; persistence optional; cluster mode for sharding—implementation choice for L2 cache.

Memcached​

Simple key-value; multithreaded; no persistence—pure cache semantics.

Caffeine / Guava (JVM)​

High-performance local caches with size and TTL eviction.

CloudFront / Akamai / Fastly​

CDN edge caching with purge APIs and cache-control headers.

Varnish / NGINX​

Reverse proxy HTTP caching layer.

Facebook TAO​

Social graph caching layer—anecdotal example of multi-tier graph cache at scale.

16. Alternatives and Tradeoffs​

PatternProsCons
Cache-asideFlexible; survives cache failureApp complexity
Read-throughCentralized load logicVendor lock-in to library
Write-throughCache always warm on writeWrite latency
Write-behindFast writesData loss risk on crash
Materialized views (DB)Consistency in DBLess flexible than Redis
No cacheSimplicityDB bottleneck at scale

17. Common Misconceptions​

MisconceptionReality
"Cache fixes write scaling"Primarily read optimization.
"TTL = invalidation"TTL bounds staleness; may serve old data until expiry.
"Update cache on write always safe"Race conditions—delete often safer.
"100% hit ratio needed"Diminishing returns; focus on hot set.
"CDN caches dynamic API by default"Requires explicit cache-control design.

18. Principal Architect Perspective​

  1. Define staleness SLA per entity type—prices vs avatars differ.
  2. Measure hit ratio per key pattern—not global aggregate only.
  3. Plan for cold start—warmup scripts, gradual traffic shift.
  4. Single-flight for hot keys before launch events.
  5. Security review cache keys for multi-tenant isolation.

Decision framework: Cache when read:write ratio > 10:1, data tolerates seconds of staleness, and origin cost or latency is pain point. Skip cache when consistency is legally strict and invalidation path unclear.

19. Architecture Review Exercise​

Scenario: E-commerce site caches cart:{userId} in Redis with 24h TTL; no invalidation on checkout; shared Redis cluster for prod and staging.

Review prompts:

  1. Stale cart after purchase?
  2. Staging flush impact on prod?
  3. Memory growth unbounded?
  4. Fixes?

Expected findings: Invalidate on order complete; separate clusters; shorter TTL; size limits; session binding.

20. Whiteboard Explanation​

90-second version:

"Caching stores hot data in fast memory to cut latency and database load. Cache-aside is the default: app checks cache, on miss reads DB and populates with TTL. On writes, update DB then delete cache keys—don't blindly update cache due to races. Hit ratio drives effectiveness—Zipf workloads cache well. TTL bounds staleness but isn't instant invalidation. Watch thundering herd when hot keys expire—use jitter, single-flight, or early refresh. Layer local in-process cache over Redis over CDN for static assets. Define staleness SLAs per data type. Caches fail—design miss path to survive. Never cache without tenant isolation in keys."

21. Interview Questions​

  1. Cache-aside vs read-through?

    • Signals: App manages vs library loads on miss.
  2. Write-through vs write-behind?

    • Signals: Sync consistency vs async speed.
  3. Thundering herd mitigation?

    • Signals: Single-flight, jitter, lock, early refresh.
  4. Update vs delete cache on write?

    • Signals: Delete safer for races.
  5. What metrics matter?

    • Signals: Hit ratio, p99 latency, eviction rate.
  6. When not to cache?

    • Signals: Strong consistency, low read ratio, tiny data.
  7. CDN vs Redis?

    • Signals: Edge static/semi-static vs app session/entity.
  8. Design product page cache.

    • Signals: TTL, invalidation, CDN images, local hot set.
  9. Cache penetration?

    • Signals: Negative cache, bloom filter.
  10. Hot key problem?

    • Signals: Shard limit; local replica; read replicas.

Scoring rubric:

DimensionStrongWeak
ConsistencyStaleness SLA, invalidation"Add Redis"
FailuresHerd, cold startIgnores miss path
SecurityKey namespacingShared keys

22. Interview Follow-Ups​

  1. Hit ratio dropped 20%—investigate?

    • Signals: Deploy change, TTL, key pattern shift, memory eviction.
  2. Cache Redis entirely down?

    • Signals: Circuit breaker to DB; rate limit; degrade gracefully.
  3. Global catalog consistency?

    • Signals: CDN purge delay; regional Redis; accept staleness bounds.

22A. Production Low-Level Design (Interview + Game Day)​

Multi-tier cache-aside with measured hit ratio and stampede controls. Production LLD and Game Day Standard.

Control vs data plane​

PlaneComponents
ControlTTL standards per entity, invalidate-on-write hooks, hit-ratio dashboards
DataLocal LRU (L1) → Redis (L2) → CDN (static) → DB on miss

Step-by-step read path:

StepLayerOn miss
1–2CDN / APIRoute to app for dynamic JSON
3L1 localμs latency; short TTL
4Redis L2sub-ms; shared across pods
5DB + singleflightOne loader per key; SET both tiers
6–8Write pathCommit DB → DELETE cache (not update-in-place)

Contract​

MetricTarget
Hit ratio (product GET)≥ 90% for ~10× DB reduction
StalenessPrice: invalidate + 60s TTL backup; images: immutable URL
Fail-openRedis down → DB with circuit breaker

One SLO​

Catalog read availability: p99 product GET < 200ms with ≥ 90% cache hit ratio; alert on hit-ratio drop > 10% WoW.


22B. Game Day Playbooks​

#DrillInjectDetectMitigateVerify
GD-1Redis cluster unavailableBlock L2 10 minHit ratio 0%; DB QPS spikeCircuit-break to DB; rate limitNo total outage; p99 bounded
GD-2TTL thundering herdAlign TTL on hot keys; spike readsMiss storm; DB saturationSingleflight + TTL jitter≤1 DB query per key per window
GD-3Stale price after promoSkip invalidate on writeSupport tickets; version mismatchEnable write-path DELFresh price within SLA

GD-2 — Thundering herd on TTL expiry​

23. Strong Answer Example​

Question: "Reduce DB load for read-heavy product API 10×."

Answer this as a 45-minute design discussion using the PRACTICE framework. Below is how a strong student sounds aloud—hit ratio math + cache-aside, not just "add Redis."

PRACTICE interview answer map for 10× DB load reduction via caching

Figure A: PRACTICE map — Problem → Requirements → Assumptions → Capacity → Topology → Invariants → Constraints → Evolution.


Student interview script (PRACTICE)​

P — Problem framing​

"Read-heavy product API means most traffic is GET /products/{id} (and maybe list/search). The DB is the bottleneck on QPS and cost.

Math: origin load ≈ request_rate × (1 − hit_ratio). To cut DB load 10× from an uncached baseline, I need about a 90% hit ratio (only 10% of reads hit the DB). Going from 90% → 99% would be another 10×—worth noting if they already cache poorly.

Short answer: Layered caching—CDN for static assets, in-process for hottest SKUs, Redis cache-aside for product:{id}—with TTL + write-path invalidation, stampede protection, and metrics that prove the 10×."

R — Requirements​

RequirementDesign
~10× fewer DB readsTarget ≥90% overall hit ratio on product GETs
Correct-enough catalogStaleness SLA per field (price stricter than description)
Survive Redis outageMiss path always hits DB; degrade gracefully
Admin updates visible soonExplicit invalidate after DB commit (+ TTL bound)
Hot / viral SKUsLocal cache + single-flight; don't melt origin

"I'd ask: personalized vs public product payload? Price freshness SLO? Read/write ratio?"

A — Assumptions (state aloud)​

AssumptionWhy it matters
Zipf / skewed SKU accessCaching works well; hot set fits memory
Mostly idempotent GETsSafe to cache; careful with auth/personalized fields
Product is rebuildable from DBRedis can be ephemeral
Writes are rarer than readsInvalidate-on-write is affordable
Images/CDN separate from JSON APIDifferent TTLs and purge paths

"I wouldn't cache Authorization-varying personalized carts under a shared product:{id} key."

C — Capacity (prove 10×)​

Uncached: 100k product reads/s → 100k DB reads/s
90% hit: 100k reads/s → 10k DB reads/s ← 10× win
99% hit: 100k reads/s → 1k DB reads/s ← another 10×

Redis memory: |hot SKUs| × avg JSON size × RF
Local LRU: top N SKUs (e.g. 10k–100k) in each app pod
CDN: images / public HTML fragments — often biggest origin win for pages

"I'd set a hit-ratio SLO and a DB QPS before/after dashboard—10× is a measured claim."

T — Topology (draw this)​

CDN + cache-aside topology for product API

Figure B: Client → CDN → API → local/Redis cache-aside → DB on miss; writes commit then invalidate.

Write path: Admin updates DB in a transaction → DELETE product:{id} (and related list keys) → optional pub/sub to flush local caches. TTL remains a backstop, not the only consistency tool.

Stampede control and metrics to prove 10×

Figure C: Stampede protection, TTL+invalidate, negative caching, and metrics that prove the 10×.

LayerWhat to cacheFreshness
CDNImages, maybe public HTMLLong TTL + purge on change
In-process (Caffeine etc.)Hottest product JSONShort TTL; invalidate via bus
Redis cache-asideproduct:{id}TTL (e.g. 5m) + DELETE on write
Negative cacheMissing IDsVery short TTL (e.g. 30–60s)

I — Invariants (safety)​

"Non-negotiable:

  1. DB is source of truth; cache is a performance optimization.
  2. Hit ratio target ≥90% to claim ~10× DB load reduction (from cold baseline).
  3. Invalidate on write for price/availability; TTL bounds residual staleness.
  4. Stampede control on hot-key miss/expiry (single-flight / lock / soft TTL refresh).
  5. No PII / per-user secrets in shared product keys.
  6. Miss path must work if Redis is down."

C — Constraints (second C)​

ConstraintDesign response
Thundering herd on TTLJitter TTLs; single-flight; probabilistic early refresh
Stale price after promoImmediate invalidate; shorter TTL on price fields or separate key
Cache OOMmaxmemory + eviction policy; size hot set; don't unbounded local caches
Key explosion (facets/lists)Cache carefully; short TTL; or cache IDs not full pages
Multi-regionRegional Redis; accept cross-region staleness or replicate invalidations
Cold start after flushSoft launch / warmup top SKUs before big sale

E — Evolution (prove it)​

Phased delivery:

PhaseDeliverable
M1Baseline DB QPS + p99; confirm Zipf with access logs
M2Redis cache-aside product:{id} + TTL + invalidate-on-write
M3Local LRU for hot set; CDN for images
M4Single-flight + TTL jitter; negative caching
M5Dashboards: hit ratio, DB QPS, stampede locks, stale complaints
M6Load test cold cache + Redis failure; prove ≥10× DB QPS drop

Failure modes:

FailureMitigation
"Just add Redis" with no invalidateWrite-path DELETE + TTL
Stampede melts DBSingle-flight / early refresh
Claim 10× without metricsHit ratio + DB QPS before/after
Cache personalized data wronglyKey by tenant/user or don't cache
Redis down = outageFail open to DB; circuit-break if DB overload

Observability: hit ratio by layer/prefix, DB QPS, p99 hit vs miss, eviction rate, invalidate rate, stampede wait count.


Closing line (interview)​

"So to cut DB load 10× on a read-heavy product API: I need roughly a 90% hit ratio. I'd use cache-aside Redis on product:{id}, an in-process LRU for the hottest SKUs, and a CDN for images—TTL plus invalidate-on-write, single-flight against stampedes, and negative caching for bad IDs. The DB stays source of truth. I'd prove the 10× with hit-ratio and DB-QPS dashboards, not by saying 'we added Redis.'"

Scoring signals​

StrongWeak / red flag
Hit-ratio math for 10×"Put Redis in front"
Cache-aside + invalidate + TTLTTL-only or write-through hand-wave
Stampede / hot-key planIgnores thundering herd
Layered CDN + local + RedisOne undifferentiated cache
Staleness SLA by fieldSame freshness for price and blurb
Metrics / failoverNo proof or miss-path story

Compact outline (if time-boxed to 2 minutes)​

"Need ~90% hit ratio for 10× less DB load. Cache-aside Redis product:{id}, local LRU for hot SKUs, CDN for images. TTL + invalidate on write. Single-flight against stampede. Measure hit ratio and DB QPS. DB remains source of truth."

24. Weak Answer Example​

Question: "Reduce DB load for read-heavy product API 10×."

"Put Redis in front of the database."

Why weak / red flags: No hit-ratio math, no cache-aside/invalidation pattern, no stampede/hot-key plan, no layered CDN/local strategy, no metrics to prove 10×.

25. Hands-On Exercise​

  1. Build cache-aside wrapper around SQLite product table.
  2. Measure RPS and latency with/without local cache.
  3. Simulate TTL expiry thundering herd—add single-flight mutex.
  4. Implement write invalidation vs write-update—race test.
  5. Add negative caching for random IDs.
  6. Plot hit ratio vs cache size.
  7. Document staleness SLA per entity.

26. Knowledge Check​

  1. Cache-aside miss path? (DB load, then SET cache.)
  2. Safer write strategy? (Delete cache key.)
  3. Thundering herd cause? (Simultaneous misses on hot key.)
  4. Hit ratio formula? (Hits / total requests.)
  5. CDN best for? (Static/edge-cacheable content.)

27. Flashcards​

#FrontBack
1Cache-asideApp manages cache read/write.
2Read-throughCache loads on miss.
3Write-throughSync cache + DB write.
4Write-behindAsync DB write from cache.
5TTLTime-based expiry.
6Hit ratioCache efficiency metric.
7Thundering herdConcurrent misses on expiry.
8Negative cacheCache absent keys.
9Single-flightOne origin load per key.
10Delete on writeSafer than update-in-place.

28. Cheat Sheet​

PATTERNS
Cache-aside: app GET → miss → DB → SET
Read-through: cache loads on miss
Write-through: write cache + DB sync
Write-behind: write cache, async DB

WRITE PATH
DB commit → DELETE cache keys (preferred)

HERD MITIGATION
TTL jitter
Single-flight / per-key lock
Probabilistic early refresh

TIERS
Local → Redis → CDN → DB

METRICS
Hit ratio, p99, evictions, memory

30. References​

Primary sources​

  • Lameter, C. (2013). "NUMA (Non-Uniform Memory Access) Aware Programming" — memory hierarchy concepts applicable to caching tiers.
  • Kleppmann, M. DDIA — derivation, materialized views, stream processing caches.

Engineering​

  • Redis Documentation — Caching patterns.
  • AWS ElastiCache Best Practices — sizing and eviction guidance.
  • Facebook engineering publications on TAO and cache stacks — verify current architecture independently.

Distinction​

Claim typeSource
Cache pattern definitionsDDIA; Redis docs
Thundering herd mitigationsEngineering practice
Production scale anecdotesCompany blogs—verify independently