How to Implement Negative Caching
Cache the answer that something does not exist for a short time, so repeated lookups for a missing key do not hammer the origin.
On this page
Introduction
When a lookup misses, the origin usually returns the same miss every time, and a burst of lookups for the same missing key fetches the origin repeatedly. Negative caching stores the fact that a key has no value, for a short time, so the next lookup for that key is answered from the cache instead of the origin. It is the mirror of a normal cache: the value cached is absence. The risks are straightforward but real: caching a miss that becomes a hit too late serves a stale not-found, and caching a miss caused by a transient error turns a temporary failure into a lasting one. This article covers the pattern, the TTL, and how to keep it correct.
What Negative Caching Is
A normal cache stores a value keyed by the request. A negative cache stores the absence of a value, so a lookup for a key known not to exist returns quickly without touching the origin. It is especially valuable against lookups for keys that are guessed or enumerated, because those produce a high rate of misses that would otherwise all reach the origin.
The same idea exists in DNS, where a non-existent name is cached with its own TTL, and in HTTP, where a 404 or 410 can be cached. The application-level version follows the same principle: the miss is a fact worth remembering briefly.
Why It Helps
Consider an endpoint that looks up a user by id. A client enumerating ids, or a bug that repeats a request for a deleted record, produces a stream of misses that each query the database. The database does duplicate work for the same negative answer. A negative cache collapses those into one query per TTL, which protects the origin from the pattern.
It also improves latency for the caller: a cached miss returns as fast as a cached hit, without the origin round trip. The benefit is largest when the miss rate is high and the same keys are requested repeatedly, which is exactly the enumeration and retry pattern.
A Short Negative Cache
The implementation is a cache of keys known to be absent, with a short TTL. On a lookup, check the negative set first; if present, return not-found without querying. On a real miss from the origin, add the key to the negative set. On a hit, remove it from the negative set in case a stale miss is present.
class NegativeCache {
constructor(ttlMs) { this.ttlMs = ttlMs; this.misses = new Map(); }
isMiss(key) {
const until = this.misses.get(key);
if (until === undefined) return false;
if (until <= Date.now()) { this.misses.delete(key); return false; }
return true;
}
markMiss(key) { this.misses.set(key, Date.now() + this.ttlMs); }
clear(key) { this.misses.delete(key); }
}
async function getUser(id, origin, neg) {
if (neg.isMiss(id)) return null; // answered without the origin
const user = await origin.findUser(id);
if (user) { neg.clear(id); return user; } // a hit clears a stale miss
neg.markMiss(id); // remember the absence briefly
return null;
}
Choosing the TTL
The negative TTL is a trade between protecting the origin and not serving a stale not-found. Too long, and a key that appears shortly after is not found until the TTL expires. Too short, and the cache does not absorb the burst. Choose it from how quickly a missing key can become present: a user id that only appears when an account is created can tolerate a few seconds; a lookup for a resource that is created frequently needs a shorter TTL.
Keep the negative TTL shorter than the positive TTL in general, because a wrong absence is more surprising to a user than a slightly stale value. When in doubt, prefer a shorter negative TTL and a larger origin capacity, rather than a long negative cache that produces confusing not-founds.
Transient Errors Are Not Misses
The most important correctness rule is to cache only a genuine not-found, never a lookup that failed because the origin was unavailable or timed out. Caching a transient failure as absence turns a brief outage into a lasting one, and the error looks like a missing record rather than a failure. Distinguish the two outcomes explicitly in the lookup.
async function lookup(id, origin, neg) {
if (neg.isMiss(id)) return { status: 'not_found' };
let result;
try {
result = await origin.fetch(id);
} catch (err) {
// Origin unavailable: do NOT cache this as a miss. Propagate the error.
throw new UpstreamUnavailable(err);
}
if (result === null) {
neg.markMiss(id); // a real not-found, safe to cache briefly
return { status: 'not_found' };
}
neg.clear(id);
return { status: 'ok', value: result };
}
Invalidation and Correctness
A negative cache entry must be cleared when the key becomes present, or the cache serves a stale not-found. The write path that creates the key should clear the negative entry, so a client that creates a record and immediately reads it sees it. This is a cache-invalidation problem, and the negative entry is one more key the writer must invalidate.
For a distributed negative cache, the same rules apply at the shared-store level: a short TTL, a clear on creation, and no caching of errors. Because the entries are short-lived, an occasional stale miss is bounded by the TTL, which is why the TTL must be short. Accept a small window of staleness in exchange for the origin protection.
Conclusion
Negative caching remembers briefly that a key has no value, so repeated lookups for a missing key do not reach the origin. Keep the negative TTL short, clear an entry the moment the key is created, and never cache a transient failure as absence, because that turns a temporary outage into a lasting wrong answer. Used with those rules, it absorbs the enumeration and retry patterns that would otherwise hammer the origin, at the cost of a short, bounded window in which a newly created key is still reported missing.
Sources: RFC 2308: DNS negative caching, RFC 9111: HTTP caching, Cloudflare: negative caching.
FAQ
- Why must the negative TTL be short?
- Because a negative entry is wrong the moment the key is created. A short TTL bounds how long a newly created key can be reported as missing, and it lets the cache absorb bursts without serving a stale not-found for long.
- Should a failed origin lookup be cached as a miss?
- Never. Caching a transient failure as absence turns a brief outage into a lasting one and makes the error look like a missing record. Cache only a genuine not-found, and propagate the error otherwise.
Report a problem with this articleOpens a pre-filled issue on GitHub.