Skip to main content

Caching

Learning objectives
  • Choose between cache-aside, read-through, write-through, write-behind and refresh-ahead for a given consistency and durability requirement
  • Explain the race conditions between a cache and its database and pick a mitigation (TTL, delete-on-write, versioned sets, leases, CDC invalidation)
  • Protect a database from stampedes, hot keys, penetration and avalanche
  • Decide what a bank must not cache, and design a safe way to serve balances quickly

TL;DR​

  • A cache trades freshness for latency and load. Every cached value has a staleness budget; make it explicit.
  • Cache-aside (app reads cache, falls back to DB, then populates) plus update DB then delete the key is the default. It still has a rare stale-set race; TTLs bound the damage.
  • Write-behind risks losing acknowledged writes. Never use it for money, orders or anything you must not lose.
  • Protect the origin: single-flight / request coalescing and probabilistic early refresh against stampedes; L1 in-process copies or key replication for hot keys; negative caching and Bloom filters against penetration; TTL jitter and warm-up against avalanche.
  • Multi-level caches (in-process → Redis → DB) cut latency further but multiply invalidation paths.
  • In banking, never authorize a debit from a cached balance. Display balances may be cached with an "as of" time; the authoritative check is a conditional update in the ledger.

Why it matters​

  • E-commerce: product detail pages are read ≈ 100× more than they change. Without a cache, a sale event turns into a database outage. With a naive cache, the moment a hot product's key expires, 50,000 requests hit the database at once.
  • Banking: bank codes, BIN tables, merchant category codes, branch lists, product configuration and FX display rates are ideal cache candidates. Balances, available credit, and limit counters are not — serving a stale balance can approve an overdraft or show a customer money that is not there, which is both a loss and a complaint to the regulator.
  • Interviews: "add a cache" is easy; interviewers probe invalidation, consistency, failure of the cache itself, and what happens at expiry under load.

Core concepts​

Where caches live​

Each layer closer to the user is faster and cheaper per hit but harder to invalidate. A useful mental model: latency improves by roughly an order of magnitude per layer you skip (DB query ≈ ms, Redis ≈ sub-ms to 1 ms, in-process ≈ 100 ns), and invalidation reach gets worse (you can delete a Redis key; you cannot delete what is in a customer's browser).

Read and write patterns​

Cache-aside (lazy loading). The application owns the logic.

  • Only requested data is cached; cache failure degrades to DB reads instead of an outage.
  • On write, delete rather than update the key: deletes are idempotent and avoid two concurrent writers leaving the cache with the older value.

Read-through. The cache (or a library in front of it) loads from the DB on a miss. Same semantics as cache-aside, but loading logic is centralised — useful for in-process caches like Caffeine-style loaders.

Write-through. Writes go to the cache layer, which synchronously writes the DB before acknowledging. The cache is always populated with fresh data, at the cost of write latency and caching data nobody reads.

Write-behind (write-back). Writes go to the cache and are acknowledged; the cache flushes to the DB asynchronously, often batched. Very fast writes and write coalescing (good for counters, view counts, analytics), but a cache node failure loses acknowledged writes, and DB constraints are checked too late to reject the request.

Refresh-ahead. Hot entries are refreshed in the background before they expire, so users rarely see a miss. Good for a small set of known-hot keys (homepage, flash-sale product, FX rate table); wasteful for the long tail.

PatternRead pathWrite pathConsistencyDurability risk
Cache-asideApp checks cache, loads DB on missApp writes DB, deletes keyEventual, bounded by TTL and racesNone (DB is truth)
Read-throughCache loads DB on missUsually paired with write-through or deleteSame as cache-asideNone
Write-throughAlways warmCache writes DB synchronouslyStrong-ish for single writerNone if DB write is synchronous
Write-behindAlways warmCache acks, flushes laterCache ahead of DBLoses unflushed writes
Refresh-aheadRare misses for hot keysIndependentBounded by refresh intervalNone

Eviction policies​

When memory is full, something must go.

  • LRU (least recently used): good default for recency-driven access (sessions, recently viewed products).
  • LFU (least frequently used): better when a stable set of items is popular (bestsellers, reference data), resists one-off scans pushing out hot data.
  • TTL-based: items expire after a fixed time regardless of memory — this is primarily a freshness tool, not an eviction policy.
  • Admission policies (TinyLFU, W-TinyLFU): decide whether a new item is worth admitting at all. Libraries such as Caffeine (Java) and Ristretto (Go) use them for high hit ratios.

Redis exposes these through maxmemory-policy: noeviction (writes fail when full — the default, and a surprise for many teams), allkeys-lru, allkeys-lfu, volatile-lru, volatile-lfu (only keys with a TTL), volatile-ttl, and random variants. Redis's LRU and LFU are sampled approximations. Use allkeys-* for a pure cache; use noeviction for a Redis that holds data you cannot lose (locks, rate-limit counters you rely on, queues). Do not mix the two roles in one instance. See Redis Deep Dive.

Invalidation strategies​

StrategyHowStaleness windowNotes
TTL onlyKey expires after N secondsUp to NSimplest; choose N from the business staleness budget
Delete on writeWriter deletes key after DB commitSmall, but racyDefault for cache-aside
Event-driven (CDC)A consumer of the DB change stream deletes or updates keysReplication delay of the streamCatches writes from every service and batch job, ordered by commit
Versioned keysKey includes a version (product:42:v17) or content hashZero for new readersOld versions age out; great for immutable data and CDN assets
Pub/sub broadcastWriter publishes an invalidation; every L1 cache drops the keyDelivery delay; lost messages leave staleness until TTLNeeded for in-process caches

Consistency with the database​

Even "update DB, then delete key" has a race:

It needs a slow reader and a write squeezed into a narrow window, so it is rare — but at millions of reads per minute, rare happens daily. Mitigations, from simplest:

  1. TTL as a safety net. Every entry expires; the race costs at most one TTL of staleness.
  2. Delayed double delete. Delete after commit, and again a few hundred milliseconds later. Cheap, narrows the window, not a guarantee.
  3. Versioned conditional set. Store a version (row version or updated_at) with the value and only set if the incoming version is newer — a short Lua script in Redis makes the compare-and-set atomic.
  4. Leases. On a miss, the cache hands out a lease token; a later SET is accepted only with a valid token, and a delete invalidates outstanding leases. Facebook's memcache paper describes this, and the same mechanism throttles stampedes.
  5. CDC-driven invalidation. Invalidate from the database's ordered change stream (via Debezium or similar), so the last invalidation always follows the last commit. See Transactional Outbox & CDC.

Also avoid "delete key, then update DB": a reader can repopulate the old value between the two steps, which is a much wider window.

Stampede (thundering herd)​

When a hot key expires, every concurrent request misses and recomputes it, hammering the DB with identical queries.

  • Single-flight / request coalescing: within a process, only one goroutine loads a given key; the others wait for its result (golang.org/x/sync/singleflight). Proxies and CDNs do the same ("collapsed forwarding"). With N instances, at most N loads instead of thousands.
  • Distributed lock or lease: one caller across the fleet recomputes (via SET key:lock NX PX 5000); others serve the stale value or wait briefly.
  • Serve stale while revalidating: keep a soft expiry inside the value and a longer hard TTL in Redis; after the soft expiry, one caller refreshes while everyone else gets the slightly old value.
  • Probabilistic early expiration (XFetch): each reader, as expiry approaches, recomputes early with a probability that rises as the deadline nears and with how expensive recomputation is. Refreshes are spread out without any coordination.
  • TTL jitter: avoid many keys created together expiring together.

Hot keys​

A single key receiving a disproportionate share of traffic — the flash-sale product, a viral listing, a global config blob, the "USD/VND rate" — saturates the one Redis shard that owns it, no matter how many shards you add.

  • L1 in-process cache with a TTL of a second or two: 100 API pods each hit Redis once per second instead of thousands of times.
  • Key replication: write the value to product:42#0 … product:42#7 (on different shards) and read a random replica; invalidation must delete all copies.
  • Read from replicas for read-only hot keys.
  • Split big values: a 2 MB key read 10,000 times per second is 20 GB/s of network; store smaller pieces or compress.
  • Detect them: client-side sampling of key access, proxy metrics, or redis-cli --hotkeys (works with an LFU eviction policy).

For write-hot keys such as a stock counter, split the counter into buckets on different shards and decrement any bucket with remaining stock. See Inventory & Flash Sales.

Penetration and avalanche​

Cache penetration: requests for keys that do not exist (random order ids from a scraper, enumeration attacks) always miss and always hit the DB.

  • Negative caching: store a "not found" marker with a short TTL (30–60 s).
  • Bloom filter of existing ids in front of the cache: a "definitely not present" answer skips both cache and DB. False positives just fall through to normal lookup.
  • Validate input before lookup: id format, check digit, ownership (see Unique ID Generation), and rate-limit per client.

Cache avalanche: a large fraction of keys disappear at once — because they were bulk-loaded with the same TTL, or because the cache cluster restarted — and the DB receives the full read load.

  • TTL jitter; staggered warm-up before opening traffic; replicated, persistent cache nodes for critical data.
  • Protect the DB anyway: connection-pool limits, circuit breakers and load shedding so a cold cache causes slowness, not a DB crash (see Resilience Patterns).

Multi-level caches​

An L1 in-process cache (bounded size, TTL of seconds) in front of L2 Redis gives ≈ 100 ns hits for the hottest data and shields Redis from hot keys. The cost is that you now have N independent copies of each hot key, one per pod. Rules of thumb:

  • Keep L1 TTL short (1–10 s) and treat it as the staleness budget for that data.
  • Broadcast invalidations (Redis pub/sub or a Kafka topic) for faster convergence, but never rely on them alone — messages can be lost; the TTL is the guarantee.
  • Use L1 only for data where per-pod divergence is acceptable for a few seconds: catalog, config, FX display rates — not inventory decisions or balances.

Caching in banking: balances and other money data​

What not to cache as a basis for decisions:

  • Account balances and available balances used to approve a debit, transfer or card authorization.
  • Credit limits, daily transfer limit counters, overdraft headroom.
  • Fraud or AML decisions that must reflect the latest state (a just-frozen account).
  • FX rates used to execute a conversion — issue a quote with an id and expiry instead, and honour exactly that quote.

What caches well: reference data (bank and branch codes, BIN ranges, MCC tables, holiday calendars), product and fee configuration, customer profile data for display, statement pages for closed periods (immutable), FX rates for display.

If you must serve balances fast (the mobile home screen is the most-hit endpoint in a bank app):

  1. Separate display from authorization. The home screen shows a cached or read-model balance labelled with "as of 10:42:15"; the debit path never reads it.
  2. Authoritative check in the ledger. Debits use a conditional update or a lock in the system of record, for example UPDATE accounts SET available = available - $1 WHERE id = $2 AND available >= $1, in the same transaction as the ledger entries (see Double-Entry Ledger Design and Locking & Concurrency Control).
  3. Update the display cache from the ledger's change stream, with the account's version number and a versioned conditional set so an older event never overwrites a newer balance.
  4. Short TTL (seconds) as a safety net, and on the screen right after the customer's own transfer, read from the primary (read-your-writes).
  5. If Redis must hold authoritative counters (some wallets reserve funds in Redis for speed), it is no longer a cache: configure persistence and replication accordingly, use synchronous replica acknowledgement where needed, and reconcile it against the ledger continuously (see Reconciliation & Settlement).

Trade-offs​

OptionStrengthsWeaknessesChoose when
Cache-aside + delete on writeSimple, resilient to cache failureStale-set race, cold missesDefault for read-heavy entities
Write-throughAlways warm, simple readsWrite latency, caches unread dataRead-after-write heavy data with a single writer
Write-behindFastest writes, coalescingData loss on cache failure, late constraint errorsCounters, metrics, non-critical aggregates
Refresh-aheadHot keys never missWasted refreshes for cold keysSmall set of known-hot keys
Short TTL onlyTrivial, bounded stalenessLoad proportional to key count / TTLData with a clear staleness budget
CDC invalidationOrdered, catches all writersPipeline to build and runMany writers, batch jobs, strict freshness
L1 in-processFastest, shields hot keysN copies, invalidation fan-outCatalog, config, reference data
RedisShared, rich data types, persistence optionsNetwork hop, single-threaded per shardMost shared caches
MemcachedSimple, multithreaded, very fast for plain KVNo persistence or rich typesLarge, simple KV caches

In practice​

  • Size the working set, not the dataset. If 5% of 10 M products drive 80% of views and each cached product is ≈ 2 KB, 500k × 2 KB ≈ 1 GB — a small Redis.
  • Measure hit ratio per key prefix, not globally; a 95% global hit ratio can hide a 40% hit ratio on the endpoint that hurts.
  • Key design: service:entity:version:id (for example catalog:product:v3:42). Bumping the schema version invalidates everything safely after a deploy that changes the serialized shape.
  • Timeouts: cache calls need tight timeouts (≈ tens of ms). A slow cache is worse than no cache, because it adds latency and still falls through to the DB.
  • Cache-aside in Go with single-flight, negative caching and TTL jitter:
package catalog

import (
"context"
"encoding/json"
"errors"
"math/rand/v2"
"time"

"github.com/redis/go-redis/v9"
"golang.org/x/sync/singleflight"
)

var ErrNotFound = errors.New("catalog: product not found")

const notFoundMarker = "__nf__"

type Product struct {
ID string `json:"id"`
Name string `json:"name"`
PriceVND int64 `json:"price_vnd"`
Version int64 `json:"version"`
}

type Repo interface {
GetProduct(ctx context.Context, id string) (*Product, error) // returns ErrNotFound
}

type Cache struct {
rdb *redis.Client
repo Repo
group singleflight.Group
ttl time.Duration
}

func (c *Cache) Get(ctx context.Context, id string) (*Product, error) {
key := "catalog:product:v3:" + id

raw, err := c.rdb.Get(ctx, key).Result()
switch {
case err == nil && raw == notFoundMarker:
return nil, ErrNotFound
case err == nil:
var p Product
if json.Unmarshal([]byte(raw), &p) == nil {
return &p, nil
}
// Corrupt entry: fall through and reload.
case !errors.Is(err, redis.Nil):
// Redis error or timeout: degrade to the DB, still protected by singleflight.
}

v, err, _ := c.group.Do(key, func() (any, error) {
// Detach from the first caller's cancellation so one aborted request
// does not fail every waiter, but keep a deadline.
loadCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second)
defer cancel()

p, err := c.repo.GetProduct(loadCtx, id)
if errors.Is(err, ErrNotFound) {
c.rdb.Set(loadCtx, key, notFoundMarker, 30*time.Second) // negative cache
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
if b, err := json.Marshal(p); err == nil {
c.rdb.Set(loadCtx, key, b, jitter(c.ttl))
}
return p, nil
})
if err != nil {
return nil, err
}
return v.(*Product), nil
}

// jitter returns base ±10% so keys loaded together do not expire together.
func jitter(base time.Duration) time.Duration {
return base - base/10 + time.Duration(rand.Int64N(int64(base)/5+1))
}
  • Probabilistic early expiration fits in a few lines; store delta (how long the last recomputation took) and the logical expiry alongside the value:
package catalog

import (
"math"
"math/rand/v2"
"time"
)

// shouldRefreshEarly implements XFetch: refresh before expiry with a probability
// that grows as expiry approaches and as recomputation gets more expensive.
// beta = 1 is the usual default; beta > 1 refreshes earlier.
func shouldRefreshEarly(now, expiry time.Time, delta time.Duration, beta float64) bool {
gap := time.Duration(float64(delta) * beta * -math.Log(1-rand.Float64()))
return !now.Add(gap).Before(expiry)
}

Common pitfalls​

  • Caching balances or stock for decisions. Symptom: overdrafts, oversold inventory, reconciliation breaks.
  • No TTL "because we invalidate on write". One missed invalidation path (a batch job, a manual SQL fix) leaves data stale forever.
  • Same TTL for a bulk load. Symptom: periodic DB load spikes exactly N minutes after each deploy or warm-up.
  • Redis default noeviction on a cache instance. Symptom: when memory fills, every SET fails with OOM errors and the app's write path breaks.
  • Unbounded in-process caches. Symptom: pod memory grows until OOM-kill; GC pauses lengthen.
  • Caching personalised data under a shared key. Symptom: one customer sees another customer's data — a data-protection incident.
  • Cache as hidden system of record. Sessions, carts or idempotency records stored only in a cache with eviction enabled. Symptom: random logouts, lost carts, duplicate payments when keys are evicted.
  • Synchronous cache dependency without timeouts. Symptom: a Redis failover makes every request slow by the client's default timeout.

Interview angle​

  • Where it appears: in nearly every design; specifically in catalog/product pages, flash sales, news feeds, leaderboards, and "speed up the balance screen" questions at banks.
  • Strong answer covers: what is cached and why (read/write ratio), the pattern and invalidation strategy, TTL tied to a staleness budget, what happens on cache failure, stampede and hot-key protection, and — at a bank — what must never come from cache.
  • Follow-ups: "How do you keep cache and DB consistent?", "The hot product's key expires during the sale — what happens?", "Redis goes down — what happens to the DB?", "How do you cache per-user data safely?", "Would you use write-behind for orders?"
  • Red flags: "just cache it" with no invalidation story, write-behind for financial data, caching without TTLs, unaware that the cache can fail or be cold.

Self-check​

1. Why delete the cache key after a DB update instead of setting the new value?

Two concurrent writers can commit to the DB in one order and set the cache in the opposite order, leaving the older value cached indefinitely. Deleting is idempotent and order-insensitive: the next reader loads whatever the DB has. It also avoids computing and caching values nobody may read.

2. Describe the stale-set race in cache-aside and two ways to close it.

A reader misses, reads the old value from the DB, stalls; a writer commits a new value and deletes the key; the reader then sets the old value, which stays until TTL. Fixes: versioned conditional set (only set if version is newer, atomically in Lua), leases (a delete invalidates the reader's lease so its set is rejected), CDC-driven invalidation from the ordered change stream, or at minimum a short TTL and delayed double delete.

3. A flash-sale product key gets 200k reads/s and the owning Redis shard is at 100% CPU. What do you do, immediately and structurally?

Immediately: add an L1 in-process cache with a 1–2 s TTL in the API pods, so each pod reads Redis about once per second. Structurally: replicate the key across shards with suffixes and read a random replica, serve the static part of the product from the CDN, and keep the dynamic stock state in a separate, bucketed counter. Monitor for hot keys before the next sale.

4. What is the difference between cache penetration and cache avalanche, and how do you mitigate each?

Penetration: lookups for keys that do not exist bypass the cache every time; mitigate with negative caching, a Bloom filter of valid ids, input validation and rate limiting. Avalanche: many keys vanish at once (same TTL, cache restart); mitigate with TTL jitter, warm-up, replicated cache nodes, and DB protection via pool limits, circuit breakers and load shedding.

5. Your bank's mobile home screen calls the balance endpoint 3,000 times per second. Design a safe, fast solution.

Serve a display balance from a read model or cache fed by the ledger's change stream, with versioned sets so out-of-order events cannot regress the value, a short TTL, and an "as of" timestamp in the UI. Right after the customer's own transaction, read from the primary or wait for the read model to reach the transaction's version. Debits and transfers never read this cache; they do a conditional update or locked check in the ledger.

6. When is write-behind acceptable?

When losing a small window of acknowledged writes is acceptable and writes are frequent and coalescable: page-view counters, "last seen" timestamps, analytics aggregates, non-critical recommendations. Not for orders, payments, ledger entries, inventory or anything with constraints that must reject the request.

7. Why can a slow cache be worse than no cache?

Each request now waits for the cache timeout and then still goes to the DB, so latency rises and DB load is unchanged. With many in-flight requests waiting (Little's Law), pools and goroutines pile up. Tight cache timeouts, circuit breakers on the cache client, and fallback limits avoid this.

🧠 Flashcards0/9 learned · 0 retries

Exercise​

Build and break a product cache.

  1. Run PostgreSQL and Redis locally (Docker). Create a products table with 100k rows.
  2. Implement the cache-aside Get above in a small Go HTTP service. Load-test one product id with vegeta at 5,000 RPS.
  3. Set a 5-second TTL and remove single-flight. Watch pg_stat_activity and DB query rate at each expiry. Then restore single-flight and compare.
  4. Add the versioned conditional set as a Redis Lua script and write a test that reproduces the stale-set race with deliberate sleeps, showing that the old value is rejected.

Done looks like: two graphs (or numbers) of DB queries per second at expiry with and without single-flight, and a passing race test.

Further reading​

  • Nishtala et al., "Scaling Memcache at Facebook" (NSDI 2013) — leases, regional invalidation, cold-cluster warm-up.
  • Vattani, Chierichetti, Lowenstein, "Optimal Probabilistic Cache Stampede Prevention" (VLDB 2015) — the XFetch algorithm.
  • Einziger, Friedman, Manes, "TinyLFU: A Highly Efficient Cache Admission Policy" (ACM TOS 2017).
  • Redis documentation: key eviction and maxmemory-policy (redis.io/docs).
  • golang.org/x/sync/singleflight package documentation (pkg.go.dev).
  • System Design Interview, Vol. 1 (Alex Xu), Ch. 1 on the cache tier.
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).