← Back to Node.js, page 8

nodejs-0144 · Medium mid

How do you build an in-memory LRU cache with a TTL in Node.js, and what are the limits of in-process caching?

A JavaScript Map keeps insertion order, so an LRU cache is a Map where each read deletes and re-inserts the key to mark it recent, and eviction removes the first key when the size limit is exceeded. Store an expiry time with each value and check it on read. In-process caches are fast but are per instance, vanish on restart, and need a size bound, so use a shared cache such as Redis when instances must agree.

Full answer

The structure

  • Map iterates in insertion order. The first key is the least recently used (LRU) when you re-insert on every read.
  • get(key): read the entry. If it is missing or expired, return undefined (and delete if expired). Otherwise delete and set the key again to move it to the end, then return the value.
  • set(key, value): delete the key if present, insert with expiry = now + ttl, then while size > max, delete map.keys().next().value.
  • Both operations are O(1) on average.
  • Inject the clock (a now function) so that tests do not need real waiting.

Decisions

  • Bound the cache by entries or by estimated bytes. An unbounded Map is a memory leak.
  • TTL protects against stale data. Choose it from how wrong the data is allowed to be, add small random jitter so many keys do not expire at once.
  • Cache promises or add request coalescing to avoid a stampede on a miss.
  • Negative caching: remember 'not found' for a short time to protect the database from repeated lookups.
  • Invalidate on write: delete the key when the source changes.

Limits of in-process caches

  • Each instance has its own copy, so instances can disagree and invalidation does not cross processes.
  • Data is lost on restart (cold start causes a burst of misses).
  • It uses the Node heap, which adds garbage collection work. Large caches belong in Redis or Memcached.
  • Libraries: lru-cache (well tested, has TTL, size accounting and stale options). Prefer it in production over your own class.
javascript
class LruCache {
  constructor({ max, ttlMs, now = Date.now }) {
    this.max = max; this.ttlMs = ttlMs; this.now = now;
    this.map = new Map();
    this.hits = 0; this.misses = 0;
  }
  get(key) {
    const entry = this.map.get(key);
    if (!entry || entry.expiresAt <= this.now()) {
      if (entry) this.map.delete(key);           // expired
      this.misses++;
      return undefined;
    }
    this.map.delete(key);                        // move to the most recent position
    this.map.set(key, entry);
    this.hits++;
    return entry.value;
  }
  set(key, value) {
    this.map.delete(key);
    this.map.set(key, { value, expiresAt: this.now() + this.ttlMs });
    while (this.map.size > this.max) this.map.delete(this.map.keys().next().value); // evict the least recently used
  }
  keys() { return [...this.map.keys()]; }
}

let time = 0;                                     // a fake clock in milliseconds
const cache = new LruCache({ max: 3, ttlMs: 1000, now: () => time });

cache.set('a', 1); cache.set('b', 2); cache.set('c', 3);
console.log('order after 3 sets      :', cache.keys().join(','));
cache.get('a');
console.log('order after reading a   :', cache.keys().join(','));
cache.set('d', 4);
console.log('after adding d (max 3)  :', cache.keys().join(','), '| b was evicted:', cache.get('b') === undefined);

time = 999; console.log('at 999 ms, a still there:', cache.get('a'));
time = 1001; console.log('at 1001 ms, a expired    :', cache.get('a'));
console.log('hits:', cache.hits, '| misses:', cache.misses);

// Without a bound, a Map used as a cache grows forever.
const unbounded = new Map();
for (let i = 0; i < 100000; i++) unbounded.set('request-' + i, i);
console.log('unbounded map size after 100000 different keys:', unbounded.size);

A fake clock makes the TTL behaviour exact. The last lines show why a bound is needed. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): order after 3 sets : a,b,c order after reading a : b,c,a after adding d (max 3) : c,a,d | b was evicted: true at 999 ms, a still there: 1 at 1001 ms, a expired : undefined hits: 2 | misses: 2 unbounded map size after 100000 different keys: 100000

Key points

  • Map order gives O(1) LRU: delete and set on read, drop the first key on overflow.
  • Store an expiry and check it on read.
  • Always bound the size.
  • Add negative caching and jitter where needed.
  • In-process caches are per instance and lost on restart.

Common mistakes

  • Using a plain object or Map as an unbounded cache.
  • Not moving a key on read, which turns LRU into FIFO.
  • Using Date.now() directly and making tests slow or flaky.
  • Caching mutable objects and letting callers change them.
  • Expecting all instances to share the same cache.

Follow-ups

  • How does lru-cache handle size by bytes?
  • How do you invalidate entries across several instances?
  • What is the difference between LRU and LFU?

Tips

  • Say 'Map keeps insertion order' in the first sentence.
  • Describe get and set in two lines.
  • Name the limits of in-process caching.