BE·53
Caching
Making reads cheap without serving wrong data. Covers why caches work (locality and skew), local versus distributed caches, Redis in depth, the access patterns (cache-aside, read-through, write-through, write-behind), TTLs, eviction policies from LRU to W-TinyLFU, invalidation and its race conditions, cache stampedes, hot keys, and negative caching. Shown with Spring's cache abstraction, Caffeine and Redis, and compared with Go (ristretto, groupcache, singleflight), Rust (moka), .NET HybridCache, Python, Elixir (ETS, Cachex) and Memcached.
Start here: remembering answers you'll be asked again
Why caches work
The same questions arrive again and again: every visitor to the café's page asks for the same menu; a few hundred popular dishes get most of the views. A cache keeps recent answers somewhere faster than the original source, so repeats are cheap. It works because real traffic is skewed: in the lab, a cache holding just 1% of 100,000 keys answered half of all requests when popularity followed a typical power law, and 1% when every key was equally popular. Caching appears at every layer: CPU caches, the browser's HTTP cache, CDNs, in-process maps, shared stores like Redis, and the database's own buffer pool.
The price is staleness: a cached answer can be out of date. Every caching decision is a trade between speed and how wrong an answer may be, and for how long.
Cache-aside, the standard pattern
static String menu(String cafe) throws Exception {
String key = "menu:" + cafe;
String cached = (String) redis.cmd("GET", key);
if (cached != null) return cached; // hit
String fresh = loadMenuFromDb(cafe); // miss: a 50 ms query
redis.cmd("SET", key, fresh, "EX", "60"); // store with a 60-second time to live
return fresh;
}
static void updatePrice(String dish, long paise) throws Exception {
UPDATE dish SET price_paise = ? WHERE name = ?
redis.cmd("DEL", "menu:udupi"); // invalidate after writing the database
}
1st request (miss): 68.1 ms Filter coffee ₹30, Idli ₹50, Masala dosa ₹90
2nd request (hit): 0.7 ms Filter coffee ₹30, Idli ₹50, Masala dosa ₹90
3rd request (hit): 0.4 ms Filter coffee ₹30, Idli ₹50, Masala dosa ₹90
TTL left on the key: 60 s | database queries so far: 1
after a price change (miss): 51.9 ms Filter coffee ₹35, Idli ₹50, Masala dosa ₹90
next request (hit): 0.9 ms Filter coffee ₹35, Idli ₹50, Masala dosa ₹90
1,000 more requests: 76.5 ms total, database queries 0
The application owns the logic (hence "cache-aside"): look in the cache, and on a miss load from the source of truth and store the result. Hits were about 100× faster than the query, and a thousand requests cost the database nothing. Two mechanisms keep the data from going stale forever:
- A TTL (time to live,
EX 60): Redis deletes the key after 60 seconds, so the worst-case staleness is bounded even if everything else fails. - Invalidation: when the price changed, the code deleted the key, and the next request reloaded the new price. Delete rather than update the cached value (a concurrent writer could otherwise leave the older value in place), and delete after the database commit.
Where to cache
| Layer | Typical latency (lab, localhost) | Shared between instances? | Use for |
|---|---|---|---|
| In-process map (Caffeine) | 0.03 µs | No (each instance has its own copy) | Small, hot, rarely changing data: config, menus, feature flags |
| Redis / Valkey / Memcached | 14 µs (plus network in production) | Yes | Sessions, rate limits, shared computed results |
| The database itself | 20 µs for a primary-key lookup | Yes | Already fast for indexed lookups: don't cache those first |
| HTTP caches and CDNs | 0 on the server | Yes | Public responses, static assets (Volume 2) |
Note the third row: a primary-key query on a warm PostgreSQL took only 20 µs locally, close to Redis. Caching pays off for expensive results (aggregations, joins, calls to other services, rendering), not for lookups the database already answers from memory. In Spring, @Cacheable (chapter 46) wraps a method in cache-aside logic, backed by Caffeine or Redis.
What goes wrong
Caches are famously one of the "two hard things in computer science". The lab reproduces the classic failures:
- Stampede: a popular key expires and hundreds of requests miss at once, all hitting the database (50 loads instead of 1); fix with single-flight loading or a lock.
- Stale data from races: a slow reader can write an old value back after a writer invalidated it, leaving a wrong price for the whole TTL.
- Missing keys: lookups for things that don't exist never get cached and always hit the database, unless you cache "not found" briefly (negative caching).
- Full memory: without an eviction policy, Redis refuses writes when it reaches its limit.
How deep to go in caching
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 hits, misses, TTLs and invalidation; use @Cacheable |
| L2 | Implement cache-aside with Redis or Caffeine; choose keys, TTLs and serialisation |
| L3 | Explain cache layers, eviction policies, consistency strategies, stampedes, hot keys and negative caching |
| L4 | Diagnose low hit rates, stale data, stampedes, memory pressure and hot-key overload |
| L5 | Design multi-layer caching with consistency guarantees per data type |
| L6 | Run shared caching platforms (Redis clusters) and their capacity, failover and governance |
Why caching works
Locality and skew
A cache stores the result of expensive work (a database query, a remote call, a computation, a rendered page) somewhere faster and closer to where it's needed, so later requests can reuse it. It works because real access patterns are skewed: a small fraction of keys gets most of the traffic (Zipf-like distributions: the popular product, the logged-in user's profile, today's exchange rates). Vol. 1 ch. 7 covers the same principle in CPU caches: temporal locality (recently used data is used again) and spatial locality (nearby data is used next).
The two numbers that describe a cache are its hit ratio (the fraction of lookups served from the cache) and the latency difference between a hit and a miss:
effective latency = hit_ratio × hit_latency + (1 − hit_ratio) × miss_latency
local in-memory hit ≈ 0.0001 ms · Redis hit ≈ 0.3–1 ms (network) · DB query ≈ 2–50 ms · remote API ≈ 50–500 ms
95% hits from Redis in front of a 20 ms query: 0.95 × 0.5 + 0.05 × 20.5 ≈ 1.5 ms (vs 20 ms)
Caching also protects the backing system: the database sees only misses, so a 95% hit ratio cuts its read load twentyfold. That's double-edged. If the cache empties (restart, eviction storm, a bad deploy), the full load suddenly hits a database sized for 5% of it. A cache that the system can't survive without is no longer an optimisation: it's critical infrastructure, and must be treated as such.
The cost: staleness and complexity
Phil Karlton's famous line, "There are only two hard things in Computer Science: cache invalidation and naming things", is about consistency. A cache holds a copy, and copies go stale. Before caching anything, decide:
- How stale may this data be? Product descriptions: minutes or hours. Prices: maybe seconds, maybe never stale at checkout. Account balances and permissions: usually not at all, or invalidated precisely.
- Who changes it, and can they tell the cache? Data you own can be invalidated on write. Data owned elsewhere usually gets a TTL.
- What happens on a cache failure? Fall back to the source (with protection against stampedes), or degrade.
- What's the key, and what is it scoped to? Caching per-user data under a global key leaks one user's data to another, a real security incident category.
Don't cache what's cheap to compute, rarely re-read, or must be strongly consistent. Fix slow queries with indexes first (Vol. 4). A cache in front of an unindexed query hides the problem until the cache misses.
Where to cache
Cache layers
Caching happens at many layers, and a request may pass through several:
| Layer | Examples | Notes |
|---|---|---|
| Browser | HTTP cache, service worker | Cache-Control, ETags (Vol. 2 ch. 27) |
| CDN / edge | CloudFront, Fastly, Cloudflare | Public, shareable responses |
| Reverse proxy / gateway | Nginx proxy_cache, Varnish |
Whole responses |
| Application, local | Caffeine, Guava, ConcurrentHashMap memo, Go ristretto, Rust moka |
In the service's own memory: fastest, per instance |
| Application, distributed | Redis/Valkey, Memcached, Hazelcast, Infinispan, cloud-managed versions (ElastiCache, MemoryDB, Memorystore, Azure Managed Redis) | Shared across instances, over the network |
| ORM second-level cache | Hibernate L2 (with Ehcache, Infinispan, Redis) | Entity-level. Easy to misconfigure; consider it carefully |
| Database | Buffer pool, query plan cache, materialised views | Automatic or explicit |
Local versus distributed caches
| Local (in-process) | Distributed (remote) | |
|---|---|---|
| Latency | Nanoseconds to microseconds | Sub-millisecond to a millisecond (network + serialisation) |
| Capacity | Limited by heap (and GC pressure on the JVM) | Large; scales out |
| Consistency across instances | Each instance has its own copy: invalidating on one instance doesn't affect others | One shared copy: an invalidation is seen by all |
| Survives deploys | No (cold start after each restart) | Yes |
| Failure modes | Memory pressure, GC, stale per-instance copies | Network failures, cache cluster outages, hot keys, serialisation bugs |
| Cost | Free | Infrastructure to run and secure |
A common design is a two-level cache (near cache): a small local L1 with a short TTL in front of a shared L2 in Redis. Most reads hit L1. L1's short TTL bounds per-instance staleness, and invalidation messages (Redis Pub/Sub or client-side caching with server-assisted invalidation, Redis 6+ CLIENT TRACKING) can evict L1 entries across instances when data changes. .NET's HybridCache (.NET 9) packages this pattern with stampede protection and tag-based invalidation.
Redis
Redis is an in-memory data structure server. Since the 2024 licence change, the Linux Foundation's Valkey fork has been widely adopted by cloud providers, and Redis 8 added an AGPL licensing option. The protocol and core commands are compatible. What makes Redis more than a cache:
| Structure | Commands | Uses |
|---|---|---|
| Strings | GET, SET key value EX 300 NX, INCR, MGET |
Cached values, counters, locks (SET NX PX) |
| Hashes | HSET, HGETALL, HINCRBY |
Objects with fields |
| Lists | LPUSH, BRPOP, LRANGE |
Simple queues, recent-items lists |
| Sets | SADD, SISMEMBER, SINTER |
Membership, tags |
| Sorted sets | ZADD, ZRANGE … BYSCORE, ZINCRBY |
Leaderboards, rate-limit windows, priority queues, time indexes |
| Streams | XADD, XREADGROUP, XACK |
Durable-ish message logs with consumer groups |
| Bitmaps / HyperLogLog / Bloom filters | SETBIT, PFADD/PFCOUNT, BF.ADD (module or built in, depending on version) |
Compact counting, unique counts, existence checks |
Geo, Pub/Sub, Lua scripts / Functions, transactions (MULTI/EXEC) |
— | Atomic multi-step operations run server-side |
Operational essentials:
- Single-threaded command execution (I/O threads help networking): each command is atomic, but one slow command (
KEYS *, a hugeHGETALL, anO(n)operation on a big collection) blocks everyone. UseSCAN, and keep values small (≲ 100 KB as a guideline). - Memory limits and eviction: set
maxmemoryand amaxmemory-policy(allkeys-lru,allkeys-lfu,volatile-ttl,noeviction…). For a pure cache,allkeys-lfuorallkeys-lru. Withnoeviction, writes fail when memory is full. - Persistence (RDB snapshots, an AOF log): optional for pure caches. Don't treat Redis as a system of record unless you've designed for it (persistence, replication, failover semantics).
- High availability: replicas + Sentinel, or Redis Cluster (16,384 hash slots across shards; multi-key operations must stay within one slot, using
{hash tags}). Replication is asynchronous, so acknowledged writes can be lost on failover. - Clients: Lettuce (Spring's default, Netty-based, thread-safe) and Jedis in Java; go-redis and rueidis in Go; redis-rs/fred in Rust; StackExchange.Redis in .NET; redis-py in Python; Redix in Elixir. Configure timeouts, connection pools or multiplexing, and TLS and AUTH/ACLs. Never expose Redis to the internet.
Memcached is the simpler alternative: multi-threaded, strings only, LRU-evicting, no persistence and no replication. It's still excellent for pure, huge, simple caches (Facebook's famous deployment).
Access patterns
Cache-aside (lazy loading)
The application owns the logic: read from the cache; on a miss, load from the source and populate the cache. On writes, update the source and invalidate (delete) the cache entry. It's the most common pattern, because the cache stays a pure optimisation and the application controls everything:
// Spring's cache abstraction: declarative cache-aside via AOP (chapter 46; mind self-invocation)
@Configuration
@EnableCaching
class CacheConfig {
@Bean
CacheManager cacheManager() {
var caffeine = new CaffeineCacheManager("products", "prices");
caffeine.setCaffeine(Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(Duration.ofMinutes(5))
.recordStats()); // hit/miss metrics via Micrometer
return caffeine;
}
}
@Service
class ProductService {
@Cacheable(cacheNames = "products", key = "#sku", unless = "#result == null")
public ProductDto find(String sku) { return toDto(repo.findBySku(sku).orElse(null)); }
@CacheEvict(cacheNames = "products", key = "#cmd.sku()") // invalidate after the update
@Transactional
public ProductDto update(UpdateProduct cmd) { … }
@CachePut(cacheNames = "products", key = "#result.sku()") // write-through-style: always runs, updates the cache
public ProductDto refresh(String sku) { … }
@Cacheable(cacheNames = "products", key = "#sku", sync = true) // sync: one loader per key per instance (stampede)
public ProductDto findHot(String sku) { … }
}
// With spring-boot-starter-data-redis + spring.cache.type=redis, the same annotations use Redis
// (RedisCacheManager with TTLs per cache, JSON serialisation of values).
Pitfalls of the abstraction:
- Keys: the default key is built from all method parameters. Be explicit, and include tenant or user in the key for user-specific data.
- Cached objects must be immutable (or copies): a local cache returns the same instance to every caller, so a mutation corrupts it for all.
- Serialisation for remote caches: version your cached types, because a deploy that changes a DTO's shape must not crash on old cached values (use JSON and tolerant readers, or put a version in the key prefix).
@CacheEvictand transactions: evicting before the transaction commits allows a concurrent read to reload the old value from the database before the commit, then cache it. Evict after commit (Spring'sTransactionAwareCacheManagerProxy, or@TransactionalEventListener(AFTER_COMMIT)).
Read-through and write-through
- Read-through: the cache itself loads missing entries through a configured loader, so the application just calls
cache.get(key). Caffeine'sLoadingCache/AsyncLoadingCache, Hazelcast MapLoader and .NET HybridCache'sGetOrCreateAsyncwork this way. This centralises loading logic and makes per-key load coalescing natural. - Write-through: writes go through the cache to the source synchronously. The cache is updated and the source is written before the write returns. The cache is always populated with recent writes, but writes pay both latencies, and you can still have inconsistency if one of the two writes fails.
- Write-behind (write-back): writes go to the cache, and the cache asynchronously flushes them to the source, often batched. Write latency is very low and the source sees fewer writes (coalescing repeated updates), but data loss happens if the cache dies before flushing, and the source is behind. It's good for counters, metrics and view counts, and wrong for orders and money unless the cache layer is itself durable.
- Refresh-ahead: refresh popular entries before they expire, in the background, so readers never wait on a miss. Caffeine's
refreshAfterWriteserves the old value while reloading asynchronously.
// Caffeine read-through with refresh-ahead and async loading
AsyncLoadingCache<String, Price> prices = Caffeine.newBuilder()
.maximumSize(50_000)
.expireAfterWrite(Duration.ofMinutes(10)) // hard staleness bound
.refreshAfterWrite(Duration.ofMinutes(1)) // after 1 min, the next read triggers a background reload; old value served meanwhile
.executor(Executors.newVirtualThreadPerTaskExecutor())
.buildAsync((sku, executor) -> pricingClient.priceAsync(sku));
CompletableFuture<Price> p = prices.get("SKU-9"); // concurrent gets for the same key share one load
Lifetimes and eviction
TTL
A time-to-live bounds staleness when you can't (or don't) invalidate precisely, and it also bounds memory use for keys that are never read again.
- Choose TTLs from the business staleness tolerance, not convenience.
- Expire-after-write (fixed staleness bound) versus expire-after-access (idle eviction: keeps hot keys forever, so it's unsafe as a staleness bound).
- Jitter TTLs (for example, 300 s ± 10%). Entries populated together, after a deploy or a bulk load, would otherwise expire together and cause a synchronised wave of misses.
- Soft versus hard TTL: serve stale data while revalidating (like HTTP's
stale-while-revalidate), with a hard limit beyond which stale data isn't served. Serving stale data on error (stale-if-error) is a resilience tool (chapter 52).
Eviction policies
When the cache is full, which entry goes?
| Policy | Evicts | Strengths and weaknesses |
|---|---|---|
| LRU (least recently used) | The entry not accessed for the longest time | Simple, good for recency-driven workloads. A scan (one-off reads of many keys) flushes the hot set |
| LFU (least frequently used) | The entry with the fewest accesses | Keeps popular items. Old popular items linger after popularity shifts, unless counts decay |
| FIFO | The oldest inserted | Cheap. SIEVE and S3-FIFO show FIFO-based designs can match LRU hit ratios with less overhead |
| Random | A random entry | Surprisingly decent and cheap |
| TTL-based | The soonest to expire | Redis volatile-ttl |
| W-TinyLFU | Admission by estimated frequency (a compact count-min sketch with ageing) + a small LRU "window" for new items | Near-optimal hit ratios across workloads. Scan-resistant, adapts to recency or frequency. Used by Caffeine, Ristretto (Go) and moka (Rust) |
| ARC / LIRS | Adaptive recency + frequency | Strong but complex (ARC was patent-encumbered; ZFS uses it) |
Redis's LRU and LFU are approximate: it samples a few keys (maxmemory-samples) and evicts the best candidate, trading precision for speed and memory. In practice it's close to true LRU or LFU.
Size by weight, not count, if values vary widely (Caffeine's maximumWeight with a weigher). On the JVM, large local caches live on the heap and raise GC work and live-set size (chapter 40). Off-heap caches (Chronicle Map, Ehcache off-heap) or Redis avoid that.
Correctness under concurrency
Cache invalidation
Strategies, from simplest:
- TTL only: accept staleness up to the TTL. Simple and robust. Good for data you don't own.
- Delete on write (cache-aside): after updating the source, delete the key.
- Update on write: write the new value into the cache. Dangerous with concurrent writers (below).
- Event-driven invalidation: services publish change events (CDC from the database via Debezium, or domain events), and caches subscribe and evict. This works across services and for data written by other systems.
- Versioned keys: include a version in the key (
product:42:v17). Writers bump the version (stored in the source), readers build keys from the current version, and old entries age out. This avoids deletion races entirely. - Tag-based invalidation: entries are tagged (
category:shoes), and one call evicts every entry with a tag. Surrogate keys in CDNs and .NET HybridCache tags work this way.
The classic race in cache-aside. Even "delete on write" can leave stale data:
Facebook's Scaling Memcache at Facebook paper describes leases for exactly this: on a miss, the cache hands the reader a lease token. A later delete invalidates the token, and the reader's SET is rejected if its token is no longer valid. The same paper's leases also throttle stampedes. Simpler mitigations: always keep a TTL as a backstop, store a version with the value and use a conditional set (Lua script: set only if the new version > the cached version), or delete again after a short delay.
Write ordering with the database transaction: delete the cache after the transaction commits. If you delete first, a concurrent reader can repopulate the cache from the not-yet-updated database.
Cache stampede
A stampede (thundering herd, dog-piling) happens when a hot key expires or is evicted and many concurrent requests miss at once, all hitting the database for the same value. For an expensive query, that can overload the database exactly when the cache is supposed to protect it. Mitigations:
- Request coalescing / single-flight: only one loader per key, and everyone else waits for its result. Within one instance: Caffeine
LoadingCache,@Cacheable(sync = true), Go'sx/sync/singleflight, .NET HybridCache, moka'sget_with. Across instances: a short distributed lock in Redis (SET lock:key token NX PX 5000) for the loader, while others briefly wait or serve stale data. - Serve stale while revalidating: keep the expired value and let one request refresh it in the background (Caffeine
refreshAfterWrite, soft TTLs). - Probabilistic early expiration ("XFetch"): each reader recomputes early with a probability that rises as expiry approaches, so refreshes spread out instead of all landing at expiry.
- TTL jitter to avoid mass simultaneous expiry.
- Pre-warming caches before traffic arrives (after deploys, before a sale).
// Go: singleflight collapses concurrent loads of the same key within one process
var group singleflight.Group
func (s *Service) Product(ctx context.Context, sku string) (Product, error) {
if p, ok := s.cache.Get(sku); ok {
return p, nil
}
v, err, _ := group.Do(sku, func() (any, error) { // only ONE goroutine runs this per key at a time
p, err := s.repo.Find(ctx, sku)
if err == nil {
s.cache.SetWithTTL(sku, p, 1, 5*time.Minute) // ristretto
}
return p, err
})
if err != nil {
return Product{}, err
}
return v.(Product), nil
}
Hot keys
A hot key receives a disproportionate share of traffic: a celebrity's profile, the homepage configuration, a flash-sale product. In a distributed cache, a key lives on one shard, so a hot key concentrates load on one Redis node (CPU, network bandwidth) while other nodes idle. Mitigations:
- A local L1 cache in each app instance for hot keys, even with a TTL of a few seconds, which absorbs most of the load.
- Key replication / splitting: store copies under
product:42#1…product:42#8and read a random one (for reads; writes must update all copies). - Read replicas for the shard, with clients reading from replicas.
- Detect hot keys:
redis-cli --hotkeys(with LFU eviction policy), client-side metrics per key prefix, proxy statistics. - Large values on hot keys multiply bandwidth: compress, or split.
Negative caching
Caching "not found" (and some error results) prevents repeated expensive lookups for things that don't exist. That matters most for attacks and bugs: requests for random non-existent IDs bypass a cache that only stores hits and hammer the database (cache penetration).
- Cache a sentinel ("absent") with a shorter TTL than positive entries, so a newly created item becomes visible soon. Invalidate the negative entry on create.
- Spring's
@Cacheablecachesnullby default if the cache allows null values (Caffeine via the manager'sallowNullValues).unless = "#result == null"disables that, so choose deliberately. - For very large ID spaces, a Bloom filter of existing keys answers "definitely not present" cheaply before the cache and database are consulted.
- Negative-cache errors only briefly (seconds), and only for errors that are stable for that key. Otherwise a transient failure becomes a cached failure.
Caches across languages
| Ecosystem | Local cache | Distributed and abstractions |
|---|---|---|
| Java | Caffeine (W-TinyLFU, async loading, refresh-ahead), Guava Cache (older), Ehcache 3 (heap/off-heap/disk tiers) | Spring Cache abstraction (@Cacheable), JCache (JSR-107), Lettuce/Jedis/Redisson, Hazelcast, Infinispan, Hibernate L2 |
| Go | ristretto (TinyLFU-based, high-concurrency), otter (S3-FIFO), sync.Map memos, groupcache (distributed, with built-in single-flight and no invalidation: immutable keys only) |
go-redis/rueidis (rueidis supports client-side caching), x/sync/singleflight |
| Rust | moka (TinyLFU-inspired, sync and async, per-entry expiry, get_with coalescing), quick_cache, cached (memoisation macros) |
redis-rs, fred, deadpool-redis |
| C#/.NET | IMemoryCache, FusionCache |
IDistributedCache (Redis, SQL Server), HybridCache (.NET 9: L1+L2, stampede protection, tag invalidation), output caching middleware |
| Python | functools.lru_cache/cache, cachetools (TTL, LFU caches), async-lru |
redis-py, aiocache, Django's cache framework |
| Elixir/Erlang | ETS tables (in-memory, concurrent reads, per-node), Cachex, Nebulex (multi-level) | Redix, Nebulex adapters; :persistent_term for rarely changing globals |
| Node | lru-cache |
ioredis, Keyv |
| C/C++ | Hand-rolled LRU maps, CacheLib (Meta's caching engine) | hiredis, redis-plus-plus; Memcached itself is C |
Lab: hit rates, stampedes and stale data
JDK 21, PostgreSQL 16 and Redis 7.0 on one machine, using the small RESP client from Start here. Experiment 1 is an in-memory simulation (a million requests); the rest run against the real Redis and PostgreSQL.
Experiment 1: skew decides hit rate
A million requests over 100,000 keys, with an LRU cache (a LinkedHashMap in access order) of different sizes:
uniform traffic, cache holding 1% of keys: hit rate 1.0%
uniform traffic, cache holding 5% of keys: hit rate 5.0%
uniform traffic, cache holding 10% of keys: hit rate 9.9%
Zipf (s=1) traffic, cache holding 1% of keys: hit rate 50.6%
Zipf (s=1) traffic, cache holding 5% of keys: hit rate 66.5%
Zipf (s=1) traffic, cache holding 10% of keys: hit rate 73.5%
With uniform traffic, a cache is worth exactly its size; with Zipf-distributed traffic (popularity proportional to 1/rank, typical of products, pages, users and search terms), a tiny cache captures most requests, with sharply diminishing returns as it grows. Measure your own distribution before sizing a cache: the hit rate, not the cache size, is what saves the database. Caffeine's W-TinyLFU policy does better than LRU on such workloads by also tracking frequency, so one-off scans don't evict genuinely popular keys.
Experiment 2: what each layer costs
one lookup, average of 10,000: in-process map 0.033 µs | Redis on localhost 13.8 µs | PostgreSQL primary-key query on localhost 20.2 µs
An in-process map is about 400× faster than Redis, because Redis needs a network round trip even on localhost (in production add 100–500 µs within a data centre). Meanwhile, a warm PostgreSQL primary-key lookup was within 50% of Redis: caching it would add complexity and staleness for almost no gain. The rule of thumb: put small, hot, read-mostly data in-process (with short TTLs or pub/sub invalidation), put shared or large data in Redis, and cache expensive computations rather than cheap queries.
Experiment 3: stampede on expiry
The menu key (a 100 ms load) is missing while 200 requests arrive at once, served by 50 worker threads:
plain cache-aside : database loads 50, done in 169 ms
single-flight in each instance : database loads 1, done in 155 ms
Redis lock (SET NX) across instances : database loads 1, done in 128 ms
Plain cache-aside sent every concurrent miss to the database (50: one per worker thread; with virtual threads it would have been 200). For an expensive query on a popular key, that's how a routine expiry turns into a database overload. Single-flight (one CompletableFuture per key in a ConcurrentHashMap, which Caffeine's loading cache does for you) collapses concurrent misses within one instance; a Redis lock (SET lock:menu 1 NX PX 5000) collapses them across all instances, with the others polling briefly for the value. Other remedies: refresh hot keys before they expire (Caffeine's refreshAfterWrite, or probabilistic early expiration) and add random jitter to TTLs so keys loaded together don't expire together.
Experiment 4: the invalidation race
A request misses the cache and reads the price (₹30) from the database, then pauses (a GC pause, a slow network) before writing it to the cache. Meanwhile an admin updates the price to ₹35 and deletes the cache key. Then the paused request writes its value:
read-miss racing an update: database says 3500, cache says 3000 for the next 300 s
The invalidation happened, correctly, before the stale write, so it achieved nothing, and customers see the old price for five minutes. This race is rare but real at scale (Facebook's memcache paper describes it). Defences: short TTLs as the backstop; leases or version checks when writing back (write only if the key's version hasn't moved, for example with a Lua script or SET … NX plus a version number); deleting the key a second time shortly after the update ("delayed double delete"); or driving invalidation from the database's change log (CDC) instead of application code. For data where staleness is unacceptable (balances, stock at checkout), don't serve it from a cache at all.
Experiment 5: negative caching
1,000 lookups of a dish id that doesn't exist, caching only hits: database queries 1000
1,000 lookups of a dish id that doesn't exist, caching 'not found' for 30 s: database queries 1
Cache-aside only stores values that exist, so requests for missing keys (deleted items, typos, or an attacker enumerating ids) always go to the database. Caching a "not found" marker with a short TTL fixes it; keep the TTL short so newly created items appear quickly. Bloom filters do the same job for very large key spaces.
Experiment 6: when Redis is full
maxmemory 5 MB, noeviction : 3,931 writes succeeded, keys now 3931, evicted_keys:0 | then: Redis: OOM command not allowed when used memory > 'maxmemory'.
maxmemory 5 MB, allkeys-lru: 20,000 writes succeeded, keys now 3922, evicted_keys:16055
With noeviction (the default), a full Redis rejects writes, so a cache that outgrows its memory starts failing requests. As a cache, Redis should use allkeys-lru or allkeys-lfu, which evicted 16,055 keys and kept accepting writes. If one Redis instance holds both cache data and data you can't lose (sessions, rate-limit counters, queues), eviction will eventually delete the latter: use separate instances or databases with different policies, and alert on evicted_keys and memory use.
Try it yourself
- Replace the LRU in experiment 1 with Caffeine (
maximumSize) and compare hit rates on the Zipf workload. - Add ±10% random jitter to the TTLs of 1,000 keys created at once, and plot how many expire per second with and without it.
- Fix experiment 4 with a version number stored alongside the value and a Lua script that only writes if the stored version is older.
- Measure Redis
GETlatency under 100 concurrent clients withredis-benchmark -p 6390 -t get -c 100. How does p99 compare with experiment 2?
Revision sheet: caching
Key ideas
- Why: temporal locality and skewed (power-law) popularity; cost is staleness, memory, complexity and new failure modes.
- Layers: browser/HTTP and CDN, in-process (Caffeine), distributed (Redis/Valkey, Memcached), database buffer pool and materialised views.
- Patterns: cache-aside (most common), read-through, write-through, write-behind;
@Cacheable/@CacheEvict; key design (namespaces, versions), serialisation. - Lifetimes: TTLs with jitter; eviction (LRU, LFU, W-TinyLFU, random; Redis
maxmemory-policy). - Consistency: delete-after-commit invalidation, races and leases, CDC-driven invalidation, versioned keys, per-data staleness budgets.
- Failure modes: stampedes (single-flight, locks, early refresh), hot keys (local caching, key replication), negative caching, penetration, cache as a hidden dependency (cold start after a flush).
- Redis: single-threaded command execution, data structures, persistence options, replication and cluster sharding, Valkey fork.
- Elsewhere: Caffeine/Ehcache (JVM),
IMemoryCache/HybridCache(.NET), groupcache/ristretto (Go), moka (Rust),functools.lru_cacheand cachetools (Python), Cachex (Elixir).
Numbers to remember
- Lab: a cache of 1% of keys gave 50.6% hits on Zipf traffic vs 1% uniform; in-process 0.03 µs vs Redis 14 µs vs PostgreSQL PK lookup 20 µs on localhost; plain cache-aside sent 50 concurrent misses to the database vs 1 with single-flight or a lock; a stale price survived an invalidation for the full 300 s TTL.
Pitfalls
- Caching cheap queries; caching without measuring hit rate.
- No TTLs (permanent staleness); identical TTLs (synchronised expiry).
- Updating cached values instead of deleting; invalidating before commit.
- Unbounded local caches; caching per-user data under shared keys (data leaks).
- Redis as a cache with
noeviction; mixing cache and durable data in one instance. - Treating the cache as required: the system must survive a cold or failed cache.
Glossary
- Hit rate: fraction of requests answered by the cache.
- Cache-aside: the application loads and stores cache entries itself.
- TTL: time to live before expiry.
- Eviction: removing entries to make room.
- Single-flight: collapsing concurrent loads of one key into one.
- Negative caching: caching the absence of a value.