LRU Cache With TTL Expiry
A generic LRU cache with per-entry TTL that evicts least recently used keys and reports hits, misses and evictions for observability.
Code
export class LruCache<T> {
private readonly store = new Map<string, { value: T; expiresAt: number }>();
private hits = 0;
private misses = 0;
private evictions = 0;
private readonly now: () => number;
private readonly capacity: number;
private readonly ttlMs: number;
constructor(options: { capacity: number; ttlMs: number; now?: () => number }) {
if (!Number.isInteger(options.capacity) || options.capacity < 1) {
throw new RangeError("capacity must be a positive integer");
}
if (!Number.isFinite(options.ttlMs) || options.ttlMs <= 0) {
throw new RangeError("ttlMs must be a positive number");
}
this.capacity = options.capacity;
this.ttlMs = options.ttlMs;
this.now = options.now ?? (() => Date.now());
}
get size(): number {
return this.store.size;
}
stats(): { hits: number; misses: number; evictions: number } {
return { hits: this.hits, misses: this.misses, evictions: this.evictions };
}
get(key: string): T | undefined {
const entry = this.store.get(key);
if (!entry) {
this.misses += 1;
return undefined;
}
if (this.now() >= entry.expiresAt) {
this.store.delete(key);
this.misses += 1;
return undefined;
}
// refresh recency
this.store.delete(key);
this.store.set(key, entry);
this.hits += 1;
return entry.value;
}
set(key: string, value: T): void {
if (this.store.has(key)) this.store.delete(key);
while (this.store.size >= this.capacity) {
const oldest = this.store.keys().next();
if (oldest.done) break;
this.store.delete(oldest.value);
this.evictions += 1;
}
this.store.set(key, { value, expiresAt: this.now() + this.ttlMs });
}
}An unbounded Map cache grows until the process is OOM-killed, and stale entries are served forever without expiry.
Use case: engineers caching expensive computations or API responses with a bounded memory budget
Inputs / outputs
- Input: capacity, per-entry TTL in milliseconds, injectable clock
- Output: cached values, or undefined on miss/expiry, plus hit/miss/eviction counters
Error conditions
- zero or negative capacity
- negative TTL
- get on an expired entry
Approach
Map preserves insertion order so the first key is the least recently used; on get, re-insert to refresh recency; on set, evict the oldest when at capacity; entries store their expiry timestamp.
Implementation
export class LruCache<T> {
private readonly store = new Map<string, { value: T; expiresAt: number }>();
private hits = 0;
private misses = 0;
private evictions = 0;
private readonly now: () => number;
private readonly capacity: number;
private readonly ttlMs: number;
constructor(options: { capacity: number; ttlMs: number; now?: () => number }) {
if (!Number.isInteger(options.capacity) || options.capacity < 1) {
throw new RangeError("capacity must be a positive integer");
}
if (!Number.isFinite(options.ttlMs) || options.ttlMs <= 0) {
throw new RangeError("ttlMs must be a positive number");
}
this.capacity = options.capacity;
this.ttlMs = options.ttlMs;
this.now = options.now ?? (() => Date.now());
}
get size(): number {
return this.store.size;
}
stats(): { hits: number; misses: number; evictions: number } {
return { hits: this.hits, misses: this.misses, evictions: this.evictions };
}
get(key: string): T | undefined {
const entry = this.store.get(key);
if (!entry) {
this.misses += 1;
return undefined;
}
if (this.now() >= entry.expiresAt) {
this.store.delete(key);
this.misses += 1;
return undefined;
}
// refresh recency
this.store.delete(key);
this.store.set(key, entry);
this.hits += 1;
return entry.value;
}
set(key: string, value: T): void {
if (this.store.has(key)) this.store.delete(key);
while (this.store.size >= this.capacity) {
const oldest = this.store.keys().next();
if (oldest.done) break;
this.store.delete(oldest.value);
this.evictions += 1;
}
this.store.set(key, { value, expiresAt: this.now() + this.ttlMs });
}
}
Verification tests
import { test } from "node:test";
import assert from "node:assert/strict";
import { LruCache } from "./example.ts";
test("evicts the least recently used key at capacity", () => {
const cache = new LruCache<number>({ capacity: 2, ttlMs: 10_000 });
cache.set("a", 1);
cache.set("b", 2);
assert.equal(cache.get("a"), 1); // a becomes most recently used
cache.set("c", 3); // evicts b
assert.equal(cache.get("b"), undefined);
assert.equal(cache.get("a"), 1);
assert.equal(cache.get("c"), 3);
});
test("expires entries after the TTL", () => {
let clock = 0;
const cache = new LruCache<string>({ capacity: 4, ttlMs: 100, now: () => clock });
cache.set("k", "v");
clock = 99;
assert.equal(cache.get("k"), "v");
clock = 100;
assert.equal(cache.get("k"), undefined);
});
test("counts hits misses and evictions", () => {
const cache = new LruCache<number>({ capacity: 1, ttlMs: 10_000 });
cache.set("a", 1);
cache.get("a");
cache.get("missing");
cache.set("b", 2); // evicts a
assert.deepEqual(cache.stats(), { hits: 1, misses: 1, evictions: 1 });
});
test("rejects invalid options", () => {
assert.throws(() => new LruCache({ capacity: 0, ttlMs: 1 }), RangeError);
assert.throws(() => new LruCache({ capacity: 1, ttlMs: 0 }), RangeError);
});
Dependencies and running
No external dependencies (standard library only).
Runtime: node >= 18 Entry point: node –experimental-strip-types example.ts
Limitations and error handling
no async loading of missing keys; no persistence; single process only.
Verification boundary
execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox
Interactive Tools for This Topic
Report a problem with this exampleOpens a pre-filled issue on GitHub.