Topic B4
Caching and LRU caches
Keeping expensive results in memory, and how LRU picks what to throw out.
Watch: the cache has only three slots. When it's full, whatever has gone unused longest is thrown out, so popular items stay.
- moving now
- being checked
- finished / the result
- no longer used
Like a desk
The filing cabinet holds every document, but it's far away. Your desk fits only three folders. The ones in use sit on the desk; if you need a fourth, one goes back to the cabinet. The sensible choice: the folder you haven't touched for the longest. That's LRU. The cabinet is the database; the desk is the cache.
Hash map + linked list
LRU needs two things to be fast at once:
- Finding an item by key: a hash map, O(1).
- Moving an item to the front and dropping the last one: a doubly linked list, O(1) because only pointers change.
The hash map holds a pointer straight to the item's list node. In JavaScript, Map remembers insertion order, so "delete then set again" is enough to move an item to the end (the newest).
Code, for programmersAn LRU cache with a Map
class LRU {
constructor(capacity) { this.capacity = capacity; this.map = new Map(); }
get(key) {
if (!this.map.has(key)) return undefined; // miss
const value = this.map.get(key);
this.map.delete(key); // move to the end = most recent
this.map.set(key, value);
return value;
}
set(key, value) {
this.map.delete(key);
this.map.set(key, value);
if (this.map.size > this.capacity) {
const oldest = this.map.keys().next().value; // first key = least recent
this.map.delete(oldest);
}
}
}Cache-aside, the most common pattern
Code, for programmersCheck the cache first, fill it on a miss
async function getProduct(id) {
const key = `product:${id}`;
const hit = await redis.get(key);
if (hit) return JSON.parse(hit); // fast path
const product = await db.product.findUnique({ where: { id } });
await redis.set(key, JSON.stringify(product), "EX", 300); // keep for 5 minutes
return product;
}Quiz
A full LRU cache holds [A, B, C] (A newest). Then get(C), then set(D). What's evicted?
Why does LRU use a hash map AND a linked list?
A cache has a 15% hit rate. What does that mean?
0 of 3 answered.