Q15 · How do you design caching layers (L1/L2) to avoid stale data and thundering herds?

Back to 24 Architecture Questions.

The question is not “add Redis”. The axis it turns on: how stale a read is allowed to be, and what happens when a key expires under load. The staleness tolerance decides what may be cached at all, and the expiry behavior decides whether the cache protects the origin or stamps it: expire one hot key and every instance hits the database at the same moment.

The thundering herd Three instances each hold an L1 cache in front of a shared L2. When a hot key expires, all three miss together and hit the origin simultaneously: single-flight and jittered TTLs are the fixes. FIGURE 15 EXPIRY UNDER LOAD L1, ONE PER INSTANCE Instance 1 Instance 2 Instance 3 L2 Cache shared, one TTL Origin the real cost same key expires: all miss together single-flight: one request refreshes, the rest wait for it jitter the TTL: the herd must not expire as one

What the answer should contain

No staleness tolerance, no cache. Per data class, name the number: prices tolerate seconds, profiles tolerate minutes, stock answers must be current. If the business cannot name a number, caching that data is not a design, it is a bet with the product’s money.

Two layers, two jobs. L1 in-process: microseconds, per instance, bounded small, evicted by size; it exists to absorb hot keys without network hops. L2 shared: milliseconds, one copy for the fleet, survives instance restarts. L1 always sits in front of L2, never the reverse, and L1 entries carry a shorter TTL than L2 so the fleet converges.

TTL is the safety net, not the mechanism. Invalidation by event or write-through is the mechanism (write the DB, then bust or update the key); the TTL catches what the mechanism misses. Order matters: update the source, then the cache, never cache-first.

The herd is the failure mode. When a hot key expires, every instance misses together and the origin receives the same query N times at once. Three fixes, in order of strength: single-flight (one request refreshes, the rest of the herd waits for its result), jittered TTLs (instances expire at different times), and probabilistic early refresh (refresh before expiry under load).

Do not cache what cannot be shared. Per-request, per-user-session data in a shared cache is complexity nobody asked for, with a latency story attached.

Version the keys, not the payloads. user:17:v2 beats clever in-place payload evolution: a deploy that changes shape reads a new key, and old entries age out by TTL instead of poisoning readers.

Ideas worth mentioning out loud

Follow-ups to expect

Red flags in an answer

Sources