lru-cache
In-memory least-recently-used cache with size limits, TTL and fetch-on-miss support.
Official Documentation ↗v11.5.3. Check the official docs for the latest API surface.Installation
npm install lru-cachepnpm add lru-cacheyarn add lru-cacheMethods
No methods match this filter.
Overview
lru-cache stores a bounded set of key-value pairs and discards the least recently used entries when it reaches capacity. It is a process-local cache suitable for hot configuration, lookups and computed values.
Core Methods
The constructor takes max or maxSize limits, a default ttl, and eviction callbacks. get and set cover basic use, while fetch memoizes an async producer so concurrent misses share one computation.
Usage Notes
Pick a max that bounds memory for your process, add ttl for data that can go stale, and use fetch to prevent duplicate expensive calls. Listen to eviction events to observe pressure.
Common Pitfalls
A cache without max can grow until the process runs out of memory. Caching mutable objects lets external mutation corrupt cached state. This cache is per-process, so it does not coordinate across workers.
FAQ
- How does the max option work?
- max caps cache size, counted in entries by default. Providing maxSize with a sizeCalculation function bounds by bytes instead, which is safer for large or variable values.
- Does the cache shrink on its own?
- Eviction happens as new entries are added and via periodic TTL purging. Call purgeStale or rely on the internal timer to reclaim expired items.
- Why does my cache keep growing?
- If max is not set the cache is unbounded. Also, keys holding live objects with timers can pin memory, so store plain data and set a max or maxSize plus ttl.
Report a problem with this API docOpens a pre-filled issue on GitHub.