AK/Wri/When Your Cache Lies

When your cache lies

1 min read

Plain Text
09:14  on-call bot        p99 /checkout latency 4.2s (baseline 180ms)
09:15  me                opening dashboard
09:16  me                redis CPU 91%. one key: product:8812:price
09:17  teammate          did we deploy?
09:18  me                deploy was 20 min ago. traffic spike started 8 min ago
09:19  teammate          cache miss storm?
09:20  me                yeah. classic stampede

what actually happened

product:8812:price expired during a flash sale. three hundred app servers noticed at nearly the same moment. each one saw a miss. each one called the database. the database got three hundred identical queries while redis stayed empty.

the cache was "working." it was also useless for about twelve seconds.

the shape of the bug

T=0   key expires
T+1ms  server A miss → query DB
T+1ms  server B miss → query DB
T+1ms  server C miss → query DB
...
T+2ms  DB connection pool saturated
T+3ms  everyone still timing out and retrying

retries made it worse. timeouts made it theatrical.

fixes that actually help

single-flight / request coalescing — first miss fetches, everyone else waits on the same promise:

TYPESCRIPT
const inflight = new Map<string, Promise<Price>>();

async function getPrice(id: string) {
  const key = `product:${id}:price`;
  const hit = await redis.get(key);
  if (hit) return JSON.parse(hit);

  if (!inflight.has(key)) {
    inflight.set(
      key,
      db.price.find(id).then(async (price) => {
        await redis.set(key, JSON.stringify(price), { EX: 300 });
        inflight.delete(key);
        return price;
      }),
    );
  }

  return inflight.get(key)!;
}

probabilistic early expiry — refresh before the cliff:

TYPESCRIPT
const ttl = 300;
const jitter = Math.floor(Math.random() * 30);
await redis.set(key, value, { EX: ttl - jitter });

stale-while-revalidate — serve old value while one worker refreshes in the background. users see slightly stale prices for a second; nobody sees a 4 second spinner.

what i got wrong the first time

i added caching to make the db faster. i did not design for many clients discovering emptiness at once. a cache is a coordination problem disguised as a performance trick.