Understanding LRU Cache: Concepts, Use Cases, and a TypeScript Implementation with Bun
Memory is fast, and memory is finite. Every system that caches data in RAM eventually hits the same question: when the cache is full, what do you throw away?
The Least Recently Used (LRU) eviction policy is the most widely used answer to that question. It is simple to reason about, fast to implement, and remarkably effective for real-world workloads.
In this article, we will cover what an LRU cache is, why it works, where it is used in production, where it falls short, and how to build and test a clean naive implementation in TypeScript using Bun.
What Is an LRU Cache?
An LRU cache is a bounded key-value store that tracks the order in which entries are accessed. Whenever the cache reaches its maximum capacity and a new item needs to be inserted, it evicts the item that has gone the longest without being read or written.
The policy relies on a fundamental observation about software workloads called temporal locality: if a piece of data was accessed recently, there is a high probability it will be accessed again soon. Conversely, data that has not been touched in a while is the safest candidate to drop.
How It Works Step by Step
Suppose we have an LRU cache with a capacity of 3. We will represent the cache from most recently used (MRU) on the left to least recently used (LRU) on the right:
put("A", 1) -> [ A ]
put("B", 2) -> [ B, A ]
put("C", 3) -> [ C, B, A ] (cache is now full)
get("A") -> [ A, C, B ] ("A" moves to the front)
put("D", 4) -> [ D, A, C ] ("B" is evicted as LRU)
Notice two important rules:
- Both
getandputrefresh recency. Reading"A"promotes it to the most-recently-used position so it survives the next eviction. - Updating an existing key does not grow the cache. Calling
put("C", 30)updates the value and moves"C"to the front without evicting anything.
What Is LRU Used For?
LRU shows up at almost every layer of the computing stack:
- Operating Systems & CPUs: Hardware caches and OS page-replacement algorithms use LRU (or low-overhead approximations like Clock/Second-Chance) to decide which memory pages stay in RAM and which get swapped to disk.
- Databases: Storage engines maintain buffer pools of recently read disk pages. Keeping hot index and table pages in memory avoids expensive disk I/O.
- Backend APIs & Microservices: Caching database query results, parsed JWT public keys (JWKS), rendered templates, or configuration objects in process memory reduces latency from milliseconds to microseconds.
- CDNs & Reverse Proxies: Edge servers cache static assets and HTTP responses; popular assets stay warm while stale or rarely requested files are evicted automatically.
- Frontend Applications: Browsers, state managers, and query libraries use bounded caches to store API responses, decoded images, or memoized computations without leaking memory over long sessions.
Trade-offs and When Not to Use LRU
LRU is a strong default, not a silver bullet. Knowing its failure modes will save you from subtle performance regressions:
- Scan Pollution: If a background job iterates over a large dataset once (a full table scan or bulk export), it can flush every genuinely hot item out of the cache and replace them with one-time data.
- Frequency Blindness: LRU only cares about when an item was last used, not how often. An item accessed 10,000 times over the last hour can be evicted by a burst of one-hit wonders. Policies like LFU (Least Frequently Used), W-TinyLFU, or SIEVE handle this better.
- Count vs. Memory Size: Limiting a cache to
1,000entries does not bound memory usage if one entry is 50 bytes and another is 50 MB. For variable-sized payloads, you need a byte-size budget rather than (or in addition to) an item-count limit.
Naive Implementation in TypeScript with Bun
In many languages, an O(1) LRU cache requires combining a hash map (for fast lookups) with a doubly linked list (for O(1) promotion and tail eviction).
In JavaScript and TypeScript, however, the built-in Map preserves insertion order by specification. That lets us write a clean, naive, zero-dependency LRU cache in under 60 lines of TypeScript:
- The oldest entry is always the first item returned by
map.keys().next(). - To promote an entry on access, we delete it and re-insert it, moving it to the end of the
Map.
We will use Bun as our runtime because it executes TypeScript directly with zero build configuration and ships with a fast built-in test runner.
1. Project Setup
Create a fresh directory and initialize it with Bun:
mkdir lru-cache-ts && cd lru-cache-ts
bun init -y
2. Implementing LRUCache
Create src/lru.ts:
export class LRUCache<K, V> {
private readonly capacity: number;
private readonly cache: Map<K, V>;
constructor(capacity: number) {
if (!Number.isInteger(capacity) || capacity <= 0) {
throw new RangeError("Capacity must be a positive integer.");
}
this.capacity = capacity;
this.cache = new Map<K, V>();
}
get size(): number {
return this.cache.size;
}
/**
* Retrieve a value and mark it as most recently used.
*/
get(key: K): V | undefined {
if (!this.cache.has(key)) {
return undefined;
}
const value = this.cache.get(key) as V;
// Delete and re-insert to move the key to the most-recent position
this.cache.delete(key);
this.cache.set(key, value);
return value;
}
/**
* Insert or update a key-value pair.
* Evicts the least recently used entry if capacity is exceeded.
*/
put(key: K, value: V): void {
if (this.cache.has(key)) {
this.cache.delete(key);
} else if (this.cache.size >= this.capacity) {
const oldestKey = this.cache.keys().next().value;
if (oldestKey !== undefined) {
this.cache.delete(oldestKey);
}
}
this.cache.set(key, value);
}
has(key: K): boolean {
return this.cache.has(key);
}
delete(key: K): boolean {
return this.cache.delete(key);
}
clear(): void {
this.cache.clear();
}
/**
* Returns keys ordered from least recently used to most recently used.
*/
keys(): K[] {
return Array.from(this.cache.keys());
}
}
Why Call This “Naive”?
Even though Map.get, Map.set, and Map.delete are O(1) on average, this implementation is still naive compared to a production cache library:
- No TTL (Time-To-Live): Entries stay in the cache indefinitely until evicted by capacity.
- No byte-size limits: Capacity is measured strictly by entry count.
- No cache statistics: It does not track hit rate, miss rate, or eviction counts.
delete+setoverhead: Re-hashing on everyget()is slightly more expensive than relinking pointers in a custom doubly linked list, though for most JavaScript workloadsMapis fast enough.
3. Running an Example with Bun
Create example.ts to see the eviction order in action:
import { LRUCache } from "./src/lru";
interface User {
id: number;
name: string;
}
const userCache = new LRUCache<string, User>(3);
userCache.put("user:1", { id: 1, name: "Alice" });
userCache.put("user:2", { id: 2, name: "Bob" });
userCache.put("user:3", { id: 3, name: "Charlie" });
console.log("Initial order (LRU -> MRU):", userCache.keys());
// Access user:1 so it becomes the most recently used
const alice = userCache.get("user:1");
console.log("Fetched:", alice?.name);
console.log("After get(user:1):", userCache.keys());
// Inserting user:4 should evict user:2 (the least recently used)
userCache.put("user:4", { id: 4, name: "Diana" });
console.log("After put(user:4):", userCache.keys());
console.log("Is user:2 still cached?", userCache.has("user:2"));
Run it directly with Bun:
bun run example.ts
Output:
Initial order (LRU -> MRU): [ "user:1", "user:2", "user:3" ]
Fetched: Alice
After get(user:1): [ "user:2", "user:3", "user:1" ]
After put(user:4): [ "user:3", "user:1", "user:4" ]
Is user:2 still cached? false
4. Writing Tests with bun:test
A cache with subtle off-by-one bugs is worse than no cache at all. Create src/lru.test.ts using Bun’s built-in test runner:
import { describe, expect, it } from "bun:test";
import { LRUCache } from "./lru";
describe("LRUCache", () => {
it("rejects non-positive or non-integer capacities", () => {
expect(() => new LRUCache(0)).toThrow(RangeError);
expect(() => new LRUCache(-5)).toThrow(RangeError);
expect(() => new LRUCache(1.5)).toThrow(RangeError);
});
it("evicts the least recently used entry when capacity is exceeded", () => {
const cache = new LRUCache<string, number>(2);
cache.put("a", 1);
cache.put("b", 2);
cache.put("c", 3);
expect(cache.get("a")).toBeUndefined();
expect(cache.get("b")).toBe(2);
expect(cache.get("c")).toBe(3);
});
it("promotes an entry on get()", () => {
const cache = new LRUCache<string, number>(2);
cache.put("a", 1);
cache.put("b", 2);
// Touch "a" so "b" becomes the LRU entry
expect(cache.get("a")).toBe(1);
cache.put("c", 3);
expect(cache.get("b")).toBeUndefined();
expect(cache.get("a")).toBe(1);
expect(cache.get("c")).toBe(3);
});
it("updates existing keys without evicting other entries", () => {
const cache = new LRUCache<string, number>(2);
cache.put("a", 1);
cache.put("b", 2);
cache.put("a", 10);
expect(cache.size).toBe(2);
expect(cache.get("a")).toBe(10);
expect(cache.get("b")).toBe(2);
});
it("handles capacity of 1 correctly", () => {
const cache = new LRUCache<string, string>(1);
cache.put("first", "one");
cache.put("second", "two");
expect(cache.size).toBe(1);
expect(cache.get("first")).toBeUndefined();
expect(cache.get("second")).toBe("two");
});
});
Run the test suite:
bun test
5. Quick Performance Check with Bun
To get a rough feel for throughput, you can run a quick micro-benchmark using Bun.nanoseconds(). Create bench.ts:
import { LRUCache } from "./src/lru";
const OPERATIONS = 500_000;
const CAPACITY = 10_000;
const cache = new LRUCache<number, number>(CAPACITY);
const start = Bun.nanoseconds();
for (let i = 0; i < OPERATIONS; i++) {
const key = i % (CAPACITY * 2);
if (cache.get(key) === undefined) {
cache.put(key, i);
}
}
const elapsedMs = (Bun.nanoseconds() - start) / 1_000_000;
const opsPerSec = Math.round((OPERATIONS / elapsedMs) * 1000);
console.log(
`${OPERATIONS.toLocaleString()} ops in ${elapsedMs.toFixed(2)} ms (~${opsPerSec.toLocaleString()} ops/sec)`
);
Run it:
bun run bench.ts
On the hardware this article was written on (a mix of get() and put() operations), this naive Map-based design sustained roughly 235,000 operations per second — a number you can reproduce or beat on your own machine with bun run bench.ts. Whether that is “fast enough” depends on your workload, but for most in-process caching needs it comfortably clears the bar.
Taking It to Production
If your application outgrows a naive LRU cache, consider these next steps:
- Add TTL support: Store
{ value, expiresAt }per entry and check expiration onget(). - Track hit ratio: Exposing
hitsandmissestells you whether your cache size is actually helping or just burning RAM. - Use a battle-tested library: For Node.js and Bun projects that need TTL, byte-size limits, stale-while-revalidate, or async fetch deduplication, reach for an established package like
lru-cache. - Move out of process when needed: When running multiple server replicas that must share cached state, an external store like Redis or Valkey (configured with
maxmemory-policy allkeys-lru) is the right layer.
Summary
An LRU cache is one of the highest-leverage data structures you can reach for when optimizing latency and protecting downstream dependencies. By leveraging JavaScript’s insertion-ordered Map and Bun’s zero-config TypeScript toolchain, you can build, test, and benchmark a clean O(1) LRU cache in minutes — and understand exactly what happens under the hood before reaching for a heavier library.