Back to results for “Caching”
Node.js › Caching

How would you implement a Least Recently Used (LRU) cache in Node.js, and why is eviction necessary for an in-memory cache?

Intermediate

Answer

An LRU cache has a fixed maximum size and, once full, evicts the entry that hasn't been accessed for the longest time to make room for a new one -- this bounds memory usage while keeping the most actively used data available, based on the assumption that recently accessed data is more likely to be accessed again soon.
const { LRUCache } = require('lru-cache');

const cache = new LRUCache({ max: 1000, ttl: 1000 * 60 * 10 });

cache.set('user:123', userData);
const cached = cache.get('user:123'); // moves this entry to 'most recently used'
Real-world example A service caching computed search-result rankings for popular queries uses an LRU cache capped at 5,000 entries, so memory usage stays bounded regardless of how many unique queries are searched, automatically evicting rankings that have fallen out of recent popularity.

Common follow-ups: How does LRU eviction compare to other eviction policies like LFU (Least Frequently Used)?;What's the time complexity of get() and set() operations in a properly implemented LRU cache, and why does that matter at scale?