这些库专为 Node.js 环境设计,用于解决服务器端数据缓存问题。前端架构师在构建 BFF 层、SSR 服务或中间件时经常需要做出选择。lru-cache 提供底层的 LRU 算法实现,性能极高。node-cache 和 memory-cache 提供更易用的键值存储接口,支持过期时间。apicache 则是专门针对 Express 应用的 HTTP 响应缓存中间件。
在 Node.js 服务端开发中,缓存是提升响应速度的关键手段。前端架构师在搭建 BFF 层或 SSR 服务时,经常需要从 apicache、lru-cache、memory-cache 和 node-cache 中做出选择。这些工具虽然都用于内存缓存,但设计目标和适用场景截然不同。让我们从核心机制到实际代码进行深度剖析。
apicache 是专门为 Express 设计的中间件。
// apicache: Express 中间件用法
const apicache = require('apicache');
const app = require('express')();
// 缓存所有 GET 请求 60 秒
app.get('/api/users', apicache.middleware('60 seconds'), (req, res) => {
res.json({ data: 'user list' });
});
lru-cache 是纯粹的 LRU 算法实现。
// lru-cache: 底层算法用法
const { LRUCache } = require('lru-cache');
const cache = new LRUCache({
max: 100, // 最多存储 100 个项
ttl: 1000 * 60 // 可选:设置过期时间
});
cache.set('key', 'value');
const value = cache.get('key');
memory-cache 是简单的键值存储。
put 和 get 方法,支持手动设置过期时间。// memory-cache: 简单键值用法
const cache = require('memory-cache');
// 存储 10 秒
cache.put('key', 'value', 10 * 1000);
const value = cache.get('key');
node-cache 是功能丰富的通用缓存。
// node-cache: 通用缓存用法
const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 100 });
cache.set('key', 'value');
const value = cache.get('key');
缓存过期处理是区分这些库的关键点。
apicache 完全自动化。
// apicache: 声明式过期
app.get('/api/data', apicache.middleware('2 hours'), handler);
lru-cache 需要显式配置。
ttl 选项才支持过期。// lru-cache: 配置式过期
const cache = new LRUCache({
max: 500,
ttl: 1000 * 60 * 5 // 5 分钟过期
});
memory-cache 支持每次存储时指定。
put 操作都可以独立设置过期时间。// memory-cache: 独立过期时间
cache.put('short', 'data', 1000); // 1 秒
cache.put('long', 'data', 3600000); // 1 小时
node-cache 支持全局和局部设置。
set 时覆盖默认值。del 事件回调,方便清理副作用。// node-cache: 灵活过期
const cache = new NodeCache({ stdTTL: 60 });
cache.set('key', 'value', 120); // 覆盖为 120 秒
cache.on('del', (key, value) => {
console.log(`Key ${key} deleted`);
});
你需要为现有的 Express 接口快速添加缓存,不想修改业务逻辑。
apicache// 使用 apicache 包裹路由
router.get('/products', apicache.middleware('1 day'), getProductHandler);
你在 SSR 页面中缓存昂贵的计算结果,需要严格控制内存上限。
lru-cache// 使用 lru-cache 缓存渲染结果
const renderCache = new LRUCache({ max: 1000 });
if (renderCache.has(htmlKey)) {
return renderCache.get(htmlKey);
}
你需要存储用户临时令牌,不同令牌过期时间不同。
node-cache 或 memory-cache// 使用 node-cache 存储会话
sessionCache.set(userId, token, sessionDuration);
你正在做一个小型工具脚本,需要快速缓存一些 API 数据。
memory-cache// 使用 memory-cache 快速缓存
cache.put('api_result', data, 5000);
在选择库时,维护活跃度是关键考量因素。
lru-cache: 维护非常活跃,是行业标准。API 在 v7 后有重大变更,需注意版本兼容性。node-cache: 维护稳定,功能成熟,适合生产环境长期使用。apicache: 专注于 Express 生态,更新频率较低,但功能稳定。memory-cache: 相对简单,社区活跃度不如 node-cache。在新项目中建议评估 node-cache 作为替代。💡 提示:如果项目允许,优先考虑
lru-cache或node-cache。memory-cache虽然简单,但在长期维护的大型项目中可能缺乏足够的支持。
| 特性 | apicache | lru-cache | memory-cache | node-cache |
|---|---|---|---|---|
| 主要用途 | HTTP 响应缓存 | 底层数据结构 | 简单键值存储 | 通用内存缓存 |
| 框架依赖 | Express | 无 | 无 | 无 |
| LRU 淘汰 | ❌ | ✅ | ❌ | ❌ |
| TTL 支持 | ✅ (中间件配置) | ✅ (需配置) | ✅ (每次设置) | ✅ (全局 + 局部) |
| 事件回调 | ❌ | ❌ | ❌ | ✅ |
| 性能开销 | 中 (含解析) | 极低 | 低 | 低 |
apicache 是特定场景的专用工具 🎯。如果你的架构基于 Express 且主要痛点是 API 响应速度,它是捷径。但不要试图用它来处理业务逻辑数据缓存。
lru-cache 是高性能基石 🧱。适合构建自己的缓存系统或在内存敏感场景中使用。它需要更多代码来管理业务逻辑,但回报是极致的性能。
node-cache 是通用首选 🛡️。它在功能和易用性之间取得了最佳平衡。对于大多数 BFF 层和 SSR 服务,它是默认推荐选项。
memory-cache 是轻量级备选 🪶。适合小型脚本或临时需求。但在企业级项目中,建议优先评估 node-cache 以获得更好的长期支持。
最终思考:缓存选型不是越复杂越好。明确你的数据过期策略、内存限制和框架依赖,才能选出最适合的工具。
选择 lru-cache 如果你需要极致性能且理解最近最少使用(LRU)算法原理。它是底层基础库,适合构建高性能缓存系统或作为其他缓存库的核心依赖。适合对内存控制有严格要求的场景。
选择 node-cache 如果你需要支持过期时间(TTL)和事件回调的通用缓存方案。它在易用性和功能之间取得了平衡,适合大多数 Node.js 服务的内部数据缓存需求。
选择 memory-cache 如果你需要最简单的键值缓存且项目规模较小。它的 API 非常直观,适合快速原型开发。但在大型项目中,其功能丰富度和维护活跃度可能不如其他选项。
选择 apicache 如果你正在使用 Express 框架且主要需求是缓存 HTTP 响应。它作为中间件集成,无需手动管理键值,适合快速为 API 接口添加缓存层。但请注意它仅适用于 Express 环境,通用性较低。
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
}
Most methods can accept a status option, which is an
LRUCache.Status
object that will be decorated along the operation with
indications about what was done and why.
Additionally, this library is instrumented using the
node:diagnostics_channel
module on Node and other platforms that support it. In order to
get diagnostics metrics, listen on the
channel('lru-cache:metrics'). To get Tracing Channel traces,
subscribe to the tracingChannel('lru-cache'). The
LRUCache.Status
objects will be provided as the message context to those channel
listeners.
For example, you could do the following to get comprehensive information about every LRUCache instance in your application:
import { tracingChannel, subscribe } from 'node:diagnostics_channel'
subscribe('lru-cache:metrics', (message, name) => {
// name will always be 'lru-cache:metrics'
// message will be the LRUCache.Status object for whatever
// synchronous operation was performed.
console.error('LRUCache Metrics', message)
})
tracingChannel('lru-cache').subscribe({
start: status => {
// a traced operation is starting
},
asyncStart: status => {
// an async traced operation is starting
},
asyncEnd: status => {
// an async traced operation is ending
}
error: status => {
// a traced operation failed
},
end: status => {
// a traced operation is complete
},
})
The async cache.fetch() and cache.forceFetch methods are
covered by tracingChannels. All the other operations are
covered by the lru-cache:metrics channel, because they are
strictly synchronous, and thus don't have an asynchronous
lifecycle to track.
Note that using status objects or using
node:diagnostics_channel listeners will impose a modest
performance penalty. Creating data objects is not ever free; do
not believe anyone who tells you otherwise. But it is as small as
possible.
Not all platforms support the node:diagnostics_channel module.
Currently, this is only available in Node, Bun, and Deno, and
some edge computing platforms that provide a Node compatibility
layer.
To work around this, if you are loading in a non-Node
environment, the package.json exports will direct your module
loader to pull in a version that starts out with a dummy
implementation, then does a conditional dynamic import of the
node:diagnostics_channel module, and then swaps out those
dummy objects with the real thing if it succeeds. This means that
cache metrics and tracing channels started in the first load-time
tick of your application will not be covered, except in
environments that load using the require import
condition, or both the node and esm import conditions
together.
Top-level await could be used to remove this caveat, but that feature is dead on arrival, unfortunately. See #397 and #398 for more details.
As of April 2026, version 11 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 you can use short non-numeric strings (ie, less than 256 characters) as your keys, and you do not need any of the other features of this library, 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 also 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 or observability features, 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.
When writing tests that involve TTL-related functionality, note
that this module creates an internal reference to the global
performance or Date objects at import time. If you import it
statically at the top level, those references cannot be mocked or
overridden in your test environment.
To avoid this, dynamically import the package within your tests so that the references are captured after your mocks are applied. For example:
// ❌ Not recommended
import { LRUCache } from 'lru-cache'
// mocking timers, e.g. jest.useFakeTimers()
// ✅ Recommended for TTL tests
// mocking timers, e.g. jest.useFakeTimers()
const { LRUCache } = await import('lru-cache')
This ensures that your mocked timers or time sources are respected when testing TTL behavior.
Additionally, you can pass in a perf option when creating your
LRUCache instance. This option accepts any object with a now
method that returns a number.
For example, this would be a very bare-bones time-mocking system you could use in your tests, without any particular test framework:
import { LRUCache } from 'lru-cache'
let myClockTime = 0
const cache = new LRUCache<string>({
max: 10,
ttl: 1000,
perf: {
now: () => myClockTime,
},
})
// run tests, updating myClockTime as needed
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.