Skip to content
← All posts
  • June 23, 2026
  • 7 min read
  • #caching
  • #redis
  • #design-systems

The cache did its job. That’s what took the database down.

A 60-second TTL worked fine for four months, until one key got popular enough to expire into a crowd.

A 60-second TTL worked fine for four months, until one key got popular enough to expire into a crowd.

Cold open

The PagerDuty alert fired at 2:14am: db-primary: connections at 98%.

Marcus pulled up the dashboard half-asleep, expecting a slow leak. Connection counts don’t usually jump. They creep, you notice them on a Tuesday afternoon, you file a ticket. This one had gone from 40 connections to 287 in about four seconds, then the database started rejecting new ones outright.

Nothing had deployed in six hours. No migration, no traffic campaign, no bot attack he could see in the logs. Just a normal Tuesday night, and then a database that looked like it had been hit by a truck.

The instinct that was wrong

His first guess was a connection leak. Some endpoint somewhere wasn’t closing its connections properly, and it had finally tipped over after running fine for weeks. He’d seen that bug before. He started grepping for places that opened a connection without a finally block.

He found nothing, because there was nothing to find. Every connection in the spike was short-lived. They opened, ran one query, and closed within milliseconds. That’s not what a leak looks like. A leak is connections that pile up and never let go. This was connections that opened, did real work, and vanished. There were just way too many of them showing up at once.

He checked what query they were all running. Same one. Same cache key. A single row in the trending_posts table, the kind of query that normally never touches the database at all, because it lives in Redis with a 60-second TTL.

It was the cache. Not because it failed. Because it expired, and at the exact moment it expired, a few hundred requests landed on it inside the same handful of milliseconds.

The math nobody had done

Redis didn’t do anything wrong. A GET on an expired key returns nothing, full stop, every time, by design. The bug wasn’t in Redis. It was in what the application did the instant it saw a miss: every single request that hit a miss ran the underlying query itself, independently, with no idea any other request was doing the exact same thing at the exact same moment.

Here’s the part that makes this worse than it sounds. The trending_posts key was popular enough that it was getting hit roughly 150 times a second. With a flat 60-second TTL, that key expires at one precise instant. In the next handful of milliseconds after that instant, every one of those concurrent requests sees a miss, because the old value is gone and the new one hasn’t landed yet. Redis itself usually resolves a miss in under a millisecond, so the entire window where requests pile up is tiny. But tiny doesn’t mean small: if even 50-100ms of traffic at 150 req/s lands inside that window before the cache refills, that’s roughly 8 to 15 requests trying to run the same expensive query at once. Hit a hotter key, or a slower rebuild query, and that number climbs fast.

This is where connection limits turn a momentary blip into an outage. PostgreSQL ships with a default of 100 max connections. Even a right-sized RDS instance only raises that ceiling. It doesn’t remove it. A web app on a few application servers, each holding a modest pool of connections, doesn’t need a huge stampede to eat a meaningful chunk of that ceiling, especially if several hot keys expire close together or the rebuild query is slow enough that connections pile up rather than clearing fast. The database wasn’t slow on its own. It just got asked to run the same expensive query several times over in the time it would normally run it once, by requests that, in a sane world, should have shared one answer.

Three scenarios, three different fixes

Marcus’s first fix worked, but only for the symptom he’d just seen. He learned that the hard way once he looked at what else was on the cache layer.

Scenario A: a handful of very hot keys, low key cardinality. trending_posts again. A handful of keys, each getting hundreds of requests a second, each expensive enough to rebuild that even a brief stampede matters.

  • Fix: request coalescing (the singleflight pattern). When a request misses the cache, it checks whether a rebuild for that exact key is already in flight. If so, it waits on that result instead of starting its own. The first request does the work; everyone else behind it gets a free ride. Go’s golang.org/x/sync/singleflight package is the canonical implementation of this idea, and most languages have an equivalent. This turns “150 queries in 100ms” into “1 query, and 149 requests waiting a few milliseconds for the same answer.”

Scenario B: many keys, each individually moderate traffic, but they were all set with the same TTL at the same code path. A product catalog where 10,000 SKUs were cached with TTL=300 as a flat constant, all written to the cache in the same batch job at midnight.

  • Fix: TTL jitter. Instead of TTL = 300, use TTL = 300 + random(0, 60). No single key here gets enough traffic to cause a stampede on its own, but ten thousand keys expiring inside the same one-second window collectively look exactly like one very hot key expiring. Spreading those expirations over a 60-second window turns one sharp spike into a low, flat hill the database barely notices. The fix costs nothing: it’s a few lines in whatever sets the TTL, not new infrastructure.

Scenario C: a key that’s both extremely hot and extremely expensive to rebuild. An aggregated dashboard metric that takes 2–3 seconds to recompute, not milliseconds, serving thousands of requests a minute.

  • Fix: probabilistic early expiration (XFetch-style), on top of coalescing. Instead of waiting for the TTL to hit zero, each request that reads the key, as it gets close to expiry, rolls a die with rising odds of triggering an early refresh. At 90% of the TTL there’s a small chance; near the very end there’s a near-certainty. One lucky request quietly refreshes the cache before anyone hits a real miss, so the herd never has anything to stampede on. Meta open-sourced this approach for exactly this kind of workload, where rebuild cost is high enough that even a coalesced single rebuild under heavy concurrent load is still a risk worth avoiding entirely.

None of these three fixes is strictly better than the others. Jitter is nearly free and you should probably have it everywhere as a baseline. Coalescing earns its complexity on individual hot keys. Probabilistic early expiration earns its complexity only when the rebuild itself is slow enough that even one in-flight rebuild under load is a risk you want to avoid, not just survive.

What the outage was actually hiding

The real mistake wasn’t picking a 60-second TTL. Sixty seconds was a completely reasonable number the day someone chose it. The mistake was treating a fixed TTL as something you set once and never reconsider, while traffic to that key kept climbing in the background, unnoticed, until it crossed a threshold nobody had defined or was watching for.

A cache miss is supposed to be the harmless case, the fallback path that politely asks the database for the answer. It only stays harmless if you’ve reasoned about what happens when not one but many requests take that fallback path at the same instant. That reasoning doesn’t show up anywhere in the cache hit-rate dashboard, which is exactly why teams don’t do it until a 2am page forces the question.

The decision guide that came out of it

Use TTL jitter when:

  • You have many keys on a flat or batch-set TTL, especially anything written in bulk (cache warming jobs, deploy-time preloads, midnight batch jobs)
  • This should usually be your default everywhere, not a targeted fix. It’s cheap enough that “why not” is the right question

Use request coalescing / singleflight when:

  • A small number of keys account for a disproportionate share of traffic
  • The rebuild is moderately expensive (a real query, an API call), and you want exactly one in-flight rebuild per key, not a controlled few

Use probabilistic early expiration when:

  • The rebuild is slow enough (multi-second aggregations, expensive joins, calls to a slow upstream) that even one stampede event, or one rebuild blocking a wave of waiters, is a latency spike worth avoiding entirely
  • You’re willing to accept slightly more cache churn (refreshing before strictly necessary) in exchange for never hitting a hard miss on a hot key

Watch for the herd’s actual signature, since it rarely announces itself as a cache problem: a connection-pool or max_connections spike that lines up in time with a cache-miss-rate spike, not a slow climb. If your dashboards show those two lines moving together at the same instant, that’s the pattern. Not a coincidence of timing.