03Building blocksCaching

03 · Building block

Caching

Use cache-aside, write-through, and write-behind strategies while making invalidation and hot keys explicit.
8 minConcept guideReference-informed · independently authored
01

Architecture map

See where the component sits in a real system.

Caching · system architecture
Caching system architecture. The cache is an acceleration layer; the database remains truth and refill/invalidation behavior is explicit. Request path: Application clients to Application service to Write path to Source database. Asynchronous path: Invalidation channel to Refill/refresh workers. Read path: Cache-aside read path to Distributed cache. External dependency: Consistency policy.

Write

Application clients enters through Application service. Write path owns validation and commits the durable record to Source database.

Propagate

Invalidation channel separates the committed write from background work. Refill/refresh workers can retry safely while it builds Distributed cache.

Read

Cache-aside read path serves from Distributed cache, then checks authoritative state whenever freshness, policy, or correctness requires it. It also consults Consistency policy as an explicit dependency.

Say this first: The cache is an acceleration layer; the database remains truth and refill/invalidation behavior is explicit.

Open the full whiteboard ↗
DEFEND THE DIAGRAM

Explain every boundary before adding more boxes.

The cache is an acceleration layer; the database remains truth and refill/invalidation behavior is explicit.

INTERVIEW CONTRACT

Use cache-aside, write-through, and write-behind strategies while making invalidation and hot keys explicit.

CAPACITY QUESTIONS TO QUANTIFY

Track hit ratio · origin QPS · p95 latency · eviction · hot-key share · stale age. State average and peak load, stored bytes, bandwidth or open connections, and the growth horizon before choosing a partitioning strategy.

01

End-to-end walkthrough

Trace the architecture in this order.

  1. 01
    Enter and classify the request
    Application clients → Application service

    Hot reads + writes enters over HTTPS / RPC. Application service handles identity, admission, routing, and request context; it deliberately does not own domain truth.

  2. 02
    Validate, then cross the commit boundary
    Application service → Write path → Source database

    Write path receives the command, checks invariants and retry identity, then uses write truth to update Source database. The user-visible mutation is accepted only after this boundary succeeds.

  3. 03
    Move replayable work off the request path
    Write path → Invalidation channel → Refill/refresh workers → Distributed cache

    Write path emits publish after commit; Refill/refresh workers uses consume and invalidate / refresh to build Distributed cache. Consumers must tolerate duplicate delivery and stale retries because this path is asynchronous.

  4. 04
    Serve reads from the right authority
    Application service → Cache-aside read path → Distributed cache / Source database

    Cache-aside read path uses GET key for the common, read-optimized path and strong read when correctness or repair requires authoritative state. The API must state the freshness promise instead of hiding it.

  5. 05
    Contain the dependency boundary
    Write path → Consistency policy

    dependency call crosses into Consistency policy. Treat timeouts as ambiguous, use a deadline and idempotent retry or reconciliation, and keep the core state recoverable when the dependency is unavailable.

02

Ownership ledger

Why each box exists—and what it must defend.

ComponentOwnsWhy it existsInterviewer probe
Application serviceCache policy ownerIdentity, admission, routingProtects the system edge and attaches trusted context before domain work begins.Timeout budgets, quotas, regional routing
Write pathCommit then invalidate/updateWrite invariants and retry identitySerializes or conditionally applies state changes before acknowledging success.Concurrent writes, deduplication, hot ownership
Source databaseAuthoritative valuesAuthoritative durable stateProvides the one record used to resolve disputes, recover, and rebuild projections.Partition key, replication, consistency
Invalidation channelVersioned key changesDurable asynchronous handoffAbsorbs bursts and lets slow or optional work retry independently of the request.Ordering key, lag, retention, dead letters
Refill/refresh workersSingle-flight + prewarmReplayable processingRuns expensive, fan-out, or side-effecting work with leases and bounded retries.Idempotency, poison work, autoscaling
Distributed cacheTTL + version + evictionRebuildable query stateShapes data for the dominant reads without weakening the write-side invariant.Freshness, versioning, rebuild time
Cache-aside read pathHit, miss, coalesceRead composition and freshness policyChooses authoritative or derived state and returns a stable client contract.Fan-out, cache policy, partial results
Consistency policyFreshness + negative cacheExternal capability, not local truthKeeps a specialized or third-party concern behind a replaceable contract.Ambiguous timeout, circuit breaking, fallback
03

Physical design

Name the database, shard key, indexes, and guarantees.

Database + storage
Redis Cluster/Memcached provides shared cache; optional local L1 serves immutable hot values; the origin database remains truth.
Partitioning / sharding
Hash full keys across virtual slots; use hash tags only for required colocation and replicate/memoize proven hot keys.
Indexes
Direct key lookup, TTL expiry, frequency sketch/LFU admission, and per-tenant memory accounting.
Replication + consistency
Cache-aside is eventual. Source versions or versioned keys are required where stale data changes behavior; cache loss must be survivable.
Cache, queue + recovery
Use miss coalescing, stale-while-revalidate, negative caching, jittered TTLs, and origin admission control.
Capacity math
Estimate object size, working set, hit target, QPS, TTL churn, hot-key share, eviction, and origin capacity at zero hits.
Alternative rejected
Write-through simplifies callers but couples writes to cache health; cache-aside is the default unless synchronous population is required.
04

Deep-dive candidates

Pick one risk and explain the mechanism, alternative, and cost.

Cache-aside

The application checks cache, reads the origin on a miss, and fills the value. It is flexible but needs stampede control.

Tie the mechanism back to Source database, Distributed cache, and the stated track hit ratio · origin qps · p95 latency · eviction · hot-key share · stale age envelope.
Read-through and write-through

A cache layer owns loading or synchronously updates cache and origin, simplifying callers while increasing coupling.

Tie the mechanism back to Source database, Distributed cache, and the stated track hit ratio · origin qps · p95 latency · eviction · hot-key share · stale age envelope.
Write-behind

Buffer writes through the cache only when temporary inconsistency and loss risk are acceptable and recovery is designed.

Tie the mechanism back to Source database, Distributed cache, and the stated track hit ratio · origin qps · p95 latency · eviction · hot-key share · stale age envelope.
05

Failure pressure test

Show detection, containment, recovery, and evidence.

The topic-specific correctness risk

Hot-key expiry can cause a thundering herd that overwhelms the origin.

Track failed promises at Source database and Distributed cache.
Invalidation channel or Refill/refresh workers falls behind

Bound admission, scale on oldest-work age, retry with jitter, and isolate poison work before lag becomes unbounded.

Oldest event age · retry rate · dead-letter volume · projection freshness
Source database is slow or unavailable

Apply a deadline, preserve retry identity, fail over only within the stated consistency model, and reconcile any ambiguous result.

Commit p99 · timeout rate · replication lag · recovery time
Before you finish, explicitly cover
  • Functional requirements and non-goals
  • Peak traffic, storage, bandwidth, and growth
  • Entities, APIs, idempotency, and pagination
  • Source of truth and consistency promise
  • Partition key, replicas, caches, and hot spots
  • Retries, backpressure, failover, and reconciliation
  • Latency, saturation, correctness, and recovery metrics
  • Security, migration, cost, and multi-region evolution

Read the solid request path first, stop at the source of truth, then follow the dashed event path into workers and rebuildable read models. Every arrow names a contract you should be ready to defend.

  1. 01

    Caller — Requests a cacheable object Define the output contract before moving to the next owner.

  2. 02

    Cache — Checks key and TTL Define the output contract before moving to the next owner.

  3. 03

    Origin — Loads canonical state Define the output contract before moving to the next owner.

  4. 04

    Fill path — Stores the result Define the output contract before moving to the next owner.

  5. 05

    Invalidator — Expires or updates keys Define the output contract before moving to the next owner.

  6. 06

    Protection — Coalesces misses Confirm the result and emit the evidence needed to reconcile it.

02

Lesson spine

What you need to understand.

A cache trades freshness and invalidation work for lower latency, lower cost, or origin protection.

01

Cache-aside

The application checks cache, reads the origin on a miss, and fills the value. It is flexible but needs stampede control.

02

Read-through and write-through

A cache layer owns loading or synchronously updates cache and origin, simplifying callers while increasing coupling.

03

Write-behind

Buffer writes through the cache only when temporary inconsistency and loss risk are acceptable and recovery is designed.

04

Invalidation

Use TTLs for bounded staleness, events for fast convergence, or versioned keys to make old results unable to validate new reads.

05

Eviction and hot keys

Choose LRU, LFU, or size-aware policies; replicate or memoize hot immutable values and coalesce concurrent misses.

06

Failure behavior

Define whether cache loss fails open to the origin, serves stale data, or rejects traffic to protect a fragile dependency.

03

Before the boxes

Frame the decision.

Outcome

What must work

Use cache-aside, write-through, and write-behind strategies while making invalidation and hot keys explicit.

Scale

What changes the design

Track hit ratio · origin QPS · p95 latency · eviction · hot-key share · stale age

Boundary

What owns the truth

Identify the component that commits authoritative state, then separate synchronous confirmation from derived work.

Non-goal

What stays simple

Do not add global coordination, multi-region writes, or a specialized store until a requirement earns the complexity.

04

Decision table

Make the trade-offs explicit.

DecisionDefensible positionCost to acknowledge
Primary mechanismCache-aside is resilient and simple; write-through improves coherence with more coupling.The stronger guarantee usually adds coordination, latency, state, or operational work.
Sync vs. asyncKeep only correctness-critical confirmation synchronous. Move derived views, notifications, analytics, and cleanup behind a durable boundary.Async work needs idempotency, lag monitoring, replay, and a product definition for partial completion.
Simple vs. scaledBegin with one logical owner and a clear API. Partition or replicate only the resource proven to be the first bottleneck.Migration requires stable identities, versioned contracts, backfill, and a rollback path.
05

Failure review

Design the recovery path.

DetectBoundRetry safelyReconcileLearn

Topic-specific risk

Hot-key expiry can cause a thundering herd that overwhelms the origin.

Response

Persist enough identity and state to distinguish retry, resume, compensation, and operator repair.

Dependency timeout

A timeout is ambiguous: the remote side may have failed, succeeded, or still be running.

Response

Use deadlines, bounded backoff with jitter, idempotency keys, and a status or reconciliation path.

Overload or skew

Average capacity can look healthy while a tenant, key, partition, region, or expensive request saturates one owner.

Response

Expose queue depth and hot-key share, apply backpressure, isolate tenants, and degrade optional work before correctness.

06

Evidence + level bar

Prove the design can be operated.

Core signals

Health of the promise

Measure user-visible latency or freshness, correctness drift, saturation, retry volume, and time to recover. Alert on the failed promise—not only CPU.

Mid-level

Complete and clear

Finish the happy path, identify the state owner, choose reasonable building blocks, and explain one scale mechanism.

Senior

Trade-offs and failure

Separate read and write paths, define consistency, explain partitioning, and make duplicate or partial failure safe.

Staff+

Evolution and operations

Discuss multi-region boundaries, migration, tenant isolation, capacity, observability, and how the architecture changes over time.

07

Interview language

Open the deep dive with a claim.

“For Caching, the decision I want to make explicit is this: Cache-aside is resilient and simple; write-through improves coherence with more coupling. I’ll trace the state-changing path first, show where the result becomes durable, then test the design against the highest-risk failure and our target scale.”

08 · Retrieval check

Can you defend it without the page?

  1. For Caching, where is the correctness boundary and which failure would you test first?
  2. Which component owns committed truth, and what event or response proves the commit?
  3. Where is the first scaling or coordination bottleneck under the stated envelope?
  4. What happens after an ambiguous timeout or duplicate operation?
  5. Which complexity would you remove at one hundredth of the scale?