What is negative caching, and why might you deliberately cache the fact that a lookup returned 'not found'?
Short answer
Negative caching stores the result of a lookup that found nothing, preventing repeated identical lookups for something known not to exist from hitting the database every time -- without it, requests probing for non-existent resources could generate significant unnecessary load…
Advertisement
AModel answer
Negative caching stores the result of a lookup that found nothing, preventing repeated identical lookups for something known not to exist from hitting the database every time -- without it, requests probing for non-existent resources could generate significant unnecessary load on the underlying data source.
async function getUser(id) {
const cached = await redis.get(`user:${id}`);
if (cached === 'NOT_FOUND') return null;
if (cached) return JSON.parse(cached);
const user = await db.users.findById(id);
if (!user) { await redis.set(`user:${id}`, 'NOT_FOUND', { EX: 60 }); return null; }
await redis.set(`user:${id}`, JSON.stringify(user), { EX: 3600 });
return user;
}Real-world example
A public API repeatedly queried for invalid or deleted user IDs by a misconfigured integration adds negative caching with a short TTL, absorbing the repeated invalid lookups without hitting the database each time.
Likely follow-ups
- Why does a negative cache entry typically need a much shorter TTL than a positive cache entry?
- Could negative caching be exploited or cause a functional bug if a resource is created shortly after being negatively cached?
Related topics