❯ehsan.blog
~/blog/the-cached-404-that-came-back-as-a-success — zsh
❯cat the-cached-404-that-came-back-as-a-success.md

The cached 404 that came back as a success

·10 min read

The cached 404 that came back as a success — article card for a post by Ehsan Shahid

A cached 404 is supposed to stay a failure. This post is about the day one of mine came back as a success instead — but first, the small, boring kind of waste that makes you cache a 404 at all. A page loads a list of IDs and asks your API about each one. Most of them exist. Two of them were deleted last month, and nobody cleaned up the references. So every time that page renders, your API gets asked about two things that will never exist, and answers 404 twice, forever.

The fix has a name: negative caching. Remember the “no, that doesn’t exist” answer for a little while, the same way you remember a “yes, here it is” answer. The second lookup skips the network entirely.

I added this to api-client. The feature itself is maybe thirty lines. The interesting part is a bug I found while writing about it — one that turns a cached error into a success, silently, with no warning anywhere.

The one rule negative caching has to keep

Say it out loud, because everything else follows from it:

A cache hit on a stored error must still fail the call.

Caching a 404 is allowed to save you a network round-trip. It is not allowed to change what your code sees. If this line throws when the cache is cold:

ts
const user = await api.users.getUser('999') // throws: 404

then it has to throw when the cache is warm too. If it sometimes throws and sometimes returns something, you now have a bug that depends on timing, which is the worst kind to find.

How it is wired up

You opt specific statuses in. Nothing is negative-cached by default:

ts
cache: {
  strategy: 'cache-first',
  ttl: 60_000,
  cacheableStatuses: [404],  // only these errors get remembered
  negativeTtl: 5_000,        // and only for this long
}

The awkward part of building this is ordering. Normally the networking code throws the instant it sees a status of 400 or above — long before any cache code gets a look at it. So for an opted-in status, the throw has to be held back:

ts
const isNegativeCacheable =
  method === 'GET' &&
  cacheConfigured &&
  (resolved.cache.cacheableStatuses ?? []).includes(raw.status);

if (raw.status >= 400 && !isNegativeCacheable) {
  throw classifyError({ kind: 'http', status: raw.status, /* ... */ });
}

It is not pretending the response was fine. It is just letting the 404 travel a bit further down the pipe so the caching layer can write it down. One step later, after it has been stored, the error is thrown anyway:

ts
const isNegative = response.status >= 400;
if (cacheKey && (!isNegative || cacheableStatuses.includes(response.status))) {
  cacheStore.set(cacheKey, {
    key: cacheKey,
    data: response.data,
    status: response.status,
    headers: response.headers,
    storedAt: now,
    expiresAt: now + (isNegative ? negativeTtl : cacheTtl),
    ...(resolvedCacheTags.length > 0 ? { tags: resolvedCacheTags } : {}),
  });
  if (resolvedCacheTags.length > 0) tagIndex.track(cacheKey, resolvedCacheTags);
}

if (isNegative) {
  throw classifyError({ kind: 'http', status: response.status, /* ... */ });
}
return response;

Store, then fail. Two separate steps, in that order. Caching the error is something that happens on the way to failing the call, never instead of it.

And on the way back out, a stored error has to be turned back into a thrown error:

ts
/** A negative-cacheable entry rethrows on a cache hit — it never resolves as success. */
const throwFromEntry = (entry: CacheEntry): never => {
  throw classifyError({
    kind: 'http',
    status: entry.status,
    statusText: '',
    headers: entry.headers,
    data: entry.data,
  });
};

Good. The comment even says it: it never resolves as success.

Except it does.

Three doors into the cache, and one of them is unlocked

While writing the section above, I went looking for every place that reads a cache entry and returns it. There are three, because there are three read strategies.

network-first — try the network, fall back to cache if that fails:

ts
if (entry) {
  emitCacheHit(cacheKey, entry);
  if (entry.status >= 400) throwFromEntry(entry);
  return toCacheResponse(entry);
}

Checks the status. Good.

cache-first, entry still fresh — serve it, skip the network:

ts
if (isFresh(entry, Date.now())) {
  emitCacheHit(cacheKey, entry);
  if (entry.status >= 400) throwFromEntry(entry);
  return toCacheResponse(entry);
}

Checks the status. Good.

stale-while-revalidate, entry gone stale — serve the old copy immediately, refresh in the background:

ts
if (cacheStrategy === 'stale-while-revalidate') {
  emitCacheHit(cacheKey, entry);
  // Background revalidation; keep the stale entry if it fails.
  void fetchThrough().catch(() => undefined);
  return toCacheResponse(entry);
}

No status check. It just returns the entry.

Two doors are locked and one is not. I stared at that for a minute, decided I was probably misreading the control flow, and wrote a test instead of guessing.

Proving it

The test is deliberately simple: cache a 404, wait for it to go stale, ask again, and report what actually happens.

ts
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

it('stale-while-revalidate: a STALE negative entry — does it reject or resolve?', async () => {
  const { api, mock } = client({
    strategy: 'stale-while-revalidate',
    ttl: 30,
    cacheableStatuses: [404],
    negativeTtl: 30,
  });
  mock.on('GET', '/users/999', { status: 404, data: { message: 'not found' } });

  await expect(api.users.getUser('999')).rejects.toBeTruthy();
  await sleep(60); // 60 ms later, past the 30 ms TTL — entry is now stale

  let outcome: string;
  try {
    const v = await api.users.getUser('999');
    outcome = `RESOLVED with ${JSON.stringify(v)}`;
  } catch (e) {
    outcome = `REJECTED ${(e as Error).constructor.name}`;
  }
  console.log('>>> SWR stale negative entry outcome:', outcome);
});

Output:

plaintext
>>> SWR stale negative entry outcome: RESOLVED with {"message":"not found"}

There it is. The call succeeded. No error was thrown. The caller got the body of the 404 handed to it as if it were real data.

Think about what that does downstream. Your code is written like this:

ts
try {
  const user = await api.users.getUser(id)
  render(user)          // <-- a 404 body walks straight in here
} catch {
  renderNotFound()      // <-- never runs
}

So renderNotFound() never fires, and render() is handed an object like { message: 'not found' }. Depending on your UI that is a blank card, a row of undefined, or a crash three components away from the actual cause. And it only happens after the TTL expires, so it works perfectly in every quick manual test you do.

The existing test suite did not catch it. There were already five tests for negative caching and all 5 passed in 32 ms — because every one of them used the default strategy and a fresh entry. The hole was in the combination nobody had written a test for.

The fix is one line

ts
if (cacheStrategy === 'stale-while-revalidate') {
  emitCacheHit(cacheKey, entry);
  void fetchThrough().catch(() => undefined);
  if (entry.status >= 400) throwFromEntry(entry);   // <-- add this
  return toCacheResponse(entry);
}

Same guard the other two doors already had. With it applied:

plaintext
>>> SWR stale negative entry outcome: REJECTED ApiError

All 89 tests in that package still pass, including the five original negative-caching tests, in 3.7 s. That is the whole fix.

Note where the line goes: after the background refresh is kicked off, not before. You still want the refresh to run — that is the entire point of stale-while-revalidate — you just do not want to hand the stale error back as data while it runs.

If you are a user of this library today

The fix is in the library’s code, not yours, so until it ships: do not combine stale-while-revalidate with cacheableStatuses. Pick cache-first for the endpoints where you want negative caching. (A cache that misbehaves quietly is a theme around here — see also what a dead Redis cache does to your logs.) Both of its read paths already handle errors correctly, and for “does this thing exist” lookups you usually want a definite answer anyway, not a fast stale one.

More generally, this is the question worth asking about any cache you own: how many different code paths can return an entry? Not “does my cache handle errors” — but “do all of my read paths handle errors.” Mine had three paths and I had tested one of them.

Two smaller things I got wrong along the way

While verifying the rest of this post, two of my own assumptions turned out to be false. Both are easy to get wrong.

negativeTtl does not default to something shorter. I believed it fell back to a shorter, safer value. It does not:

ts
const negativeTtl = resolved.cache.negativeTtl ?? cacheTtl;

If you do not set it, a cached 404 lives exactly as long as a cached success. That matters, because the right lifetime for the two is genuinely different. A resource that exists and might change is one thing. A resource that does not exist yet can appear at any moment — someone creates it a second after you cached the 404, and now you are serving “not found” for a thing that is right there. So set negativeTtl explicitly, and set it short. The default is a shared value, not a safety net. (The same TTL carelessness bites in the other direction too — I wrote about Redis keys that never expire at all.)

Tag invalidation does not clean up negative entries automatically. Negative entries are stored with tags like any other entry, so a write that invalidates a tag does evict them. But tags are opt-in on both sides. If your GET was never tagged, a tagged POST has nothing to match:

ts
// GET with no tags -> the POST's invalidatesTags has nothing to match.
await expect(api.users.getUser('5')).rejects.toBeInstanceOf(Error);
await api.users.createUser('5');
await expect(api.users.getUser('5')).rejects.toBeInstanceOf(Error); // still 404 from cache
expect(mock.callsTo('GET', '/users/5')).toHaveLength(1);            // network never re-hit

Tag the GET as well, and it works the way you expected all along:

ts
ctx.request(
  { method: 'GET', path: '/users/{id}', pathParams: { id } },
  { cache: { tags: [`user:${id}`] } },   // <-- the half people forget
)

Now creating user 5 evicts the cached 404 and the next read goes to the network.

Which statuses actually belong in the list

Last thing, because this one has a simple rule hiding in it. cacheableStatuses is an explicit list instead of “cache all 4xx” on purpose.

  • 404 — a fact about the resource. Stable, cheap, worth remembering. Good candidate.
  • 401 / 403 — a fact about the caller, not the resource. Someone’s permissions change and they keep seeing a stale rejection until the TTL runs out. Bad candidate.
  • 429 — the worst one. “You were rate limited a moment ago” is supposed to be re-checked on the next attempt. Caching it defeats the point.
  • 500 — usually temporary. Remembering a blip as if it were a fact is how a ten-second outage becomes a five-minute one.

So the question is not “is this an error?” It is: does this status describe the resource, and will it stay true for a while no matter who asks? For 404, usually yes. For nearly everything else, you need a specific reason.

The takeaway

Negative caching is a good idea and it is easy to build. The hard part is not storing the error — it is making sure the cache is only ever a shortcut to a decision you already made, never a second, different decision.

And the way you find out whether that is true is not by reading the code and nodding at the comment that says it is. The comment in my own codebase said it never resolves as success, and the code one function away did exactly that. I only found it because I wrote a test for the boring combination nobody had bothered to test.

If a cache hit and a live request can ever disagree about whether a call succeeded, that is the bug. Go check your third read path.

❯ls ./related
❯cat ./comments

Comments are not configured yet. Enable GitHub Discussions and paste the giscus repo-id / category-id into src/consts.ts.