SD·126
Caching Architecture
Caching in depth: why caches work (locality and skew), where to cache (client, CDN, gateway, in-process, distributed, database), the patterns (cache-aside, read-through, write-through, write-behind/write-back, refresh-ahead) with code, invalidation strategies and their race conditions, TTLs and jitter, eviction policies (LRU, LFU, W-TinyLFU, ARC), cache stampede prevention (request coalescing, locks, probabilistic early expiration, stale-while-revalidate), hot-key mitigation, two-level local plus distributed caches, HTTP caching, negative caching, consistency and security pitfalls, and how to measure and size caches.
Start here: remembering answers, and when they go stale
A cache keeps a copy of an answer close to where it's needed, so the next request doesn't redo the work. It is the single most effective performance tool in system design, and the source of a whole family of bugs, because a copy can disagree with the original.
Why caches work at all: skew
A cache only helps if the same things are asked for repeatedly. A simulated cache holding just 1% of 100,000 dishes, under traffic with different amounts of skew (a Zipf distribution: a few items are very popular, most are rarely asked for):
uniform traffic (every dish equally likely) hit ratio 1.0%
mild skew (s = 0.6) hit ratio 5.3%
typical web skew (s = 0.9) hit ratio 34.1%
strong skew (s = 1.1) hit ratio 66.4%
With uniform traffic, a 1% cache catches 1% of requests: useless. Real traffic is skewed (today's specials, the home page, famous users), which is why a small cache can absorb a large share of reads.
Cache-aside: check the cache, fall back to the database
def get_dish(i):
v = redis.get(f"dish:{i}")
if v: return json.loads(v) # hit
row = db_query(i) # miss: do the real work
redis.set(f"dish:{i}", json.dumps(row), ex=60) # remember it for 60 s
return row
300 requests over 50 popular dishes, where each database query takes about 20 ms:
no cache: p50 20.73 ms p99 29.56 ms 300 database queries
cache-aside: p50 0.13 ms p99 21.97 ms 50 database queries (one per dish)
The median fell 160-fold; only the first request for each dish paid the full cost (that's the p99). The database did a sixth of the work.
The stampede
A popular key expires, and 50 requests arrive at the same moment. All of them miss, and all of them go to the database:
plain cache-aside: 24 database queries for one key
with a "single-flight" lock (SET NX): 2 database queries
On a busy site, a hot key expiring can send thousands of identical queries to the database at once and knock it over. Letting one caller rebuild the value while the others wait briefly (a lock in Redis with SET … NX PX) collapses them to one or two.
Staleness: the cost of remembering
The dish's price was changed in the database from 49 to 999. Reads through the cache with a 3-second TTL:
0.0s:49 0.5s:49 1.0s:49 1.5s:49 2.0s:49 2.5s:49 3.0s:999 3.5s:999
after "update the database, then delete the cache key": next read → 1001
For three seconds customers saw the old price. A TTL bounds how stale data can get; invalidating (deleting the key when the data changes) removes most of the staleness, at the cost of having to find every place that changes the data.
How deep to go in caching architecture
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain what a cache is, hits and misses, TTLs and why skew matters |
| L2 | Add cache-aside caching with sensible keys and TTLs to a read path |
| L3 | Explain the patterns (read/write-through, write-behind, refresh-ahead), eviction, invalidation and stampede protection |
| L4 | Diagnose stale data, stampedes, low hit ratios and hot keys from measurements |
| L5 | Design multi-layer caching (client, CDN, service, database) with consistency rules for each piece of data |
| L6 | Operate caching platforms and their consistency guarantees across many services |
Why caches work
A cache keeps a copy of data in a place that's faster or closer than the source of truth. It works because real access patterns are skewed and local:
- Temporal locality: recently accessed data is likely to be accessed again soon.
- Spatial locality: data near recently accessed data is likely to be accessed (pages, rows on the same block).
- Popularity skew: a small fraction of items (popular products, active users, trending posts) receives most requests, often approximating a Zipf distribution.
Benefits: lower latency (memory vs disk vs network), lower load on the source (databases, third-party APIs with quotas), lower cost (fewer database instances, less egress), and resilience (serving cached data when the source is slow or down).
Costs: staleness (cached data can be out of date), complexity (invalidation is famously hard: "There are only two hard things in Computer Science: cache invalidation and naming things", attributed to Phil Karlton), memory, cold-start behaviour (an empty cache after restart can overload the source), and new failure modes (stampedes, hot keys, inconsistent caches).
Where to cache
| Layer | What to cache | Invalidation | Notes |
|---|---|---|---|
| Client (browser, app) | Static assets, API responses with Cache-Control, offline data |
TTL, revalidation (ETag), versioned URLs |
You can't purge it: only control via headers and URLs |
| CDN / edge | Public static and semi-static content, media, cacheable API responses | TTL, purge by URL or tag, stale-while-revalidate |
Huge offload; mind cache keys and personalisation |
| Gateway / reverse proxy | Whole responses for anonymous or common requests | TTL, purge | Varnish, NGINX, Envoy |
| In-process (L1) | Very hot, small, rarely changing data: config, feature flags, reference data, hot keys | TTL, local eviction, pub/sub invalidation | Fastest (no network); each instance has its own copy (inconsistent across instances); memory per instance |
| Distributed (L2) | Shared data across instances: sessions, computed views, query results, rate-limit counters | TTL, explicit delete, versioned keys | Redis/Valkey, Memcached, Hazelcast; network hop |
| Database | Buffer pool, query plan cache, materialized views | Automatic / refresh | Size memory so the working set fits |
Caching patterns
Cache-aside (lazy loading)
The application manages the cache explicitly: on read, check the cache; on miss, load from the database and populate the cache; on write, update the database and invalidate (delete) the cache entry.
// Java: cache-aside with Redis (Lettuce/Spring Data Redis), JSON values, TTL with jitter
public Product getProduct(long id) {
String key = "product:v3:" + id; // versioned key prefix (schema changes)
String cached = redis.opsForValue().get(key);
if (cached != null) return json.readValue(cached, Product.class);
Product p = productRepository.findById(id).orElseThrow(NotFound::new);
Duration ttl = Duration.ofMinutes(10).plusSeconds(ThreadLocalRandom.current().nextInt(0, 120));
redis.opsForValue().set(key, json.writeValueAsString(p), ttl);
return p;
}
@Transactional
public void updatePrice(long id, BigDecimal price) {
productRepository.updatePrice(id, price);
// delete AFTER commit so readers can't repopulate with the old row in between
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override public void afterCommit() { redis.delete("product:v3:" + id); }
});
}
// Go: cache-aside with go-redis
func (s *Store) Product(ctx context.Context, id int64) (*Product, error) {
key := fmt.Sprintf("product:v3:%d", id)
if b, err := s.rdb.Get(ctx, key).Bytes(); err == nil {
var p Product
if json.Unmarshal(b, &p) == nil { return &p, nil }
} else if !errors.Is(err, redis.Nil) {
// cache error: log and fall through to the database (cache is an optimisation)
s.log.Warn("cache get failed", "err", err)
}
p, err := s.db.ProductByID(ctx, id)
if err != nil { return nil, err }
b, _ := json.Marshal(p)
ttl := 10*time.Minute + time.Duration(rand.IntN(120))*time.Second
_ = s.rdb.Set(ctx, key, b, ttl).Err()
return p, nil
}
# Python: cache-aside with redis-py
def get_product(pid: int) -> Product:
key = f"product:v3:{pid}"
if (raw := r.get(key)) is not None:
return Product.model_validate_json(raw)
p = db.get_product(pid)
r.set(key, p.model_dump_json(), ex=600 + random.randint(0, 120))
return p
def update_price(pid: int, price: Decimal) -> None:
with db.transaction():
db.update_price(pid, price)
r.delete(f"product:v3:{pid}") # after commit
Properties: only requested data is cached; cache failures degrade to database reads; first requests after expiry are slow (misses); stale data possible within TTL or due to races (below). The most common pattern.
Read-through
The cache (or a library in front of it) loads missing entries from the source itself via a configured loader; the application only talks to the cache. Examples: Caffeine LoadingCache, Spring's @Cacheable, NCache/Hazelcast map loaders, DAX for DynamoDB. Cleaner code, and the library can coalesce concurrent misses.
// Caffeine: in-process read-through cache with size bound, expiry and refresh
LoadingCache<Long, Product> products = Caffeine.newBuilder()
.maximumSize(50_000) // W-TinyLFU eviction
.expireAfterWrite(Duration.ofMinutes(10))
.refreshAfterWrite(Duration.ofMinutes(1)) // serve stale while refreshing asynchronously
.recordStats()
.build(id -> productRepository.findById(id).orElse(null));
Product p = products.get(42L); // concurrent misses for 42 load once
Write-through
Writes go to the cache and the source synchronously (via the cache layer or the application), so the cache always holds recent data for written keys.
- Pros: reads after writes hit fresh cache data.
- Cons: write latency includes both; caches data that may never be read; still needs care when the database write fails after the cache write (or vice versa).
Write-behind (write-back)
Writes go to the cache, which acknowledges immediately and asynchronously flushes to the source later (batched).
- Pros: very low write latency; absorbs write bursts; batching reduces database load (counters, view counts, telemetry).
- Cons: data loss if the cache fails before flushing; the source is temporarily behind; ordering and conflict issues. Use only where losing recent writes is acceptable or the cache layer is itself durable/replicated (and test it).
Refresh-ahead
Proactively refresh entries before they expire (e.g. when an entry is read in the last 10% of its TTL, or by a background job for known-hot keys), so popular items never have a miss. Caffeine's refreshAfterWrite and CDNs' stale-while-revalidate implement this idea.
| Pattern | Read path | Write path | Best for |
|---|---|---|---|
| Cache-aside | App checks cache, loads on miss | App writes DB, deletes cache | General purpose |
| Read-through | Cache loads on miss | (combine with any write pattern) | Simpler code, coalescing |
| Write-through | Cache | Cache + DB synchronously | Read-after-write-heavy keys |
| Write-behind | Cache | Cache now, DB later | Write-heavy, loss-tolerant data |
| Refresh-ahead | Cache, refreshed before expiry | — | Hot keys with predictable access |
Invalidation
Strategies
- TTL-based expiry: simplest; bounds staleness to the TTL. Choose TTLs per data type from requirements ("prices may be stale for 30 s; product descriptions for 1 h").
- Explicit invalidation on write: delete (preferred over update, see below) the key when the source changes.
- Event-driven invalidation: consume change events (CDC from the database, domain events) and delete/update affected keys, including in other services' caches and in-process caches on every instance (via pub/sub broadcast).
- Versioned keys: include a version in the key (
product:42:v17or a global namespace versioncatalog:v8:product:42); changing the version makes old entries unreachable (they expire naturally). Great for bulk invalidation and schema changes. - Tag/surrogate-key purges on CDNs: tag responses with
Surrogate-Key: product-42 category-7, purge by tag when product 42 changes.
Why delete instead of update
Updating the cache on write invites races between concurrent writers: writer A updates DB to v1, writer B updates DB to v2, B writes v2 to cache, A writes v1 to cache → cache holds v1 forever (until TTL). Deleting avoids writer-writer races because the next reader loads the current value.
The read-write race in cache-aside
Even with delete-on-write, a classic race remains:
Mitigations:
- Short TTLs bound how long staleness lasts (always have a TTL as a safety net).
- Leases (Facebook's Memcache paper): on a miss, the cache hands the client a lease token; a
setis only accepted with a valid token, and adeleteinvalidates outstanding leases, so the delayed stalesetis rejected. Leases also throttle stampedes. - Versioned writes: store a version (row version/updated_at) with the value and only overwrite with a newer version (Lua script or
WATCH/MULTIcompare-and-set in Redis). - CDC-driven invalidation (Debezium → consumer deleting keys) delivers deletes after the commit, in commit order, independent of application code paths, including bulk updates done directly in SQL.
- Delayed double delete: delete on write, then delete again after a short delay (e.g. 500 ms) to catch in-flight stale sets. A pragmatic heuristic, not a guarantee.
Consistency expectations
Caches make systems eventually consistent by nature. Decide per use case:
- Read-your-writes for the writer: after a user updates their profile, bypass or update the cache for that user's own reads (or read from the source for a short window).
- Never cache data where staleness violates invariants (inventory decrements, balances used for authorisation decisions), or cache it only as a hint with authoritative checks at write time ("probably in stock" in the listing; verified at checkout).
TTLs and jitter
- Choose TTLs from acceptable staleness, access frequency, and the cost of misses.
- Add jitter (randomise TTLs by ±10–20%) so entries cached at the same moment (after a deploy, a cache flush, a bulk load) don't all expire at once, creating synchronised miss storms.
- Use sliding expiration carefully (extends on access; can keep stale data alive indefinitely for hot keys); pair with an absolute maximum.
- Negative caching: cache "not found" results with a short TTL to prevent repeated database hits for missing keys (including attacks that request random non-existent IDs); a Bloom filter of existing keys can also reject definitely-absent keys cheaply.
Eviction policies
When the cache is full, an eviction policy decides what to drop:
| Policy | Idea | Strengths | Weaknesses |
|---|---|---|---|
| LRU (least recently used) | Evict the item unused for longest | Simple, good for recency | One large scan pollutes the cache |
| LFU (least frequently used) | Evict the least accessed | Keeps popular items | Old popular items linger; needs aging |
| FIFO / CLOCK | Evict oldest inserted / approximate LRU with a reference bit | Cheap | Ignores popularity |
| Random | Evict random items | Very cheap, surprisingly decent | Unpredictable |
| ARC (adaptive replacement) | Balances recency and frequency lists adaptively | Robust to scans | More bookkeeping (used in ZFS) |
| W-TinyLFU | Small LRU window + frequency sketch admission + segmented LRU main | Near-optimal hit rates across workloads | Implementation complexity (Caffeine, Ristretto) |
| TTL-only | Items leave only when expired | Predictable staleness | Needs enough memory |
Redis/Valkey maxmemory-policy options include allkeys-lru, allkeys-lfu, volatile-ttl and noeviction (writes fail when full: right for data you can't lose, wrong for a cache). For a pure cache, use allkeys-lru or allkeys-lfu and set maxmemory with headroom.
Cache stampede prevention
A cache stampede (thundering herd, dog-piling) happens when a hot key expires (or the cache restarts) and many concurrent requests miss simultaneously, all hitting the database for the same data, possibly overloading it, which slows the reloads, causing more misses: a positive feedback loop.
Techniques:
- Request coalescing (single-flight): within a process, only one goroutine/thread loads a missing key; others wait for its result. Go's
golang.org/x/sync/singleflight, Caffeine and most read-through caches do this per instance. - Distributed lock / lease: across instances, the first to miss acquires a short lock (
SET key:lock token NX PX 5000) and reloads; others wait briefly and retry the cache, or serve stale data. - Serve stale while revalidating: keep the stale value (logical expiry stored inside the value, longer physical TTL) and refresh in the background; users get slightly old data rather than waiting.
- Probabilistic early expiration ("XFetch", Vattani et al.): each reader recomputes early with probability increasing as expiry approaches, so one request refreshes before expiry with high likelihood and no coordination.
- Refresh-ahead for known hot keys and pre-warming caches before traffic (after deploys, before sales).
- Jittered TTLs to avoid synchronised expiry.
// Go: per-process coalescing with singleflight + serve-stale logical expiry
type entry struct {
Value json.RawMessage `json:"v"`
SoftUntil time.Time `json:"soft"` // logical expiry; physical TTL is longer
}
func (c *Cache) Get(ctx context.Context, key string, load func(context.Context) ([]byte, error)) ([]byte, error) {
if raw, err := c.rdb.Get(ctx, key).Bytes(); err == nil {
var e entry
if json.Unmarshal(raw, &e) == nil {
if time.Now().After(e.SoftUntil) {
go c.refresh(context.WithoutCancel(ctx), key, load) // stale: refresh in background
}
return e.Value, nil
}
}
v, err, _ := c.sf.Do(key, func() (any, error) { // coalesce misses in this process
v, err := c.refresh(ctx, key, load)
if errors.Is(err, errBusy) { return load(ctx) } // another instance holds the lock
return v, err
})
if err != nil { return nil, err }
return v.([]byte), nil
}
func (c *Cache) refresh(ctx context.Context, key string, load func(context.Context) ([]byte, error)) ([]byte, error) {
// optional distributed lock so only one instance refreshes
ok, _ := c.rdb.SetNX(ctx, key+":lock", "1", 5*time.Second).Result()
if !ok { return nil, errBusy }
defer c.rdb.Del(ctx, key+":lock")
v, err := load(ctx)
if err != nil { return nil, err }
b, _ := json.Marshal(entry{Value: v, SoftUntil: time.Now().Add(5 * time.Minute)})
c.rdb.Set(ctx, key, b, 30*time.Minute) // physical TTL ≫ logical
return v, nil
}
# Python: probabilistic early expiration (XFetch)
import math, random, time
def xfetch(key: str, ttl: float, beta: float, recompute):
item = cache.get(key) # {"value": ..., "delta": recompute_seconds, "expiry": ts}
now = time.time()
if item is None or now - item["delta"] * beta * math.log(random.random()) >= item["expiry"]:
start = time.time()
value = recompute()
delta = time.time() - start # how long recomputation takes
cache.set(key, {"value": value, "delta": delta, "expiry": now + ttl}, ttl=ttl)
return value
return item["value"]
# log(random()) is negative, so the check fires slightly before expiry, more likely for slow recomputes
Hot-key mitigation
A hot key receives so much traffic that the single cache node (or partition) owning it saturates: a celebrity's profile, a viral post, a flash-sale product, a global configuration key.
- Local (L1) caching of hot keys in every application instance with a short TTL (1–5 s): spreads load across the whole fleet; slight staleness. Detect hot keys dynamically (Redis
--hotkeys/LFU counters, client-side counting, sketches) and promote them. - Key replication / splitting: store copies under
key#0..key#Non different nodes and read a random replica; writes update all copies (or invalidate all). - Read replicas for the cache cluster (Redis replicas with reads allowed, Valkey cluster read-from-replica).
- Request coalescing at the proxy or CDN for identical concurrent requests.
- Rate limiting per key for abusive patterns.
- For write-hot keys (counters): shard counters and sum on read; batch increments in memory and flush (write-behind); use approximate structures (HyperLogLog for unique counts).
Local plus distributed caching
A two-level cache combines a small in-process L1 (microseconds, no network, per instance) with a shared distributed L2 (sub-millisecond, consistent across instances):
- Read: L1 → L2 → source; populate L2 then L1.
- Invalidation: delete in L2 and broadcast to all instances to drop L1 entries (Redis pub/sub, Kafka topic, or Redis client-side caching with server-assisted invalidation (
CLIENT TRACKING), where the server notifies clients when keys they cached change). - Keep L1 TTLs short to bound staleness if an invalidation message is missed.
- Size L1 small (hot set only) to protect heap/GC.
// Spring: two caches composed manually (L1 Caffeine, L2 Redis) — sketch
public Product get(long id) {
Product p = l1.getIfPresent(id);
if (p != null) return p;
p = l2Get(id); // Redis, may be null
if (p == null) { p = repo.findById(id).orElseThrow(); l2Set(id, p); }
l1.put(id, p);
return p;
}
// On change: l2Delete(id); redis.convertAndSend("invalidate:product", id);
// Every instance subscribes and calls l1.invalidate(id)
HTTP caching
HTTP has a sophisticated caching model used by browsers, CDNs and proxies (RFC 9111):
| Header | Meaning |
|---|---|
Cache-Control: public, max-age=31536000, immutable |
Cache for a year, never revalidate: for fingerprinted assets (app.3f9a1c.js) |
Cache-Control: private, max-age=0, must-revalidate |
Only the browser may cache; always revalidate |
Cache-Control: no-store |
Don't store anywhere (sensitive data) |
s-maxage=60 |
TTL for shared caches (CDN) separately from browsers |
stale-while-revalidate=30 |
Serve stale up to 30 s while fetching a fresh copy in the background |
stale-if-error=86400 |
Serve stale for a day if the origin errors |
ETag / If-None-Match |
Validator: origin returns 304 Not Modified if unchanged (saves bytes, not round trips) |
Last-Modified / If-Modified-Since |
Time-based validator |
Vary: Accept-Encoding, Accept-Language |
Cache separate variants by these request headers (keep Vary minimal; Vary: Cookie effectively disables shared caching) |
Patterns: versioned/fingerprinted URLs for static assets (cache forever, deploy new URLs); short s-maxage plus stale-while-revalidate for semi-dynamic pages; never cache personalised responses in shared caches unless the cache key includes the user (a classic data-leak bug: one user's account page served to others). CDN cache keys should normalise query strings and strip tracking parameters to improve hit ratio.
Pitfalls and security
- Cache as source of truth by accident: data only in cache (write-behind without durability) is lost on eviction or restart.
- Cold start / cache loss: if the cache is flushed or a node dies, the database must survive the miss rate; protect it with stampede controls, concurrency limits and gradual warm-up. Load-test with an empty cache.
- Cache penetration: requests for keys that don't exist bypass the cache every time → negative caching, Bloom filters, input validation.
- Cache poisoning: an attacker gets a malicious response cached under a key others will request (unkeyed headers like
X-Forwarded-Hostinfluencing the response); include all response-affecting inputs in the cache key or don't cache. - Sensitive data: don't cache secrets or personal data in shared caches without encryption/ACLs; set
no-storefor sensitive pages; namespace multi-tenant keys by tenant (chapter 133). - Serialisation versioning: changing the cached object's schema breaks deserialisation of old entries during deploys; version key prefixes.
- Unbounded caches in process memory cause OOM kills; always bound size.
- Big values: huge cached values (MBs) block single-threaded caches and saturate networks; compress, split, or don't cache.
Measuring and sizing
Monitor:
- Hit ratio (overall and per key prefix/endpoint), and byte hit ratio for CDNs.
- Latency of cache operations (p99), evictions per second (high evictions = too small), memory usage, keyspace size, connection counts, CPU of cache nodes (hot keys show as one hot shard).
- Load on the source with and without the cache (what happens if the cache disappears?).
- Staleness incidents and invalidation lag (time from DB change to cache deletion via CDC).
Size from the working set: the hot data accessed within the TTL window. Simulate with access logs (hit ratio curves for different sizes and policies) or start with an estimate (chapter 122) and adjust from eviction and hit-ratio metrics.
Lab: hit ratios, stampedes and staleness
Redis 7.0.15 and PostgreSQL 16 on the lab machine, a Python client using redis-py and psycopg 3, and a dish table of 1,000 rows. The "expensive query" is select … , pg_sleep(0.02) from dish where id = %s, standing in for a 20 ms join or aggregation.
Experiment 1: skew decides hit ratio
An in-process LRU simulation with 100,000 keys, a cache of 1,000 (1%), 200,000 requests:
| Traffic | Hit ratio |
|---|---|
| uniform | 1.0% |
| Zipf s = 0.6 | 5.3% |
| Zipf s = 0.9 | 34.1% |
| Zipf s = 1.1 | 66.4% |
Measure your own skew before sizing a cache: sort keys by request count from access logs and plot cumulative share. If the top 1% of keys carry 60% of reads, a small cache is enough; if traffic is flat, a cache barely helps and you need to make the source faster instead.
Experiment 2: cache-aside latency and load
| Setup | p50 | p99 | Database queries / 300 requests |
|---|---|---|---|
| no cache | 20.73 ms | 29.56 ms | 300 |
| cache-aside, 60 s TTL | 0.13 ms | 21.97 ms | 50 |
The hit latency (0.13 ms) is a Redis round trip from Python on the same host; across a network expect 0.3–1 ms, which is why very hot data often gets an in-process cache in front of the distributed one (with a short TTL, since each process holds its own copy).
Experiment 3: stampede protection
50 threads released together by a barrier, all reading dish:7 just after it was deleted:
plain cache-aside: 24 database queries
single-flight (SET NX PX): 2 database queries
The plain run did "only" 24 rather than 50 because Python threads take turns (the GIL), so some threads found the value already cached; with real parallel clients across many servers expect the full herd. The lock version did 2, not 1: between the rebuilder's SET value and DEL lock, a waiter could read the cache before the value was visible and then win the lock. Other remedies: probabilistic early refresh (each reader refreshes with a small probability as expiry approaches, the "XFetch" approach), refresh-ahead in the background, serving stale while revalidating, and request coalescing in a proxy (nginx proxy_cache_lock, Varnish).
Experiment 4: staleness and invalidation
DB price → 999 at t=0, TTL 3 s: 0.0s:49 … 2.5s:49 3.0s:999 3.5s:999
DB price → 1001, then DEL key: next read 1001
| Strategy | Staleness | Cost |
|---|---|---|
| TTL only | up to the TTL | none; simplest |
| delete on write | a tiny race window | every writer must know the keys |
| write-through | none for that writer | writes slower; other writers bypass it |
| change data capture → invalidate | seconds of replication lag | an extra pipeline (Debezium → consumer → DEL) |
versioned keys (dish:9:v42) |
none | readers must know the current version |
Decide per piece of data: menu text can be minutes stale; price shown in the cart can be seconds stale if checkout re-reads from the database; a payment balance shouldn't be cached on the write path at all.
Try it yourself
- Add an in-process LRU (64 entries, 1 s TTL) in front of Redis and measure p50 for hot keys.
- Implement XFetch-style probabilistic early refresh and rerun the stampede with the key about to expire rather than deleted.
- Make two threads update the same dish's price and write the cached value directly (not delete) with random delays. How often does the cache end up wrong?
- Measure Redis memory for 100,000 cached dishes (
INFO memory) and estimate how many fit in 1 GB.
Revision sheet: caching architecture
Key ideas
- Why caches work: temporal and spatial locality, and skew; hit ratio drives benefit.
- Where: browser/client, CDN, gateway, in-process, distributed (Redis, Memcached), database buffer cache.
- Patterns: cache-aside (lazy), read-through, write-through, write-behind (write-back), refresh-ahead.
- Eviction: LRU, LFU, TinyLFU/W-TinyLFU (Caffeine), random; size and TTL limits.
- Invalidation: TTL, delete-on-write, write-through, CDC-driven, versioned keys; decide staleness per data item.
- Stampedes: single-flight locks, probabilistic early refresh, stale-while-revalidate, coalescing.
- Failure modes: cold start after restart (warm-up), cache outage sending full load to the database, hot keys, memory fragmentation, inconsistent copies.
- Negative caching: cache "not found" briefly to stop repeated misses.
Numbers to remember
- Lab: 1% LRU cache → 1% hits uniform, 34% at Zipf 0.9, 66% at Zipf 1.1.
- Lab: 20.7 ms query → 0.13 ms cache hit (p50); database load cut to a sixth.
- Lab: stampede 24 → 2 database queries with a lock.
Pitfalls
- Caching without measuring skew or hit ratio.
- Updating cache values on write (ordering races) instead of deleting.
- Same TTL for every key (synchronised expiry); add jitter.
- The database sized only for cache-hit load, so a cache restart takes it down.
- Caching personalised or authorised data under shared keys.
- Unbounded caches and missing negative caching.
Glossary
- Hit ratio: hits ÷ requests.
- Cache-aside: application checks cache, loads source on miss.
- Write-behind: writes acknowledged from cache, persisted later.
- Stampede / thundering herd: many concurrent misses on one key.
- Stale-while-revalidate: serve the old value while fetching a new one.