Caching patterns
A 2.6 ms query, a 75 µs Redis GET and a 5 ns local map; cache-aside and its relatives, local against distributed, TTLs, LFU beating LRU at one tenth of the data, and negative caching.
A cache is a copy of data kept somewhere faster than where the data lives. That sentence contains both halves of every caching decision: faster, which is why you add one, and copy, which is the cost — a copy can be missing, too big for the space you gave it, or different from the original.
This lesson measures the first half and names the second. The experiments ran against Redis 7.4 in one container and a Java client in another; the "database" is a simulated 2 ms query, so that the numbers isolate the cache.
What a cache buys
Three ways to fetch the same product:
database query (simulated) 2,592,324 ns
Redis GET (another container) 74,609 ns
local map get 5 ns- A database query of about 2.6 ms — and in production, often much more under load.
- A Redis GET over the network: about 75 microseconds, roughly 35 times faster than the query, because it is a hash lookup in memory with a network round trip in front of it.
- A local, in-process map: about 5 nanoseconds once the JIT has compiled the lookup — fifteen thousand times faster than Redis, because there is no network at all.
Speed is only one of the things bought. A cache also absorbs load the database would otherwise take: every cache hit is a query that did not happen. For many systems that is the real reason — the database could answer fast enough, but not ten thousand times a second.
The four patterns
The patterns differ in who talks to the cache and when it is written:
| pattern | read | write | the catch |
|---|---|---|---|
| cache-aside | the application checks the cache; on a miss, it reads the database and fills the cache | the application writes the database, then deletes or updates the cache entry | the application owns the logic, and the race between a read-fill and a write-delete |
| read-through | the application asks the cache; the cache loads from the database on a miss | as cache-aside | the cache needs a loader — common in local caches like Caffeine, rare in Redis |
| write-through | as read-through | the application writes to the cache, which writes the database synchronously | the cache is now on the write path; its failure is a write failure |
| write-behind | as read-through | the cache acknowledges, and writes the database later, in batches | writes acknowledged and not yet durable can be lost |
Cache-aside is the default for a service in front of Redis: it keeps the database as the only source of truth, and a cache outage degrades to slower reads rather than to failed writes. The code is short:
Product get(long id) {
Product cached = cache.get(id);
if (cached != null) return cached;
Product fresh = repository.findById(id);
cache.put(id, fresh, Duration.ofMinutes(5));
return fresh;
}
void update(Product p) {
repository.save(p);
cache.evict(p.id());
}In Spring, the same shape is declarative — reference code, not run in these experiments:
@Cacheable(cacheNames = "products", key = "#id")
public Product get(long id) { return repository.findById(id).orElseThrow(); }
@CacheEvict(cacheNames = "products", key = "#p.id")
public void update(Product p) { repository.save(p); }@Cacheable works through a proxy, so a call from inside the same class bypasses the cache — the same self-invocation trap as @Transactional. And the two lines in update are not atomic: the stampedes and consistency lesson measures how often that leaves the cache wrong.
Local, distributed, or both
The 15,000× gap between a local map and Redis is tempting. The trade:
| local (in-process: Caffeine, a map) | distributed (Redis) | |
|---|---|---|
| hit latency | nanoseconds | tens to hundreds of microseconds |
| shared between instances | no — each instance has its own copy | yes |
| survives a deploy | no | yes |
| memory | the service's own heap | a separate server |
| invalidation | per instance; others keep the old value | one delete reaches everyone |
The critical row is the fourth. With ten instances each holding a local copy, an update invalidates the copy on one instance. The other nine serve the old value until their entries expire, and a user whose requests are balanced across instances sees the value change back and forth. That incoherence is acceptable for data that is allowed to be a few seconds old — configuration, reference data, feature flags — and not for anything a user just edited.
A common compromise is two levels: a small local cache with a very short TTL in front of Redis, for the hottest keys only. It removes most network round trips while bounding how long instances can disagree to that short TTL.
TTL: how long a copy may be wrong
Every cache entry should have a time-to-live, even when the application also invalidates on write. The TTL is the upper bound on how long any bug, race or missed invalidation can serve wrong data. Choosing it:
- From the data's tolerance for staleness, not from what "feels right". A product description can be an hour old. A price at checkout cannot be cached at all.
- With jitter. Entries written together — a warm-up at startup, a batch job — expire together, and the database takes all the misses at the same moment. Adding a random 10% to each TTL spreads that out.
- Shorter than the invalidation you do not trust. If an update path might forget to evict, the TTL is the fix that works anyway.
Eviction: when the cache is full
A cache has a memory limit, and when it is reached something must go. Redis supports several maxmemory-policy settings, and the choice matters in proportion to how uneven the traffic is.
An experiment: 100,000 products of about 1 KB each — 100 MB of potential cache — in a Redis limited to 12 MB, so roughly one product in ten fits. Two hundred thousand requests with realistic skew (a Zipf distribution, where a few products get most of the traffic), cache-aside on every request:
allkeys-lru keys held 10,507 hit ratio 59.5% evicted 70,441 database queries 80,971
allkeys-lfu keys held 10,507 hit ratio 62.4% evicted 64,757 database queries 75,287
allkeys-random keys held 10,507 hit ratio 56.4% evicted 76,753 database queries 87,283- LRU (least recently used) evicts what has not been touched lately.
- LFU (least frequently used) evicts what is touched rarely, using a small decaying counter per key.
- random evicts anything.
With one tenth of the data in memory, the cache answered 56–62% of requests — that is what skewed traffic gives you, and it is why caches work at all. LFU was best here, because with a stable popularity distribution, frequency is a better predictor than recency: an unpopular product requested once is recently used, but not frequently. LFU beat LRU by about three points of hit ratio — 5,684 fewer database queries out of 200,000.
Two cautions about the policy names. volatile-* policies only evict keys with a TTL, and noeviction — the default — makes writes fail when memory is full. A cache configured with noeviction stops accepting new entries instead of making room, which usually shows up as errors from SET.
Negative caching: remembering what does not exist
Cache-aside caches values. A request for something that does not exist finds nothing in the cache, queries the database, finds nothing there either, and caches nothing — so the next request for it does the same. A bug that requests a deleted product in a loop, or a scraper walking through ids that do not exist, goes straight through the cache to the database every time. This is called cache penetration.
Twenty thousand requests, one in ten for one of 50 product ids that do not exist:
negative caching off: 3,019 database queries for 20,000 requests
negative caching on : 1,050 database queries for 20,000 requestsWithout it, every one of the 2,000 requests for a missing product reached the database. With a sentinel value cached for 30 seconds — "we looked, it is not there" — each missing id cost one query, and the database load fell by two thirds.
The sentinel needs a short TTL, because the thing that did not exist may be created: a product added a moment after a failed lookup should not stay invisible for an hour. For open-ended id spaces, where an attacker can request a different missing id every time, a negative cache alone does not help; a Bloom filter of ids that do exist, checked before the cache, rejects most of them without touching Redis or the database.
Under the hood: write-behind's durability gap
The pattern table above notes write-behind's catch in one line — "writes acknowledged and not yet durable can be lost" — and it is worth being precise about what that means, because write-behind is the pattern most likely to be reached for under pressure ("writes are slow, let's ack immediately and flush later") without the trade-off being stated out loud.
The mechanism. In write-behind, the application writes to the cache and gets an acknowledgement back immediately — the caller believes the write is done. The cache does not write the database synchronously; instead it buffers the write (often batching several writes to the same or nearby keys) and flushes to the database on a schedule or when the buffer fills. Real systems that support this shape — Hazelcast's MapStore with write-delay-seconds, for example — implement it exactly this way: an in-memory (or cache-tier) buffer, and a background thread that periodically drains it to the store of record.
The gap, precisely. Between the moment the cache acknowledges the write and the moment the buffered write actually lands in the database, the only copy of that write's data is in the cache tier. If the cache process crashes, the node is evicted under memory pressure, or the buffer is lost in a failover before that flush happens, the write is gone — silently, from the caller's point of view, because the acknowledgement already went out and nothing tells the caller it did not survive. This is different in kind from cache-aside's staleness problem: cache-aside can serve an old value, which is wrong but recoverable once the TTL expires or the next write corrects it; write-behind's gap can make a write never have happened at all, with no record anywhere that it was ever attempted, because the cache — not the database — was, for a window, the only place the new value existed.
Why the gap is not a bug to fix, but a trade to make on purpose. Making the flush synchronous removes the gap and also removes the reason to use write-behind — that would just be write-through with extra steps. The gap is the whole point: it is what buys write-behind's speed and its ability to batch many small writes into fewer, larger database operations. The engineering question is not "how do we eliminate it" but "how long is this window, and what is actually acceptable to lose". A counter that periodically write-behinds an approximate value (page views, a "likes" count) can tolerate losing the last few seconds of updates on a crash; a payment ledger cannot, and write-behind is very likely the wrong pattern for it regardless of how attractive the acknowledged-write latency looks.
Try it yourself
Size the loss window
A write-behind cache batches writes and flushes to the database every 5 seconds, or immediately if the buffer reaches 1,000 pending writes, whichever comes first. During a burst, the service receives 40 writes per second, evenly spaced. The cache process crashes 3.2 seconds after the previous flush completed. Reason through: how many writes are lost, and what does that number depend on? Then reason about what changes if the write rate spikes to 400 writes per second instead.
The loss window is bounded by the flush interval, not by how many writes happened
At 40 writes/second, 3.2 seconds since the last flush means roughly 128
writes are sitting in the buffer, unflushed, when the crash happens — all
128 are lost, because none of them exist anywhere but that buffer. The
number of writes lost depends on the write rate during the window and how
far into the window the crash lands; the window itself is bounded by
whichever flush trigger fires first — here, 5 seconds, since 1,000 writes at
40/s would take 25 seconds to accumulate, so the time-based flush always
fires first at this rate. At 400 writes/second, the count-based trigger
takes over: 1,000 writes accumulate in 2.5 seconds, so the buffer flushes
before the 5-second timer would have fired, and the maximum possible loss is
bounded by 1,000 writes (or fewer, since a crash can land at any point in
that 2.5 s window) rather than by 5 seconds' worth of writes at the higher
rate (which would have been 2,000). The general shape: the loss window is
min(time trigger, time to fill the buffer at the current rate), and a
system that only reasons about the time-based flush interval will
under-estimate risk once the write rate is high enough for the size trigger
to matter — or over-estimate the buffer's safety margin once it is low
enough that the size trigger never fires at all.
Misconceptions
- "Write-behind is basically write-through, just faster because it's async." Write-through keeps the acknowledged write durable before returning — the write is in the database (or has failed, and the caller knows). Write-behind acknowledges before the database write happens at all, which is a different durability guarantee, not the same guarantee delivered faster. Conflating the two means shipping write-behind's data-loss window while believing you have write-through's durability.
- "Read-through and cache-aside behave the same, so it doesn't matter which one a library gives you." They differ in where the loading logic lives and who is exposed to a cache outage: cache-aside's application code decides what happens on a miss (and can fall back to the database directly if the cache is down), while a read-through cache is on the read path itself — if it cannot reach its loader or its backing store, the read fails at the cache, not in application code that could choose to route around it.
Sources
- AWS documentation, "Caching strategies and best practices" (Amazon ElastiCache) — cache-aside, read-through, write-through and write-behind, and their trade-offs.
- Hazelcast documentation,
MapStoreandwrite-behind/write-delay-seconds— a real write-behind implementation's buffering and flush mechanics.