Negative Cache for Repeated Failed Lookups
Remember missing lookup results for a short TTL to avoid repeated expensive calls while distinguishing hits from misses.
Code
export interface CacheLookup<V> {
hit: boolean;
value?: V;
}
interface CacheEntry<V> {
value: V | null;
expiresAt: number;
}
export class NegativeCache<K, V> {
private readonly entries = new Map<K, CacheEntry<V>>();
private readonly ttlMs: number;
private readonly now: () => number;
constructor(ttlMs: number, now: () => number = () => Date.now()) {
if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
throw new RangeError("ttlMs must be a positive finite number");
}
if (typeof now !== "function") throw new TypeError("now must be a function");
this.ttlMs = ttlMs;
this.now = now;
}
get(key: K): CacheLookup<V> {
const entry = this.entries.get(key);
if (!entry) return { hit: false };
if (this.now() >= entry.expiresAt) {
this.entries.delete(key);
return { hit: false };
}
if (entry.value === null) return { hit: true };
return { hit: true, value: entry.value };
}
setMiss(key: K): void {
this.entries.set(key, { value: null, expiresAt: this.now() + this.ttlMs });
}
setValue(key: K, value: V): void {
if (value === null) throw new TypeError("value must not be null; use setMiss");
this.entries.set(key, { value, expiresAt: this.now() + this.ttlMs });
}
delete(key: K): boolean {
return this.entries.delete(key);
}
get size(): number {
return this.entries.size;
}
}
export async function withNegativeCache<K, V>(
cache: NegativeCache<K, V>,
key: K,
loader: () => Promise<V | null>,
): Promise<V | null> {
if (typeof loader !== "function") throw new TypeError("loader must be a function");
const cached = cache.get(key);
if (cached.hit) return cached.value ?? null;
const value = await loader();
if (value === null) cache.setMiss(key);
else cache.setValue(key, value);
return value;
}How it works
Negative Cache for Repeated Failed Lookups reduces to the class NegativeCache and the function withNegativeCache.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. A guard precedes the RangeError and TypeError: bad state stops the flow there instead of continuing.
What comes back is a new object, not a reference to anything passed in.
Caveats
- The guard
typeof now !== "function"short-circuits the flow with an earlythrowwhen its condition holds.
Putting it to use
NegativeCache is what another module would consume; nothing else here is load-bearing for callers.
Core lines
if (cached.hit) return cached.value ?? null;
if (typeof loader !== "function") throw new TypeError("loader must be a function");
if (value === null) throw new TypeError("value must not be null; use setMiss");
Interactive Tools for This Topic
Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Does `NegativeCache` modify its input?
- It does not. Inputs are only read; the return value is freshly built.
- What does the snippet do with malformed data?
- The code refuses to continue: `RangeError` and `TypeError` is thrown while the state is still recoverable.
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. The file defines `withNegativeCache` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.