Why This Matters at Engineering Leadership Scale
Caching is the fastest way to cut database load and the easiest way to ship memory leaks or stale authorization bugs. Across SaaS teams, engineers routinely drop an unbounded Map into a service module and call it a cache. Within weeks, heap usage climbs until pods crash, or revoked entitlements stay cached past expiry.
In senior engineering and Engineering Manager coding loops, the LRU Cache with TTL Expiry tests two instincts: selecting O(1) data structures under load, and structuring clean seams that absorb Minute-30 curveballs (per-key TTL overrides, active expiry sweeps, async stampede coalescing, and hit/miss telemetry) without rewriting pointer logic.
Core Mental Model & Architecture
| Data Structure Approach | get(k) | put(k, v) | Evict Oldest | Why It Wins or Fails |
|---|---|---|---|---|
| HashMap + Doubly-Linked List | O(1) | O(1) | O(1) | Direct prev/next pointers unlink any middle node without scanning |
| HashMap + Singly-Linked List | O(N) | O(N) | O(1) | Unlinking a middle node forces an O(N) scan from head |
| HashMap + Min-Heap | O(log N) | O(log N) | O(log N) | Heap bubble-up on every read adds avoidable overhead |
JS Map Only | O(1) | O(1) | O(1) | Works in JS/TS; explicit DLL proves language-agnostic rigor |
Why pair a HashMap with a doubly-linked list instead of a singly-linked list? On get(key), you locate node in O(1) from the map, then unlink it from the middle and move it to the head. Without node.prev, finding the predecessor costs O(N). Dummy head/tail sentinels remove null-pointer edge cases.
For thread and async safety: multi-threaded runtimes (Java, Go) guard pointer updates with a mutex or sharded locks. In Node.js/TypeScript, pointer mutations are atomic per tick, but async misses race: an inFlight: Map<K, Promise<V>> coalesces 50 concurrent cache misses onto one backend load.
Step-by-Step Implementation Tutorial
1. Implement the O(1) Doubly-Linked List, TTL Expiry, and Single-Flight Loader (Minutes 5 to 28)
export interface Clock { nowMs(): number; }
export interface CacheStats {
hits: number; misses: number; expirations: number; evictions: number; size: number; hitRate: number;
}
interface LruNode<K, V> {
key: K; value: V; expiresAtMs: number; prev: LruNode<K, V> | null; next: LruNode<K, V> | null;
}
export class AsyncTtlLruCache<K, V> {
private readonly map = new Map<K, LruNode<K, V>>();
private readonly inFlight = new Map<K, Promise<V>>();
private readonly head: LruNode<K, V>;
private readonly tail: LruNode<K, V>;
private hits = 0; private misses = 0; private expirations = 0; private evictions = 0;
constructor(
private readonly capacity: number,
private readonly defaultTtlMs: number,
private readonly clock: Clock = { nowMs: () => Date.now() }
) {
if (capacity <= 0 || defaultTtlMs <= 0) throw new Error("capacity and defaultTtlMs must be positive");
this.head = { key: null as unknown as K, value: null as unknown as V, expiresAtMs: 0, prev: null, next: null };
this.tail = { key: null as unknown as K, value: null as unknown as V, expiresAtMs: 0, prev: null, next: null };
this.head.next = this.tail;
this.tail.prev = this.head;
}
public get(key: K): V | undefined {
const node = this.map.get(key);
if (!node) { this.misses++; return undefined; }
// Minute-30 Extension: Lazy expiry on get()
if (this.clock.nowMs() >= node.expiresAtMs) {
this.deleteNode(node);
this.expirations++;
this.misses++;
return undefined;
}
this.moveToHead(node);
this.hits++;
return node.value;
}
// Minute-30 Extension: Per-key custom TTL override
public put(key: K, value: V, ttlMs = this.defaultTtlMs): void {
if (ttlMs <= 0) throw new Error("ttlMs must be positive");
const expiresAtMs = this.clock.nowMs() + ttlMs;
const existing = this.map.get(key);
if (existing) {
existing.value = value;
existing.expiresAtMs = expiresAtMs;
this.moveToHead(existing);
return;
}
const node: LruNode<K, V> = { key, value, expiresAtMs, prev: null, next: null };
this.map.set(key, node);
this.addToHead(node);
if (this.map.size > this.capacity && this.tail.prev && this.tail.prev !== this.head) {
this.deleteNode(this.tail.prev);
this.evictions++;
}
}
public async getOrLoad(key: K, loader: () => Promise<V>, ttlMs = this.defaultTtlMs): Promise<V> {
const cached = this.get(key);
if (cached !== undefined) return cached;
const pending = this.inFlight.get(key);
if (pending) return pending;
const promise = loader()
.then((val) => { this.put(key, val, ttlMs); return val; })
.finally(() => { this.inFlight.delete(key); });
this.inFlight.set(key, promise);
return promise;
}
// Minute-30 Extension: Active sweep for unread expired entries
public purgeExpired(): number {
const now = this.clock.nowMs();
let purged = 0;
let cur = this.tail.prev;
while (cur && cur !== this.head) {
const prev = cur.prev;
if (now >= cur.expiresAtMs) { this.deleteNode(cur); this.expirations++; purged++; }
cur = prev;
}
return purged;
}
public getStats(): CacheStats {
const total = this.hits + this.misses;
return {
hits: this.hits, misses: this.misses, expirations: this.expirations,
evictions: this.evictions, size: this.map.size,
hitRate: total === 0 ? 0 : Number((this.hits / total).toFixed(4)),
};
}
private addToHead(n: LruNode<K, V>): void {
n.prev = this.head; n.next = this.head.next;
if (this.head.next) this.head.next.prev = n;
this.head.next = n;
}
private removeNode(n: LruNode<K, V>): void {
if (n.prev) n.prev.next = n.next;
if (n.next) n.next.prev = n.prev;
n.prev = null; n.next = null;
}
private moveToHead(n: LruNode<K, V>): void { this.removeNode(n); this.addToHead(n); }
private deleteNode(n: LruNode<K, V>): void { this.removeNode(n); this.map.delete(n.key); }
}2. Write Focused Unit Tests (Minutes 30 to 35)
Using a fake Clock, assert: (1) LRU eviction order after touching A before inserting C, (2) per-key custom TTL (500ms expires while 5,000ms stays live), (3) purgeExpired() removes untouched expired entries, (4) 20 concurrent getOrLoad() calls trigger loader once, and (5) a rejected loader clears inFlight in finally.
3. Absorb the Minute-30 Extension (Minutes 35 to 50)
Storing expiresAtMs on each LruNode makes per-key TTLs a 1-parameter change. Lazy expiry guarantees O(1) fresh reads, purgeExpired() reclaims unread zombie keys, and getStats() exposes capacity thrashing immediately.
Worked Production Scenario: Before vs. After
Context: A B2B SaaS authorization service ran 18,000 permission checks/sec across 6 squads behind an uncapped Map with a fixed 5-minute TTL and no stampede guard. Every 5 minutes when a hot tenant expired, 120 concurrent requests slammed PostgreSQL to 94% CPU, while short-lived tokens grew pod heap to 1.8 GB over 48 hours.
After: The Identity squad deployed AsyncTtlLruCache (cap 20,000, 60s default TTL, 10s override for admin tokens, 30s purgeExpired() sweep, getOrLoad coalescing, and Prometheus getStats() export).
| Metric | Before | After |
|---|---|---|
| PostgreSQL CPU spikes at TTL expiry | 94% every 5 mins | 18% steady |
| Permission API p99 latency | 640 ms | 14 ms |
| Pod heap memory after 72 hours | 1.8 GB (OOM risk) | 210 MB flat |
| Cache hit rate visibility | None | 96.4% in Grafana |
Common Failure Modes & Anti-Patterns
- Evicting live entries while expired entries sit in memory: Dropping
tail.prevblindly wastes slots on stale items. Fix: Run periodicpurgeExpired()sweeps or check tail expiry before evicting live entries. - Leaking rejected promises in
inFlight: Missing.finally(() => this.inFlight.delete(key))pins future callers to a dead error permanently. Fix: Always removeinFlightentries infinally. - Ambiguous
undefinednegative caching: Checkingcached !== undefinedconflates a miss with a cached "not found". Fix: Store{ found: true, value } | { found: false }wrappers when negative caching is needed.
How to Handle Pushback in the Room
Skeptical Principal Engineer: "Why write a doubly-linked list in TypeScript when JS Map preserves insertion order?"
Calm Response: "In production Node.js, wrapping Map is fine for plain LRU. Tech Leads still need the HashMap-plus-DLL invariant because it transfers directly to Go, Java, and C++, and explicit node objects keep per-key metadata like expiresAtMs clean."
VP of Engineering: "Our cache hit rate is 45% - should we double pod RAM to raise capacity?"
Calm Response: "Not before checking evictions versus expirations. If expirations drive most misses, doubling RAM wastes money because entries time out before reuse. Telemetry tells us in two minutes whether we have a capacity or TTL issue."
Key Takeaways & This Week's Action Rep
- Pair
HashMapwith a doubly-linked list: Dummyhead/tailsentinels holdO(1)reads, writes, and evictions cleanly. - Combine lazy expiry with
purgeExpired(): Prevent both stale reads and zombie memory leaks. - Coalesce async misses with
inFlight: Turn a 100-caller stampede into one DB query. - Instrument every cache from day one: Export
hits,misses,expirations, andevictions.
This Week's Action Rep: Audit one in-memory cache in your primary service for a hard size cap, per-key TTL support, async stampede coalescing, and hit-rate metrics, and open a ticket for any missing guardrail.