lru-cache, memory-cache, node-cache, and node-persist are all JavaScript libraries used for caching or storing data in Node.js applications, but they serve different purposes. lru-cache provides a high-performance, size-limited Least Recently Used cache ideal for memory-constrained environments. memory-cache offers a simple in-memory key-value store with optional time-based expiration but no size limits. node-cache delivers a configurable in-memory cache with TTL, max key limits, and built-in statistics. node-persist is not an in-memory cache at all—it's a disk-based persistent storage solution that saves data to the filesystem, making it suitable for preserving state across application restarts rather than improving runtime performance.
When building backend services or CLI tools in Node.js, caching is a common pattern to avoid redundant computation or I/O. The packages lru-cache, memory-cache, node-cache, and node-persist all offer ways to store data temporarily—but they differ significantly in scope, behavior, and use cases. Let’s examine them side by side from an architectural standpoint.
lru-cache is a strict, high-performance Least Recently Used (LRU) cache. It enforces size limits based on item count or total size and automatically evicts the least recently accessed entries. It’s designed for scenarios where you need predictable memory usage and deterministic eviction.
// lru-cache: Enforce max size with automatic LRU eviction
import { LRUCache } from 'lru-cache';
const cache = new LRUCache({
max: 100, // max 100 items
ttl: 1000 * 60 * 5 // 5 minutes
});
cache.set('user:123', userData);
const user = cache.get('user:123');
memory-cache is a simple, unbounded in-memory key-value store with optional TTLs. It does not enforce any size limit—so it can grow indefinitely if you’re not careful. Best suited for short-lived scripts or low-scale applications where memory pressure isn’t a concern.
// memory-cache: Basic TTL-based caching, no size limits
import cache from 'memory-cache';
cache.put('session:abc', sessionData, 300000); // 5 minutes
const data = cache.get('session:abc');
node-cache offers a middle ground: in-memory caching with optional max keys, TTL, and checkperiod-based cleanup. It supports stats tracking and event hooks, making it more suitable for long-running services that need observability.
// node-cache: Configurable in-memory cache with stats
import NodeCache from 'node-cache';
const cache = new NodeCache({
stdTTL: 600, // default TTL: 10 minutes
checkperiod: 120, // scan for expired every 2 mins
useClones: false // avoid deep cloning for performance
});
cache.set('config:prod', config);
const cfg = cache.get('config:prod');
node-persist is not an in-memory cache—it’s a persistent key-value store that writes data to disk using fs. It’s meant for saving application state between process restarts, not for performance optimization. Think of it as a lightweight alternative to databases for small datasets.
// node-persist: Persistent storage across restarts
import * as storage from 'node-persist';
await storage.init(); // creates ./storage dir
await storage.setItem('lastRun', Date.now());
const last = await storage.getItem('lastRun');
⚠️ Important:
node-persistshould not be used as a drop-in replacement for in-memory caches. Its I/O overhead makes it orders of magnitude slower than RAM-based solutions.
lru-cache: Supports per-item ttl (time-to-live) and global ttl. Items expire after their TTL, regardless of access.memory-cache: Only supports TTL via the put(key, value, time) API. No background cleanup—expired items linger until accessed.node-cache: Uses stdTTL for default expiry and checkperiod to run a background sweeper that removes stale entries.node-persist: Does not support TTL natively. You must implement expiration logic yourself (e.g., store timestamps and filter manually).lru-cache: Yes — via max (item count) or maxSize + sizeCalculation (for byte-aware eviction).memory-cache: No — unlimited growth.node-cache: Optional — via maxKeys. When exceeded, oldest entries are removed.node-persist: No built-in limit. Disk space is your only constraint.lru-cache uses a Map-like interface (set, get, delete, has) and supports advanced features like fetch() for lazy loading with deduplication:
// lru-cache: fetch with automatic deduplication
const user = await cache.fetch('user:456', async () => {
return db.getUser(456);
});
memory-cache has a minimal API: put, get, del, clear. No events, no stats.
node-cache provides richer instrumentation:
// node-cache: Listen to events
cache.on('del', (key) => console.log(`Deleted ${key}`));
cache.on('expired', (key, val) => logExpired(key));
// Get stats
console.log(cache.getStats()); // { hits, misses, keys, ... }
node-persist mimics localStorage with setItem, getItem, removeItem, and async/await support. It also offers values(), keys(), and clear().
Only node-persist writes to disk. The other three are purely in-memory and lose all data when the process exits.
If you need both speed and durability, consider layering: use lru-cache for hot data and flush critical entries to node-persist or a real database.
As of 2024:
lru-cache: Actively maintained. Version 10+ is modern ESM-first.memory-cache: Last published in 2018. Functionally stable but unmaintained. No security updates.node-cache: Actively maintained, with regular releases.node-persist: Actively maintained, though its scope remains narrow (disk persistence only).🚫 Avoid
memory-cachein new production systems due to lack of maintenance and unbounded memory growth.
You’re building a REST service that calls a slow external API. Responses should be cached for 2 minutes, and memory usage must stay under 50MB.
lru-cacheconst apiCache = new LRUCache({
maxSize: 50 * 1024 * 1024,
sizeCalculation: (value) => JSON.stringify(value).length,
ttl: 120_000
});
You need to store user sessions for 30 minutes in a hobby project with <100 concurrent users.
node-cache (with stdTTL: 1800)memory-cache (no cleanup, unmaintained)Your CLI tool needs to remember the last processed file path.
node-persistawait storage.setItem('lastFile', '/path/to/file.txt');
You’re running a microservice that requires hit/miss metrics and alerting on cache churn.
node-cache| Feature | lru-cache | memory-cache | node-cache | node-persist |
|---|---|---|---|---|
| Storage | Memory | Memory | Memory | Disk |
| Size Limit | ✅ (strict LRU) | ❌ | ✅ (maxKeys) | ❌ (disk-limited) |
| TTL Support | ✅ | ✅ (on put) | ✅ | ❌ |
| Background Cleanup | ✅ (lazy) | ❌ | ✅ (checkperiod) | ❌ |
| Persistence | ❌ | ❌ | ❌ | ✅ |
| Events / Stats | Limited | ❌ | ✅ | ❌ |
| Maintenance Status | ✅ Active | 🚫 Unmaintained | ✅ Active | ✅ Active |
lru-cachenode-cache (avoid memory-cache)node-persistmemory-cacheChoose based on whether your priority is performance, durability, observability, or simplicity—and always consider memory growth implications in long-running processes.
Choose lru-cache when you need a high-performance, memory-safe cache with strict size limits and automatic LRU eviction. It’s ideal for production services where unbounded memory growth is unacceptable, and you require predictable resource usage with optional TTL support.
Choose node-cache when you want a balanced in-memory cache with TTL, optional key limits, background cleanup, and built-in stats or event hooks. It’s well-suited for medium-scale services that need observability without the complexity of full LRU management.
Avoid memory-cache in new projects—it hasn’t been maintained since 2018 and lacks size limits, which can lead to memory leaks in long-running applications. Only consider it for throwaway scripts where simplicity outweighs reliability concerns.
Choose node-persist only when you need to persist data to disk across process restarts—such as saving CLI tool state or caching infrequently changing configuration. Never use it as a performance cache; its disk I/O makes it much slower than in-memory alternatives.
A cache object that deletes the least-recently-used items.
Specify a max number of the most recently used items that you want to keep, and this cache will keep that many of the most recently accessed items.
This is not primarily a TTL cache, and does not make strong TTL
guarantees. There is no preemptive pruning of expired items by
default, but you may set a TTL on the cache or on a single
set. If you do so, it will treat expired items as missing, and
delete them when fetched. If you are more interested in TTL
caching than LRU caching, check out
@isaacs/ttlcache.
As of version 7, this is one of the most performant LRU implementations available in JavaScript, and supports a wide diversity of use cases. However, note that using some of the features will necessarily impact performance, by causing the cache to have to do more work. See the "Performance" section below.
npm install lru-cache --save
// hybrid module, either works
import { LRUCache } from 'lru-cache'
// or:
const { LRUCache } = require('lru-cache')
// or in minified form for web browsers:
import { LRUCache } from 'http://unpkg.com/lru-cache@9/dist/mjs/index.min.mjs'
// At least one of 'max', 'ttl', or 'maxSize' is required, to prevent
// unsafe unbounded storage.
//
// In most cases, it's best to specify a max for performance, so all
// the required memory allocation is done up-front.
//
// All the other options are optional, see the sections below for
// documentation on what each one does. Most of them can be
// overridden for specific items in get()/set()
const options = {
max: 500,
// for use with tracking overall storage size
maxSize: 5000,
sizeCalculation: (value, key) => {
return 1
},
// for use when you need to clean up something when objects
// are evicted from the cache
dispose: (value, key, reason) => {
freeFromMemoryOrWhatever(value)
},
// for use when you need to know that an item is being inserted
// note that this does NOT allow you to prevent the insertion,
// it just allows you to know about it.
onInsert: (value, key, reason) => {
logInsertionOrWhatever(key, value)
},
// how long to live in ms
ttl: 1000 * 60 * 5,
// return stale items before removing from cache?
allowStale: false,
updateAgeOnGet: false,
updateAgeOnHas: false,
// async method to use for cache.fetch(), for
// stale-while-revalidate type of behavior
fetchMethod: async (key, staleValue, { options, signal, context }) => {},
}
const cache = new LRUCache(options)
cache.set('key', 'value')
cache.get('key') // "value"
// non-string keys ARE fully supported
// but note that it must be THE SAME object, not
// just a JSON-equivalent object.
var someObject = { a: 1 }
cache.set(someObject, 'a value')
// Object keys are not toString()-ed
cache.set('[object Object]', 'a different value')
assert.equal(cache.get(someObject), 'a value')
// A similar object with same keys/values won't work,
// because it's a different object identity
assert.equal(cache.get({ a: 1 }), undefined)
cache.clear() // empty the cache
If you put more stuff in the cache, then less recently used items will fall out. That's what an LRU cache is.
For full description of the API and all options, please see the LRUCache typedocs
This implementation aims to be as flexible as possible, within the limits of safe memory consumption and optimal performance.
At initial object creation, storage is allocated for max items.
If max is set to zero, then some performance is lost, and item
count is unbounded. Either maxSize or ttl must be set if
max is not specified.
If maxSize is set, then this creates a safe limit on the
maximum storage consumed, but without the performance benefits of
pre-allocation. When maxSize is set, every item must provide
a size, either via the sizeCalculation method provided to the
constructor, or via a size or sizeCalculation option provided
to cache.set(). The size of every item must be a positive
integer.
If neither max nor maxSize are set, then ttl tracking must
be enabled. Note that, even when tracking item ttl, items are
not preemptively deleted when they become stale, unless
ttlAutopurge is enabled. Instead, they are only purged the
next time the key is requested. Thus, if ttlAutopurge, max,
and maxSize are all not set, then the cache will potentially
grow unbounded.
In this case, a warning is printed to standard error. Future
versions may require the use of ttlAutopurge if max and
maxSize are not specified.
If you truly wish to use a cache that is bound only by TTL
expiration, consider using a Map object, and calling
setTimeout to delete entries when they expire. It will perform
much better than an LRU cache.
Here is an implementation you may use, under the same license as this package:
// a storage-unbounded ttl cache that is not an lru-cache
const cache = {
data: new Map(),
timers: new Map(),
set: (k, v, ttl) => {
if (cache.timers.has(k)) {
clearTimeout(cache.timers.get(k))
}
cache.timers.set(
k,
setTimeout(() => cache.delete(k), ttl),
)
cache.data.set(k, v)
},
get: k => cache.data.get(k),
has: k => cache.data.has(k),
delete: k => {
if (cache.timers.has(k)) {
clearTimeout(cache.timers.get(k))
}
cache.timers.delete(k)
return cache.data.delete(k)
},
clear: () => {
cache.data.clear()
for (const v of cache.timers.values()) {
clearTimeout(v)
}
cache.timers.clear()
},
}
If that isn't to your liking, check out @isaacs/ttlcache.
This cache never stores undefined values, as undefined is used
internally in a few places to indicate that a key is not in the
cache.
You may call cache.set(key, undefined), but this is just
an alias for cache.delete(key). Note that this has the effect
that cache.has(key) will return false after setting it to
undefined.
cache.set(myKey, undefined)
cache.has(myKey) // false!
If you need to track undefined values, and still note that the
key is in the cache, an easy workaround is to use a sigil object
of your own.
import { LRUCache } from 'lru-cache'
const undefinedValue = Symbol('undefined')
const cache = new LRUCache(...)
const mySet = (key, value) =>
cache.set(key, value === undefined ? undefinedValue : value)
const myGet = (key, value) => {
const v = cache.get(key)
return v === undefinedValue ? undefined : v
}
As of January 2022, version 7 of this library is one of the most performant LRU cache implementations in JavaScript.
Benchmarks can be extremely difficult to get right. In particular, the performance of set/get/delete operations on objects will vary wildly depending on the type of key used. V8 is highly optimized for objects with keys that are short strings, especially integer numeric strings. Thus any benchmark which tests solely using numbers as keys will tend to find that an object-based approach performs the best.
Note that coercing anything to strings to use as object keys is unsafe, unless you can be 100% certain that no other type of value will be used. For example:
const myCache = {}
const set = (k, v) => (myCache[k] = v)
const get = k => myCache[k]
set({}, 'please hang onto this for me')
set('[object Object]', 'oopsie')
Also beware of "Just So" stories regarding performance. Garbage collection of large (especially: deep) object graphs can be incredibly costly, with several "tipping points" where it increases exponentially. As a result, putting that off until later can make it much worse, and less predictable. If a library performs well, but only in a scenario where the object graph is kept shallow, then that won't help you if you are using large objects as keys.
In general, when attempting to use a library to improve performance (such as a cache like this one), it's best to choose an option that will perform well in the sorts of scenarios where you'll actually use it.
This library is optimized for repeated gets and minimizing eviction time, since that is the expected need of a LRU. Set operations are somewhat slower on average than a few other options, in part because of that optimization. It is assumed that you'll be caching some costly operation, ideally as rarely as possible, so optimizing set over get would be unwise.
If performance matters to you:
If it's at all possible to use small integer values as keys, and you can guarantee that no other types of values will be used as keys, then do that, and use a cache such as lru-fast, or mnemonist's LRUCache which uses an Object as its data store.
Failing that, if at all possible, use short non-numeric strings (ie, less than 256 characters) as your keys, and use mnemonist's LRUCache.
If the types of your keys will be anything else, especially long strings, strings that look like floats, objects, or some mix of types, or if you aren't sure, then this library will work well for you.
If you do not need the features that this library provides (like asynchronous fetching, a variety of TTL staleness options, and so on), then mnemonist's LRUMap is a very good option, and just slightly faster than this module (since it does considerably less).
Do not use a dispose function, size tracking, or especially
ttl behavior, unless absolutely needed. These features are
convenient, and necessary in some use cases, and every attempt
has been made to make the performance impact minimal, but it
isn't nothing.
This library changed to a different algorithm and internal data structure in version 7, yielding significantly better performance, albeit with some subtle changes as a result.
If you were relying on the internals of LRUCache in version 6 or before, it probably will not work in version 7 and above.
fetchContext option was renamed to context, and may no
longer be set on the cache instance itself.null or undefined.'lru-cache/min', for both CJS
and MJS builds.cache.fetch() return type is now Promise<V | undefined>
instead of Promise<V | void>. This is an irrelevant change
practically speaking, but can require changes for TypeScript
users.For more info, see the change log.