Implement an LRU Cache in Node.js
Build a least-recently-used cache in Node.js with O(1) get and set using a Map plus a doubly linked list, or a Map-only version for small caches.
An LRU (Least Recently Used) cache evicts the entry you touched longest ago once it runs out of room, so hot data stays in memory while total usage stays bounded. There are two common ways to build one in JavaScript: a Map plus a doubly linked list for true O(1) moves and evictions, or a Map-only shortcut that reorders entries with delete + set. Both are below, with honest notes on where each one makes sense.
When to Use This
- Caching expensive computations or database lookups inside a single process
- Rate limiting or deduplication where the oldest entries should expire first
- The L1 tier of a multi-level cache sitting in front of Redis
- Any spot where you want bounded memory and Redis would be overkill — although for cross-process or shared caching you do need an external store like Redis
Don’t reach for an in-memory cache when several instances must see the same data, or when entries are large enough that duplicating them per process costs more than the latency you save.
Prerequisites
- Node.js 18+
- No external dependencies required
Solution
1. LRU with a Map plus a doubly linked list
This is the textbook implementation: the Map gives you O(1) lookup, and the linked list gives you O(1) move-to-front and evict-from-back regardless of how big the cache grows.
// lru-cache.ts
interface LRUNode<K, V> {
key: K;
value: V;
prev: LRUNode<K, V> | null;
next: LRUNode<K, V> | null;
}
export class LRUCache<K, V> {
private index = new Map<K, LRUNode<K, V>>();
private head: LRUNode<K, V> | null = null; // most recently used
private tail: LRUNode<K, V> | null = null; // least recently used
constructor(private readonly capacity: number) {
if (capacity <= 0) {
throw new Error("Capacity must be positive");
}
}
get(key: K): V | undefined {
const node = this.index.get(key);
if (!node) return undefined;
this.moveToHead(node);
return node.value;
}
set(key: K, value: V): void {
const existing = this.index.get(key);
if (existing) {
existing.value = value;
this.moveToHead(existing);
return;
}
const node: LRUNode<K, V> = { key, value, prev: null, next: this.head };
if (this.head) this.head.prev = node;
this.head = node;
if (!this.tail) this.tail = node;
this.index.set(key, node);
if (this.index.size > this.capacity) {
this.evictTail();
}
}
delete(key: K): boolean {
const node = this.index.get(key);
if (!node) return false;
this.unlink(node);
this.index.delete(key);
return true;
}
has(key: K): boolean {
return this.index.has(key);
}
clear(): void {
this.index.clear();
this.head = null;
this.tail = null;
}
get size(): number {
return this.index.size;
}
*entries(): IterableIterator<[K, V]> {
let node = this.head;
while (node) {
yield [node.key, node.value];
node = node.next;
}
}
private moveToHead(node: LRUNode<K, V>): void {
if (node === this.head) return;
this.unlink(node);
node.prev = null;
node.next = this.head;
if (this.head) this.head.prev = node;
this.head = node;
}
private unlink(node: LRUNode<K, V>): void {
if (node.prev) node.prev.next = node.next;
if (node.next) node.next.prev = node.prev;
if (node === this.tail) this.tail = node.prev;
}
private evictTail(): void {
if (!this.tail) return;
this.index.delete(this.tail.key);
this.tail = this.tail.prev;
if (this.tail) {
this.tail.next = null;
} else {
this.head = null;
}
}
}
2. Map-only version for small caches
If the cache will never hold more than a few hundred entries, you can skip the linked list. Map preserves insertion order, so delete + set moves a key to the most-recent position and the first iterated key is the least recently used.
// lru-cache-map.ts
export class MapLRUCache<K, V> {
private cache = new Map<K, V>();
constructor(private readonly capacity: number) {
if (capacity <= 0) {
throw new Error("Capacity must be positive");
}
}
get(key: K): V | undefined {
if (!this.cache.has(key)) return undefined;
const value = this.cache.get(key)!;
this.cache.delete(key);
this.cache.set(key, value);
return value;
}
set(key: K, value: V): void {
if (this.cache.has(key)) {
this.cache.delete(key);
} else if (this.cache.size >= this.capacity) {
const oldest = this.cache.keys().next().value;
if (oldest !== undefined) this.cache.delete(oldest);
}
this.cache.set(key, value);
}
has(key: K): boolean {
return this.cache.has(key);
}
get size(): number {
return this.cache.size;
}
}
The catch: the cost isn’t uniformly O(1). Under a churn-heavy workload the leading edge of the Map fills with deleted slots, and keys().next() has to step past them on every eviction. Published benchmarks of this exact pattern show eviction slowing down sharply once you get into tens of thousands of keys — at that point, use the linked-list version or the lru-cache package. For a small rate limiter or memoized helper, the Map-only version is perfectly fine and easier to read.
3. Add TTL support
// ttl-cache.ts
interface CacheEntry<V> {
value: V;
expiresAt: number;
}
export class TTLCache<K, V> {
private cache = new Map<K, CacheEntry<V>>();
private cleanupTimer: NodeJS.Timeout | null = null;
constructor(
private readonly capacity: number,
private readonly defaultTtl: number = 300_000,
) {}
get(key: K): V | undefined {
const entry = this.cache.get(key);
if (!entry) return undefined;
if (Date.now() > entry.expiresAt) {
this.cache.delete(key);
return undefined;
}
this.cache.delete(key);
this.cache.set(key, entry);
return entry.value;
}
set(key: K, value: V, ttl: number = this.defaultTtl): void {
if (this.cache.has(key)) {
this.cache.delete(key);
} else if (this.cache.size >= this.capacity) {
const oldest = this.cache.keys().next().value;
if (oldest !== undefined) this.cache.delete(oldest);
}
this.cache.set(key, { value, expiresAt: Date.now() + ttl });
}
startCleanup(interval: number = 60_000): void {
if (this.cleanupTimer) return;
this.cleanupTimer = setInterval(() => this.cleanup(), interval);
this.cleanupTimer.unref();
}
stopCleanup(): void {
if (this.cleanupTimer) {
clearInterval(this.cleanupTimer);
this.cleanupTimer = null;
}
}
private cleanup(): void {
const now = Date.now();
for (const [key, entry] of this.cache) {
if (now > entry.expiresAt) {
this.cache.delete(key);
}
}
}
get size(): number {
return this.cache.size;
}
clear(): void {
this.cache.clear();
}
}
One detail matters in cleanup(): entries are stored in insertion order, not expiry order, because each set can carry a different TTL. You need to scan the whole Map — stopping at the first live entry would leave expired ones behind.
4. Wrap a function with caching
// memoize.ts
import { LRUCache } from './lru-cache';
export function memoize<Args extends unknown[], R>(
fn: (...args: Args) => R,
capacity: number = 100,
keyFn: (...args: Args) => string = (...args) => JSON.stringify(args),
): (...args: Args) => R {
const cache = new LRUCache<string, R>(capacity);
return (...args: Args): R => {
const key = keyFn(...args);
const cached = cache.get(key);
if (cached !== undefined) {
return cached;
}
const result = fn(...args);
cache.set(key, result);
return result;
};
}
// Usage
const expensiveCompute = memoize(
(n: number) => {
console.log(`Computing for ${n}...`);
return n * n;
},
50,
);
expensiveCompute(5); // "Computing for 5..." → 25
expensiveCompute(5); // 25 (from cache)
How It Works
- The
Mapindexes nodes by key, sogetis a single hash lookup andsetcan find an existing entry without walking the list. - The linked list tracks recency. Any access (
getorseton an existing key) unlinks the node and re-links it at the head; the tail is always the least recently used entry and costs O(1) to remove. - TTL entries wrap the value with an
expiresAttimestamp.getchecks expiry lazily on access, and the periodic sweeper removes whatever is left.unref()on the cleanup timer keeps it from pinning the event loop. - The Map-only shortcut leans on insertion order instead of a list:
delete+setre-appends the key. It reads well and wins on simplicity, but eviction stops being cheap once the leading edge of the table fills with dead slots.
Variants
Async LRU cache
For caching async operations (API calls, DB queries), store the promise rather than the resolved value so concurrent callers share one in-flight request. Handle rejections explicitly — a failed fetch shouldn’t stay cached:
export class AsyncLRUCache<K, V> {
private cache = new Map<K, { promise: Promise<V>; expiresAt: number }>();
constructor(
private readonly capacity: number,
private readonly ttl: number = 300_000,
) {}
async get(key: K, loader: () => Promise<V>): Promise<V> {
const entry = this.cache.get(key);
if (entry && Date.now() < entry.expiresAt) {
this.cache.delete(key);
this.cache.set(key, entry);
return entry.promise;
}
const promise = loader().then(
(v) => v,
(err) => {
this.cache.delete(key); // don't cache failures
throw err;
},
);
this.cache.set(key, { promise, expiresAt: Date.now() + this.ttl });
if (this.cache.size > this.capacity) {
const oldest = this.cache.keys().next().value;
if (oldest !== undefined) this.cache.delete(oldest);
}
return promise;
}
}
Using the lru-cache package
For production services the lru-cache package is the safer default — it handles size-based limits, stale reads, disposal callbacks, and the edge cases you won’t think of on a Friday afternoon:
npm install lru-cache
import { LRUCache } from 'lru-cache';
const cache = new LRUCache<string, { id: number; name: string }>({
max: 500,
ttl: 300_000,
updateAgeOnGet: true,
dispose: (value, key, reason) => {
console.log(`Evicted ${key}: ${reason}`);
},
});
Map-only vs linked list: which one?
| Map + linked list | Map only (delete+set) | lru-cache package | |
|---|---|---|---|
get/set cost | O(1), uniform | O(1) amortized, degrades under churn | O(1) |
| Best at | Any size, hot eviction loops | A few hundred keys | Any size, production |
| Code size | ~80 lines | ~25 lines | One dependency |
| Extras | You build them | You build them | TTL, maxSize, dispose, stale reads |
A rule of thumb that holds up in practice: reach for the Map-only version when the capacity is small and you want zero ceremony, the linked list when evictions are frequent or capacity is in the thousands, and the npm package when you need TTL, dispose, or byte-size accounting and don’t want to maintain it yourself.
The benchmark in the companion repo makes the gap concrete. On a dev machine (Node 26, 20,000 set calls that each force an eviction) the Map-only version took 3.9 ms at capacity 100 — but 31.9 ms at 10,000 and 36.3 ms at 50,000. The linked-list version stayed flat: 2.3, 1.9 and 4.5 ms for the same sizes. Below a few hundred keys the difference is noise; past a few thousand the Map-only eviction becomes the bottleneck.
Best Practices
- Size the capacity against your memory budget, not your record count. Rough size-per-entry math beats guessing; the linked list adds two pointers plus a wrapper object per entry.
- Combine LRU eviction with TTL when data can go stale — eviction bounds memory, expiry bounds staleness.
- Always
unref()cleanup timers so they can’t keep the process alive at shutdown. - Track hit rate in
get(hits / total lookups) and log it periodically; a cache below ~60% hits usually means the capacity is too small or the access pattern has no reuse. - Use
maxSize+sizeCalculationinlru-cacheif entries vary a lot in size — a count limit alone won’t protect memory.
Common Mistakes
- Re-setting without deleting first —
Map.seton an existing key updates the value but doesn’t move it in iteration order, so a recently used entry can get evicted early. - Assuming the Map-only version stays O(1) at scale — it doesn’t under eviction-heavy loads; that’s the workload the linked list exists for.
- Caching rejected promises — without the
catch-and-delete step above, a transient failure poisons the entry until its TTL runs out. - Expecting shared state across processes — every Node.js process keeps its own copy; use Redis when workers need a common view.
- Caching
undefinedresults — agetthat returnsundefinedlooks exactly like a miss; store a sentinel or usehas()ifundefinedis a legitimate value.
Further Reading
- node-lru-cache (isaacs) — the de facto standard implementation and its option surface.
- MDN: Map — insertion-order semantics that make the Map-only version possible.
- Multi-Level Cache with In-Memory L1 and Redis L2 — where an in-process LRU fits in a two-tier design.
- Cache-Aside Pattern — the read/write strategy an LRU cache usually serves.
- Runnable companion examples — both implementations plus a small benchmark script.
Frequently Asked Questions
Why does the Map delete-and-set trick get slow at large sizes?
Map keeps entries in insertion order, so keys().next() returns the oldest one — but under heavy churn the head of the underlying table accumulates deleted slots that the iterator has to skip. The effect is small at a few hundred keys and pronounced at tens of thousands. A linked list sidesteps it entirely because eviction just cuts the tail pointer.
What is the time complexity of get and set?
O(1) for both. The Map lookup is constant time, and moving a node or dropping the tail touches a fixed number of pointers.
Should I use this or the lru-cache npm package?
Ship the package in production services. Writing your own is worth it for learning, for very small caches where a dependency feels heavy, or when you need behavior the package doesn't expose.
Can I use WeakMap instead of Map?
No. WeakMap can't be iterated, and LRU eviction depends on knowing which entry is oldest. It's also designed for a different problem — letting the GC collect keys, not bounded capacity.
How do I monitor cache hit rate?
Keep two counters in get — one for hits, one for misses — and expose them via a stats() method or a periodic log line. Divide hits by total lookups; most healthy caches sit well above 0.6.
Related Resources
Caching with Redis
How to implement application caching using Redis for performance and scalability.
RecipeCache Function Results with Redis and TTL in Python
Build a Python decorator that caches function return values in Redis with configurable TTL, key generation, and cache invalidation
PatternCache-Aside Pattern
Load data into the cache on demand from the backing store. A caching pattern that gives the application full control over what and when to cache.
RecipeMulti-Level Cache with In-Memory L1 and Redis L2
Cut Redis round-trips on hot keys: in-memory L1 for microsecond reads, Redis L2 for shared state, and pub/sub invalidation across instances
RecipeConfigure Caffeine Cache in Java with Eviction Policies
Set up Caffeine cache in a Java application with size-based, time-based, and weighted eviction policies for high-performance local caching.