Workbench / Volume 3 Companion: The Backend
V3·53
Caching
Companion to Volume 3, chapter 53: how why caching works, where to cache, access patterns, lifetimes and eviction, and correctness under concurrency connect; new angles (a version number as a "best before" that never lies, a cache in front of a door rather than a store, the part of a page that's yours alone); what the chapter simplifies, measured on the build's stage 54: a reconnect stampede of 600 kitchen pages that made orders at every other kitchen wait for the whole stampede because each page rebuilt its snapshot under a lock the orders also need, fixed by caching per kitchen version with no TTL and no purge, and what a cache must leave out; the theory behind them (versioned keys, single-flight, what to cache, measuring cache value); how Spring's @Cacheable(sync = true) makes loads single-flight, from its source; four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 53 covers why caching works (locality and skew, the cost in staleness and complexity), where to cache (layers, local against distributed, Redis), access patterns (cache-aside, read-through, write-through), lifetimes and eviction (TTL, eviction policies) and correctness under concurrency (invalidation, stampedes, hot keys, negative caching), with caches across languages.
The links worth remembering:
- A cache trades correctness work for speed. Every cache needs an answer to "when is this wrong, and for how long?"; TTLs, invalidation and versions are three different answers.
- Skew is what makes caches pay, and what makes hot keys and stampedes hurt: the same few keys are both the benefit and the risk.
- Caches protect something. Usually a database; sometimes, as in TiffinBox, a lock or a CPU. Measure what they protect, not only their hit rate.
Explain it differently
1. A version number is a "best before" that never lies. A TTL guesses how long a value stays good. A version says exactly which state it was made from: when the state changes, the version changes, and the old value is simply never asked for again (Gaps 2).
2. A cache in front of a door. TiffinBox's cache doesn't save a database trip; it keeps 600 people from each doing the same work in a doorway everyone else needs to walk through (Gaps 1).
3. The part of a page that's yours alone. A shared page can carry parts that belong to one request: the time it was made, a nonce, a theme. Cache the shared part, add the rest per request (Gaps 3).
Gaps and misconceptions
What the chapter oversimplifies
All outputs are real, from OpenJDK 21.0.12 and the build's stage 53 and 54 servers (exp/54), unless stated. Requests go through the router in process, so the numbers are the server's own work.
1. A stampede that isn't about a database. The chapter's stampede is many requests loading one expired key from a database. TiffinBox has no database, and found a stampede anyway: after a deploy, every kitchen tablet reconnects and every kitchen page asks for its kitchen's snapshot (stage 24). Kitchen k7 with 60 open orders; 600 page requests at once, while eight clients place orders at eight other kitchens:
# stage 53
round 1: 600 kitchen pages in 242 ms (p50 75.8 ms, p99 114.6 ms); orders meanwhile p50 1.39 ms, p99 8.2 ms, max 244.8 ms; CPU 1,260 ms
round 2: 600 kitchen pages in 251 ms (p50 98.6 ms, p99 137.0 ms); orders meanwhile p50 1.01 ms, p99 8.4 ms, max 252.6 ms; CPU 1,200 ms
round 3: 600 kitchen pages in 208 ms (p50 66.5 ms, p99 94.6 ms); orders meanwhile p50 0.92 ms, p99 3.1 ms, max 210.3 ms; CPU 1,120 ms
The slowest order took as long as the whole stampede, at a kitchen nobody was reloading. A snapshot is taken under the event stream's lock (so a client never misses an event between its snapshot and its stream), and that lock is also where every order, at every kitchen, publishes its change. 600 snapshots of 60 orders each, one after another under one lock, and every order waited behind them. Stage 54 caches each kitchen's order list, and its first screen of HTML tickets, per kitchen version:
# stage 54
round 1: 600 kitchen pages in 101 ms (p50 0.2 ms, p99 35.9 ms); orders meanwhile p50 1.43 ms, p99 10.9 ms, max 70.7 ms; CPU 940 ms
round 2: 600 kitchen pages in 83 ms (p50 0.1 ms, p99 5.7 ms); orders meanwhile p50 0.79 ms, p99 5.0 ms, max 83.6 ms; CPU 810 ms
round 3: 600 kitchen pages in 71 ms (p50 0.1 ms, p99 35.8 ms); orders meanwhile p50 0.82 ms, p99 5.8 ms, max 43.5 ms; CPU 810 ms
A page's median went from 76 ms to 0.2 ms, the stampede finished three times sooner, and the worst order waited 44–84 ms instead of 210–253. The remaining CPU is the rest of each page (headers, theme, asset names), done outside any lock.
2. No TTL, no purge: versions. Each kitchen has a version, the sequence number of its latest event, and every change to its open orders publishes an event. A cached list records the version it was made from, and is used only while that's still the kitchen's version. So there's nothing to expire and nothing to purge, and the chapter's invalidation race (the lab's Experiment 4: a slow reader writes an old value after the invalidation) can't happen: a slow reader stores its list under the version it read, and once the kitchen has moved on, nobody asks for that version again. The order matters: read the version first, then the data. Data read before the version could be older than the version says.
3. What the cache must leave out. The snapshot JSON carries serverTime, the moment it was made, which kitchen screens use to correct their clocks (stage 17). Cached whole, every tablet would get the time the first one asked, and correct its clock to the past. Stage 54 caches only the order list and adds the request's instant each time (OrdersTest.aKitchensSnapshotIsComputedOncePerChange checks that two snapshots of one version have the same list and different times). Pages carry a theme (stage 25) and, for the Angular view, a per-response CSP nonce (stage 28): the cached part is the tickets, never the page.
4. A cache's value is what it protects. The order list's counters (cacheStats(): hits and misses) say how often it saved work; the measurement that matters is the one above: orders at other kitchens no longer wait behind a reconnect. A hit rate of 99.8% (599 of 600) would look the same whether the work saved took 1 µs outside a lock or 0.4 ms inside one.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "Caches are for databases." | They're for any repeated work, especially under a lock. | Gaps 1 |
| "Every cache needs a TTL." | With a version in the key, entries are never stale, just unused. | Gaps 2 |
| "Cache the response." | Cache what's shared; add what's per request. | Gaps 3 |
| "Hit rate measures a cache." | What it protects does: latency, load, contention. | Gaps 4 |
| "Deleting the key fixes staleness." | A racing reader can write the old value back. | The chapter's lab, Experiment 4 |
Theoretical gaps: the ideas behind the chapter
1. Versioned keys. Put the version of the source in the cache key (or alongside the value, checked on read). It turns invalidation into a lookup: no messages, no TTL, no race. It needs a cheap, reliable version: a sequence number, a row version, an ETag. HTTP's ETag with If-None-Match (stage 19's menu) is the same idea across the network.
2. Single-flight. When many requests miss the same key at once, one computes and the others wait for its result. TiffinBox gets it from computing under the stream's lock (one at a time, then hits); ConcurrentHashMap.computeIfAbsent and Caffeine's loading caches do it per key without a global lock; Spring's @Cacheable(sync = true) delegates to them (Code walkthrough).
3. Cache the shared, compute the personal. Split a response into what depends only on shared state (cacheable, keyed by its version) and what depends on the request (time, identity, nonces, preferences). Mixing them either leaks one user's data to another or serves stale per-request values.
4. Measuring cache value. Count hits and misses, but evaluate a cache by the cost it removes from what it protects: database load, lock hold time, CPU, tail latency of other requests. Turn the cache off in a load test and compare.
Applying it
Code walkthrough
Theory 2 in Spring's cache abstraction: what sync = true changes. From spring-projects/spring-framework, main at commit 7ce40c8 (18 November 2026).
Synchronised @Cacheable
spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java:
if (contexts.isSynchronized()) {
// Special handling of synchronized invocation
return executeSynchronized(invoker, method, contexts);
}
...
try {
return wrapCacheValue(method, doGet(cache, key, () -> unwrapReturnValue(invokeOperation(invoker))));
}
With @Cacheable(sync = true), Spring doesn't look up, call, then put; it hands the cache a loader and asks it to do both (Cache.get(key, valueLoader)). The simple in-memory implementation, spring-context/src/main/java/org/springframework/cache/concurrent/ConcurrentMapCache.java:
public <T> @Nullable T get(Object key, Callable<T> valueLoader) {
return (T) fromStoreValue(this.store.computeIfAbsent(key, k -> {
try {
return toStoreValue(valueLoader.call());
}
catch (Throwable ex) {
throw new ValueRetrievalException(key, valueLoader, ex);
}
}));
}
ConcurrentHashMap.computeIfAbsent runs the loader at most once per key while other callers for that key wait: single-flight within one process. Without sync, 600 concurrent misses run the method 600 times (the lab's Experiment 3). Two limits: it's per process (each instance loads once, and a fleet of 50 still loads 50 times), and a slow loader blocks every caller of that key, and in ConcurrentHashMap, possibly of other keys in the same bin. Caffeine's cache uses its own per-key futures, which is one reason it's the usual production choice.
Debugging drills
D1. Every deploy, orders slow down
Right after each deploy, order placement latency spikes for a few hundred milliseconds across every store, though the order path didn't change.
D2. Clocks wrong on cached pages
Since a performance change, some kiosks show "ordered 5 minutes ago" for orders placed just now.
D3. A stale price after an update
A price changed; one server kept showing the old price for minutes, the others the new one, although the update deleted the cache entry.
D4. 99% hit rate, no improvement
A team added a cache with a 99% hit rate, and latency didn't move.
Career-oriented
Interview prep
Mid-level 1: TTL or invalidation
Question. "A product's price is cached. How do you keep it from being stale?"
How to get there. How stale may it be, and who knows when it changes?
Mid-level 2: what not to cache
Question. "We want to cache our rendered dashboard page for all users. What could go wrong?"
How to get there. What on the page belongs to one user or one request?
Senior 1: a reconnect stampede
Question. "After every deploy, 20,000 clients reconnect and each loads its dashboard state. The database falls over. Design the fix."
How to get there. Spread the load in time, and make each unit of work serve many clients.
Senior 2: local or distributed
Question. "Local cache in each instance, or Redis?"
How to get there. Compare cost per lookup, consistency between instances, and failure modes.
Staff 1: a caching standard
Question. "Write the rules every team must follow when adding a cache."
How to get there. What went wrong in each drill?
Staff 2: cache as architecture
Question. "Our services cache so much that the database is effectively a backup. Is that a problem?"
How to get there. What happens on a cold start, or when the cache layer fails?