Backend Case Studies

Topic B4

Caching and LRU caches

Keeping expensive results in memory, and how LRU picks what to throw out.

10 min · intermediate

Watch: the cache has only three slots. When it's full, whatever has gone unused longest is thrown out, so popular items stay.

newestevicted nextrequestscacheDBABCADABEA
  • moving now
  • being checked
  • finished / the result
  • no longer used
Step 1 of 11

The cache holds 3 items. LRU: when full, evict whatever has gone unused the longest. Every time an item is used, it moves to the front.

When the cache is full, something has to go. The eviction rule decides how many requests can skip the database.

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

  1. A full LRU cache holds [A, B, C] (A newest). Then get(C), then set(D). What's evicted?

  2. Why does LRU use a hash map AND a linked list?

  3. A cache has a 15% hit rate. What does that mean?

0 of 3 answered.