lru-cache vs cacheable-request vs node-cache vs cache-manager vs memory-cache vs apicache
Node.js 缓存方案深度对比:从内存存储到 HTTP 中间件
lru-cachecacheable-requestnode-cachecache-managermemory-cacheapicache类似的npm包:

Node.js 缓存方案深度对比:从内存存储到 HTTP 中间件

apicache、cache-manager、cacheable-request、lru-cache、memory-cache 和 node-cache 都是 Node.js 生态中流行的缓存工具,但它们的定位和适用场景截然不同。lru-cache 是底层的 LRU 算法实现,适合高性能数据结构缓存;node-cache 和 memory-cache 提供了更友好的内存键值存储 API;cache-manager 是一个统一的缓存接口,支持多种存储后端(如 Redis、内存);apicache 和 cacheable-request 则专注于 HTTP 层面的缓存,前者是 Express/Koa 中间件,后者是基于请求的缓存包装器。选择哪个包取决于你需要缓存的是数据对象、HTTP 响应,还是需要跨进程共享存储。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
lru-cache818,477,0765,9203.33 MB222 个月前BlueOak-1.0.0
cacheable-request47,505,8102,01379.3 kB36 个月前MIT
node-cache6,529,7042,373-776 年前MIT
cache-manager6,123,1642,01348.7 kB35 个月前MIT
memory-cache710,9541,590-339 年前BSD-2-Clause
apicache67,2361,248-635 年前MIT

Node.js 缓存方案深度对比:从内存存储到 HTTP 中间件

在 Node.js 后端开发中,缓存是提升性能的关键手段。然而,npm 上众多的缓存包往往让人困惑:lru-cache 和 node-cache 有什么区别?apicache 能替代 cache-manager 吗?本文将从架构设计、API 体验和适用场景三个维度,深入剖析这六个主流缓存库,帮助你做出正确的技术选型。

🏗️ 核心定位:底层算法 vs 应用层封装

这六个包可以分为三类:底层数据结构、内存存储封装、HTTP 缓存中间件。

lru-cache 是最底层的实现,专注于 LRU(最近最少使用)算法本身。

  • 它没有内置的定时清理机制(旧版本),只负责在达到上限时剔除旧数据。
  • 适合对性能极其敏感的场景,如配置读取、函数结果记忆化。
// lru-cache: 基础用法 (v7+)
import { LRUCache } from 'lru-cache';

const cache = new LRUCache({ max: 500 });
cache.set('key', 'value');
const value = cache.get('key');

node-cache 和 memory-cache 是在内存存储之上的友好封装。

  • 它们内置了 TTL(生存时间)管理和定时清理。
  • node-cache 提供更多事件钩子(如 del, expired),memory-cache 则更轻量。
// node-cache: 带 TTL 的内存缓存
import NodeCache from 'node-cache';

const cache = new NodeCache({ stdTTL: 100 });
cache.set('key', 'value');
// memory-cache: 极简内存缓存
import memoryCache from 'memory-cache';

memoryCache.put('key', 'value', 1000 * 60); // 单位毫秒
const value = memoryCache.get('key');

cache-manager 是一个抽象层,旨在统一不同存储后端。

  • 它可以轻松切换内存、Redis、MongoDB 等,支持多级缓存。
  • 适合需要灵活切换存储策略的大型项目。
// cache-manager: 统一接口
import cacheManager from 'cache-manager';

const cache = await cacheManager.caching({ store: 'memory', max: 100 });
await cache.set('key', 'value');
const value = await cache.get('key');

apicache 和 cacheable-request 专注于 HTTP 层面。

  • apicache 是 Express/Koa 中间件,直接缓存响应。
  • cacheable-request 包装 HTTP 客户端,缓存请求结果。
// apicache: Express 中间件
import apicache from 'apicache';

app.get('/api/data', apicache.middleware('10 minutes'), (req, res) => {
  res.json({ data: 'cached' });
});
// cacheable-request: 包装 HTTP 请求
import CacheableRequest from 'cacheable-request';

const cacheableRequest = new CacheableRequest('http://api.example.com/data');
cacheableRequest.on('response', (response) => {
  console.log('Status:', response.statusCode);
});

⏱️ 过期策略:自动清理 vs 手动管理

缓存过期(TTL)是核心功能,各包实现方式差异巨大。

node-cache 提供全局和单个键的 TTL 设置,并自动后台清理。

  • 开发者无需关心清理逻辑,适合通用数据缓存。
// node-cache: 灵活 TTL
const cache = new NodeCache();
cache.set('key1', 'val', 10); // 10 秒
cache.set('key2', 'val'); // 使用默认 TTL

memory-cache 在 put 方法中直接指定毫秒数。

  • 简单直接,但缺乏全局默认配置。
// memory-cache: 毫秒级 TTL
memoryCache.put('key', 'val', 5000); // 5 秒

lru-cache 在 v7+ 版本中引入了 ttl 选项,但行为更严格。

  • 它不会主动后台清理,而是在 get 或 set 时检查过期。
  • 性能更高,但可能占用内存直到被访问。
// lru-cache: 按需检查过期
const cache = new LRUCache({ ttl: 10000, ttlAutopurge: false });
cache.set('key', 'val');
// 过期后 get 返回 undefined

cache-manager 依赖具体存储实现的 TTL 机制。

  • 内存模式下类似 node-cache,Redis 模式下依赖 Redis 过期。
// cache-manager: 透传 TTL
await cache.set('key', 'val', { ttl: 10000 });

apicache 基于时间字符串解析。

  • 对开发者非常友好,直接写 '10 minutes'。
// apicache: 自然语言时间
apicache.middleware('5 minutes');
apicache.middleware('1 hour');

cacheable-request 遵循 HTTP 缓存头。

  • 它尊重 Cache-Control 和 Expires,适合代理缓存。
// cacheable-request: 遵循 HTTP 头
// 自动解析响应头中的 max-age

🔄 存储后端:单内存 vs 多存储支持

这是选择 cache-manager 与其他包的关键分水岭。

lru-cache, node-cache, memory-cache 仅限进程内内存。

  • 重启即丢失,多实例间不共享。
  • 适合无状态服务的本地热点数据。
// 三者均仅限内存
// 无法直接配置 Redis

cache-manager 支持插件化存储。

  • 可以配置 redis、memory、mongodb 等。
  • 支持 multi-caching(同时写内存和 Redis)。
// cache-manager: 多存储配置
const redisCache = await cacheManager.caching({ store: 'redis', host: 'localhost' });
const memoryCache = await cacheManager.caching({ store: 'memory' });
const multiCache = cacheManager.multiCaching([memoryCache, redisCache]);

apicache 默认内存,但支持自定义存储组。

  • 可以集成 Redis,但配置较复杂。
// apicache: 自定义存储
apicache.options({ redisClient: redisClient });

cacheable-request 使用 Keyv 作为底层存储。

  • 支持多种适配器,但主要用于请求缓存。
// cacheable-request: 基于 Keyv
const cacheableRequest = new CacheableRequest(request, { cache: new KeyvRedis('redis://localhost') });

🎯 事件与钩子:可观测性对比

在复杂系统中,知道缓存何时命中、失效非常重要。

node-cache 提供丰富的事件系统。

  • 支持 set, del, expired, flush 等事件。
  • 适合需要审计或日志记录的场景。
// node-cache: 事件监听
cache.on('expired', (key, value) => {
  console.log(`Key ${key} expired`);
});

cache-manager 支持包装器模式添加钩子。

  • 需要额外代码实现事件监听。
// cache-manager: 需自定义包装
// 无内置事件发射器,需自行封装

lru-cache v7+ 支持 fetchMethod 和基础事件。

  • 主要用于异步数据填充,而非审计。
// lru-cache: 异步获取
const cache = new LRUCache({
  fetchMethod: async (key) => fetchData(key)
});

memory-cache, apicache, cacheable-request 事件支持较弱。

  • 主要关注功能实现,而非可观测性。
// memory-cache: 无内置事件
// apicache: 仅提供简单的中间件日志

🛑 维护状态与风险提示

在选择库时,维护状态至关重要。

apicache 目前维护频率较低。

  • 虽然稳定,但新特性添加缓慢。
  • 建议在新项目中评估是否直接用 cache-manager 中间件替代。
// 风险提示:apicache 更新较慢
// 考虑替代方案

memory-cache 功能简单,长期未大改。

  • 适合小工具,但不建议用于核心业务缓存。
// 风险提示:功能有限
// 仅适合简单场景

lru-cache, node-cache, cache-manager 维护活跃。

  • 社区支持好,文档完善。
  • 是生产环境的安全选择。
// 推荐:维护活跃
// 适合生产环境

📊 总结对比表

特性lru-cachenode-cachememory-cachecache-managerapicachecacheable-request
定位底层算法内存缓存库简易内存缓存缓存抽象层HTTP 中间件HTTP 请求缓存
存储内存内存内存多后端 (Redis 等)内存/Redis内存/适配器
TTL 管理访问时检查自动后台清理自动后台清理依赖后端时间字符串HTTP 头
API 风格Class/MapEvent EmitterStatic MethodsPromise/CallbackMiddlewareStream/Event
适用场景高性能数据结构通用数据缓存简单临时缓存企业级架构API 响应缓存外部 API 调用

💡 架构师建议

1. 纯内存数据缓存:首选 node-cache。它在功能丰富度和易用性之间取得了最佳平衡,事件系统对调试非常有帮助。如果追求极致性能且能处理过期逻辑,选 lru-cache。

2. 需要 Redis 或分布式:直接使用 cache-manager 配合 Redis 存储,或者直接使用该 Redis 客户端(如 ioredis),避免过度封装带来的性能损耗。

3. HTTP 响应缓存:如果是 Express/Koa 项目,apicache 可以快速落地,但长期看建议基于 cache-manager 编写自定义中间件以获得更多控制权。

4. 调用第三方 API:cacheable-request 是最佳选择,它能正确处理 HTTP 缓存语义,避免重复请求。

最终结论:没有银弹。对于大多数 Node.js 应用,node-cache 足以解决 80% 的内存缓存需求;当需要扩展性或标准化时,cache-manager 是架构演进的方向;而 HTTP 层面的缓存应交给专门的中间件或请求库处理。

如何选择: lru-cache vs cacheable-request vs node-cache vs cache-manager vs memory-cache vs apicache

  • lru-cache:

    如果你追求极致的性能,且只需要在单进程内存中缓存键值对,选择 lru-cache。它是许多其他缓存库的底层依赖,API 简洁高效,但缺乏内置的 TTL 过期清理机制(需配合外部逻辑或新版 API)。

  • cacheable-request:

    如果你主要需要缓存对外部 HTTP API 的请求结果(例如调用第三方服务),选择 cacheable-request。它基于 HTTP 缓存规范(RFC 7234),能智能处理过期和验证,但不适合缓存内部应用数据。

  • node-cache:

    如果你需要一个功能丰富的纯内存缓存库,支持 TTL、事件回调和键管理,选择 node-cache。它比 memory-cache 更健壮,适合单节点应用的数据缓存,但不支持分布式存储。

  • cache-manager:

    如果你需要统一的缓存接口,并且未来可能从内存切换到 Redis 或其他存储,选择 cache-manager。它支持多存储组合(multi-caching),适合企业级应用,但配置相对繁琐,且对纯内存场景略显厚重。

  • memory-cache:

    如果你需要一个极其简单、零配置的内存缓存,且项目规模较小,选择 memory-cache。它的 API 非常直观,但功能相对基础,缺乏高级特性如事件钩子或持久化,不适合复杂生产环境。

  • apicache:

    如果你正在使用 Express 或 Koa 构建 API,并且希望以最小的代码量实现 HTTP 响应缓存,选择 apicache。它作为中间件运行,自动处理 ETag 和 Cache-Control 头。但需注意其维护频率较低,复杂场景下可能不如自定义中间件灵活。

lru-cache的README

lru-cache

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.

Installation

npm install lru-cache --save

Usage

// 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

Storage Bounds Safety

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.

Storing Undefined Values

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
}

Tracing and Observability

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.

Platform Compatibility Caveat

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.

Performance

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:

  1. 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.

  2. 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.

  3. 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).

  4. 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.

Testing

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

Breaking Changes in Version 7

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.

Breaking Changes in Version 8

  • The fetchContext option was renamed to context, and may no longer be set on the cache instance itself.
  • Rewritten in TypeScript, so pretty much all the types moved around a lot.
  • The AbortController/AbortSignal polyfill was removed. For this reason, Node version 16.14.0 or higher is now required.
  • Internal properties were moved to actual private class properties.
  • Keys and values must not be null or undefined.
  • Minified export available at 'lru-cache/min', for both CJS and MJS builds.

Breaking Changes in Version 9

  • Named export only, no default export.
  • AbortController polyfill returned, albeit with a warning when used.

Breaking Changes in Version 10

  • 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.