这些库提供了不同层次的缓存解决方案。lru-cache 和 quick-lru 是基础的内存键值存储;cache-manager 是支持多种后端(如 Redis、内存)的统一接口层;cacheable-request 专门用于自动缓存 HTTP 请求响应;而 memory-cache 已停止维护。它们共同解决了数据重复获取、降低延迟和减轻服务器负载的问题。
在 Node.js 开发中,缓存是提升性能的关键手段。但面对 cache-manager、lru-cache、quick-lru 等多个选项,开发者往往难以抉择。本文将从架构设计、API 用法、过期策略和维护状态四个维度,深入分析这五个库的差异,帮助你在实际工程中做出正确选择。
这五个包并非都在解决同一个问题。理解它们的定位是选型的第一步。
lru-cache 是标准的内存键值存储。它专注于在内存中保存数据,并根据最近最少使用(LRU)原则淘汰旧数据。它是其他许多缓存库的底层依赖。
// lru-cache: 标准内存 KV 存储
const { LRUCache } = require('lru-cache');
const cache = new LRUCache({ max: 500 });
cache.set('key', 'value');
const val = cache.get('key');
quick-lru 同样是内存键值存储,但追求极致轻量。它去除了复杂功能,只保留核心的 LRU 淘汰逻辑。
// quick-lru: 轻量级内存 KV 存储
const QuickLRU = require('quick-lru');
const lru = new QuickLRU({ maxSize: 500 });
lru.set('key', 'value');
const val = lru.get('key');
memory-cache 也是内存键值存储,但设计较旧。它曾流行一时,但现在已不再推荐。
// memory-cache: 旧式内存 KV 存储
const cache = require('memory-cache');
cache.put('key', 'value', 5000);
const val = cache.get('key');
cache-manager 不是存储引擎,而是包装层。它统一了不同存储(内存、Redis、文件系统)的接口,让你可以轻松切换后端。
// cache-manager: 多存储统一接口
const cacheManager = require('cache-manager');
const cache = await cacheManager.caching({ store: 'memory', max: 100 });
await cache.set('key', 'value');
const val = await cache.get('key');
cacheable-request 专用于 HTTP 请求缓存。它包装了 HTTP 客户端,自动根据响应头缓存 GET 请求,无需手动管理键值。
// cacheable-request: HTTP 请求自动缓存
const CacheableRequest = require('cacheable-request');
const cr = new CacheableRequest(require('http'));
const req = cr.get('http://example.com/api');
// 响应内容会自动被缓存
数据过期(TTL)是缓存的核心功能之一。不同库对此的支持程度差异巨大。
lru-cache 提供完善的 TTL 支持。你可以为每个条目设置存活时间,过期后自动失效。
// lru-cache: 支持 TTL
const cache = new LRUCache({ ttl: 1000 * 60 * 5 }); // 5 分钟
cache.set('key', 'value'); // 自动应用 TTL
cache-manager 也支持 TTL,并通过统一接口传递给底层存储。
// cache-manager: 支持 TTL
await cache.set('key', 'value', { ttl: 300 }); // 300 秒
memory-cache 支持过期时间,但 API 较旧,需要在 put 时指定毫秒数。
// memory-cache: 支持过期时间
cache.put('key', 'value', 5000); // 5000 毫秒
quick-lru 不支持原生 TTL。它仅基于大小淘汰。如果需要过期功能,需自行实现或使用其他库。
// quick-lru: 无原生 TTL
const lru = new QuickLRU({ maxSize: 500 });
// 无法直接设置过期时间,需外部管理
cacheable-request 依赖 HTTP 响应头(如 Cache-Control)来决定过期。它遵循 Web 标准,而非手动配置时间。
// cacheable-request: 依赖 HTTP 头
// 服务器返回 Cache-Control: max-age=3600
// 库会自动缓存 1 小时,无需代码设置
现代 Node.js 开发倾向于异步 API,但部分库仍保留同步风格。
lru-cache (v7+) 主要使用同步 API,因为内存操作极快,无需异步开销。
// lru-cache: 同步操作
const val = cache.get('key'); // 直接返回值
quick-lru 同样是同步 API,追求极致性能。
// quick-lru: 同步操作
const val = lru.get('key'); // 直接返回值
memory-cache 也是同步 API。
// memory-cache: 同步操作
const val = cache.get('key'); // 直接返回值
cache-manager (v5+) 全面转向异步 API,以支持 Redis 等网络存储。
// cache-manager: 异步操作
const val = await cache.get('key'); // 返回 Promise
cacheable-request 基于事件发射器或 Promise,取决于底层 HTTP 客户端。
// cacheable-request: 异步流或 Promise
const response = await cr.get('http://example.com');
选型时,库的活跃度直接关系到生产安全。
lru-cache 由 Node.js 核心贡献者维护,更新频繁,是行业标准。
quick-lru 由知名开发者 Sindre Sorhus 维护,稳定可靠,适合轻量场景。
cache-manager 社区活跃,支持多种插件,适合企业级应用。
cacheable-request 维护正常,但需注意与 got 等客户端的版本兼容性。
memory-cache 已停止维护。最后更新停留在数年前,存在未修复的 Bug 风险。新项目应避免使用。
// memory-cache: 已弃用
// 不建议在新代码中 import 此包
const cache = require('memory-cache');
| 特性 | lru-cache | quick-lru | cache-manager | cacheable-request | memory-cache |
|---|---|---|---|---|---|
| 类型 | 内存 KV | 内存 KV | 存储包装层 | HTTP 缓存 | 内存 KV |
| TTL 支持 | ✅ 原生支持 | ❌ 不支持 | ✅ 支持 | ✅ 依赖 HTTP 头 | ✅ 支持 |
| API 风格 | 同步 | 同步 | 异步 | 异步 | 同步 |
| 维护状态 | ✅ 活跃 | ✅ 活跃 | ✅ 活跃 | ✅ 活跃 | ❌ 停止维护 |
| 适用场景 | 通用缓存 | 轻量缓存 | 多后端切换 | API 请求缓存 | 旧项目维护 |
首选 lru-cache:如果你需要在内存中缓存数据且需要 TTL 功能,这是最稳妥的选择。它功能全面且性能优秀。
选 quick-lru:如果你只需要简单的基于大小的淘汰策略,且希望依赖尽可能少,它是一个干净的替代方案。
选 cache-manager:如果你希望未来可能从内存切换到 Redis,或者需要统一多个缓存后端,使用它来解耦代码。
选 cacheable-request:如果你主要想缓存 HTTP GET 请求,不要手动实现,直接用这个库处理响应头逻辑。
避开 memory-cache:除非你在维护旧代码,否则不要在新项目中使用。它的功能已被 lru-cache 完全覆盖且更安全。
缓存选型没有绝对的最佳,只有最适合场景的方案。理解数据流向和过期需求,才能构建高效的缓存层。
适合需要统一接口切换不同存储后端(如从内存切换到 Redis)的场景。它提供了包装层,适合大型项目需要灵活配置缓存策略的情况。如果你希望代码不依赖具体存储实现,选它。
适合需要自动缓存 HTTP GET 请求响应的场景。如果你主要想减少网络请求次数而不想手动管理键值,这是最佳选择。它通常与 got 或原生 http 模块配合使用。
适合需要标准、功能丰富(支持 TTL、最大尺寸)的内存缓存场景。它是 Node.js 生态中最成熟的选择,适合大多数通用缓存需求。如果你需要时间过期策略,选它。
不建议在新项目中使用。该库已多年未更新,存在潜在风险。请改用 lru-cache 或 quick-lru 替代。仅在维护旧代码时可能会遇到它。
适合需要极简、高性能且仅需基于大小淘汰策略的场景。如果你不需要 TTL 等复杂功能,它的依赖更少且速度更快。适合对体积敏感的轻量级工具。
A cache module for NodeJS that allows easy wrapping of functions in cache, tiered caches, and a consistent interface.
nonBlocking option that optimizes how the system handles multiple stores.We moved to using Keyv which are more actively maintained and have a larger community.
A special thanks to Tim Phan who took cache-manager v5 and ported it to Keyv which is the foundation of v6. 🎉 Another special thanks to Doug Ayers who wrote promise-coalesce which was used in v5 and now embedded in v6.
v7 has only one breaking change which is changing the return type from null to undefined when there is no data to return. This is to align with the Keyv API and to make it more consistent with the rest of the methods. Below is an example of how to migrate from v6 to v7:
import { createCache } from 'cache-manager';
const cache = createCache();
const result = await cache.get('key');
// result will be undefined if the key is not found or expired
console.log(result); // undefined
v6 is a major update and has breaking changes primarily around the storage adapters. We have moved to using Keyv which are more actively maintained and have a larger community. Below are the changes you need to make to migrate from v5 to v6. In v5 the memoryStore was used to create a memory store, in v6 you can use any storage adapter that Keyv supports. Below is an example of how to migrate from v5 to v6:
import { createCache, memoryStore } from 'cache-manager';
// Create memory cache synchronously
const memoryCache = createCache(memoryStore({
max: 100,
ttl: 10 * 1000 /*milliseconds*/,
}));
In v6 you can use any storage adapter that Keyv supports. Below is an example of using the in memory store with Keyv:
import { createCache } from 'cache-manager';
const cache = createCache();
If you would like to do multiple stores you can do the following:
import { createCache } from 'cache-manager';
import { createKeyv } from 'cacheable';
import { createKeyv as createKeyvRedis } from '@keyv/redis';
const memoryStore = createKeyv();
const redisStore = createKeyvRedis('redis://user:pass@localhost:6379');
const cache = createCache({
stores: [memoryStore, redisStore],
});
When doing in memory caching and getting errors on symbol or if the object is coming back wrong like on Uint8Array you will want to set the serialization and deserialization options in Keyv to undefined as it will try to do json serialization.
import { createCache } from "cache-manager";
import { Keyv } from "keyv";
const keyv = new Keyv();
keyv.serialize = undefined;
keyv.deserialize = undefined;
const memoryCache = createCache({
stores: [keyv],
});
The other option is to set the serialization to something that is not JSON.stringify. You can read more about it here: https://keyv.org/docs/keyv/#custom-serializers
If you would like a more robust in memory storage adapter you can use CacheableMemory from Cacheable. Below is an example of how to migrate from v5 to v6 using CacheableMemory:
import { createCache } from 'cache-manager';
import { createKeyv } from 'cacheable';
const cache = createCache({
stores: [createKeyv({ ttl: 60000, lruSize: 5000 })],
});
To learn more about CacheableMemory please visit: http://cacheable.org/docs/cacheable/#cacheablememory---in-memory-cache
If you are still wanting to use the legacy storage adapters you can use the KeyvAdapter to wrap the storage adapter. Below is an example of how to migrate from v5 to v6 using cache-manager-redis-yet by going to Using Legacy Storage Adapters.
If you are looking for older documentation you can find it here:
CacheableMemory or lru-cache as storage adapterredis and ioredis Supportnpm install cache-manager
By default, everything is stored in memory; you can optionally also install a storage adapter; choose one from any of the storage adapters supported by Keyv:
npm install @keyv/redis
npm install @keyv/memcache
npm install @keyv/mongo
npm install @keyv/sqlite
npm install @keyv/postgres
npm install @keyv/mysql
npm install @keyv/etcd
In addition Keyv supports other storage adapters such as lru-cache and CacheableMemory from Cacheable (more examples below). Please read Keyv document for more information.
import { Keyv } from 'keyv';
import { createCache } from 'cache-manager';
// Memory store by default
const cache = createCache()
// Single store which is in memory
const cache = createCache({
stores: [new Keyv()],
})
Here is an example of doing layer 1 and layer 2 caching with the in-memory being CacheableMemory from Cacheable and the second layer being @keyv/redis:
import { Keyv } from 'keyv';
import KeyvRedis from '@keyv/redis';
import { CacheableMemory } from 'cacheable';
import { createCache } from 'cache-manager';
// Multiple stores
const cache = createCache({
stores: [
// High performance in-memory cache with LRU and TTL
new Keyv({
store: new CacheableMemory({ ttl: 60000, lruSize: 5000 }),
}),
// Redis Store
new Keyv({
store: new KeyvRedis('redis://user:pass@localhost:6379'),
}),
],
})
Once it is created, you can use the cache object to set, get, delete, and wrap functions in cache.
// With default ttl and refreshThreshold
const cache = createCache({
ttl: 10000,
refreshThreshold: 3000,
})
await cache.set('foo', 'bar')
// => bar
await cache.get('foo')
// => bar
await cache.del('foo')
// => true
await cache.get('foo')
// => null
await cache.wrap('key', () => 'value')
// => value
Because we are using Keyv, you can use any storage adapter that Keyv supports such as lru-cache or CacheableMemory from Cacheable. Below is an example of using CacheableMemory:
In this example we are using CacheableMemory from Cacheable which is a fast in-memory cache that supports LRU and and TTL expiration.
import { createCache } from 'cache-manager';
import { Keyv } from 'keyv';
import { KeyvCacheableMemory } from 'cacheable';
const store = new KeyvCacheableMemory({ ttl: 60000, lruSize: 5000 });
const keyv = new Keyv({ store });
const cache = createCache({ stores: [keyv] });
Here is an example using lru-cache:
import { createCache } from 'cache-manager';
import { Keyv } from 'keyv';
import { LRU } from 'lru-cache';
const keyv = new Keyv({ store: new LRU({ max: 5000, maxAge: 60000 }) });
const cache = createCache({ stores: [keyv] });
stores?: Keyv[]
List of Keyv instance. Please refer to the Keyv document for more information.
ttl?: number - Default time to live in milliseconds.
The time to live in milliseconds. This is the maximum amount of time that an item can be in the cache before it is removed.
refreshThreshold?: number | (value:T) => number - Default refreshThreshold in milliseconds. You can also provide a function that will return the refreshThreshold based on the value.
If the remaining TTL is less than refreshThreshold, the system will update the value asynchronously in background.
refreshAllStores?: boolean - Default false
If set to true, the system will update the value of all stores when the refreshThreshold is met. Otherwise, it will only update from the top to the store that triggered the refresh.
nonBlocking?: boolean - Default false
If set to true, the system will not block when multiple stores are used. Here is how it affects the type of functions:
set and mset - will not wait for all stores to finish.get and mget - will return the first (fastest) value found.del and mdel - will not wait for all stores to finish.clear - will not wait for all stores to finish.wrap - will do the same as get and set (return the first value found and not wait for all stores to finish).cacheId?: string - Defaults to random string
Unique identifier for the cache instance. This is primarily used to not have conflicts when using wrap with multiple cache instances.
set(key, value, [ttl]): Promise<value>
Sets a key value pair. It is possible to define a ttl (in milliseconds). An error will be throw on any failed
await cache.set('key-1', 'value 1')
// expires after 5 seconds
await cache.set('key 2', 'value 2', 5000)
See unit tests in test/set.test.ts for more information.
mset(keys: [ { key, value, ttl } ]): Promise<true>
Sets multiple key value pairs. It is possible to define a ttl (in milliseconds). An error will be throw on any failed
await cache.mset([
{ key: 'key-1', value: 'value 1' },
{ key: 'key-2', value: 'value 2', ttl: 5000 },
]);
get(key): Promise<value>
Gets a saved value from the cache. Returns a null if not found or expired. If the value was found it returns the value.
await cache.set('key', 'value')
await cache.get('key')
// => value
await cache.get('foo')
// => null
See unit tests in test/get.test.ts for more information.
mget(keys: [key]): Promise<value[]>
Gets multiple saved values from the cache. Returns a null if not found or expired. If the value was found it returns the value.
await cache.mset([
{ key: 'key-1', value: 'value 1' },
{ key: 'key-2', value: 'value 2' },
]);
await cache.mget(['key-1', 'key-2', 'key-3'])
// => ['value 1', 'value 2', null]
ttl(key): Promise<number | null>
Gets the expiration time of a key in milliseconds. Returns a null if not found or expired.
await cache.set('key', 'value', 1000); // expires after 1 second
await cache.ttl('key'); // => the expiration time in milliseconds
await cache.get('foo'); // => null
See unit tests in test/ttl.test.ts for more information.
del(key): Promise<true>
Delete a key, an error will be throw on any failed.
await cache.set('key', 'value')
await cache.get('key')
// => value
await cache.del('key')
await cache.get('key')
// => null
See unit tests in test/del.test.ts for more information.
mdel(keys: [key]): Promise<true>
Delete multiple keys, an error will be throw on any failed.
await cache.mset([
{ key: 'key-1', value: 'value 1' },
{ key: 'key-2', value: 'value 2' },
]);
await cache.mdel(['key-1', 'key-2'])
clear(): Promise<true>
Flush all data, an error will be throw on any failed.
await cache.set('key-1', 'value 1')
await cache.set('key-2', 'value 2')
await cache.get('key-1')
// => value 1
await cache.get('key-2')
// => value 2
await cache.clear()
await cache.get('key-1')
// => null
await cache.get('key-2')
// => null
See unit tests in test/clear.test.ts for more information.
wrap(key, fn: async () => value, [ttl], [refreshThreshold]): Promise<value>
Alternatively, with optional parameters as options object supporting a raw parameter:
wrap(key, fn: async () => value, { ttl?: number, refreshThreshold?: number, raw?: true }): Promise<value>
Wraps a function in cache. The first time the function is run, its results are stored in cache so subsequent calls retrieve from cache instead of calling the function.
If refreshThreshold is set and the remaining TTL is less than refreshThreshold, the system will update the value asynchronously. In the meantime, the system will return the old value until expiration. You can also provide a function that will return the refreshThreshold based on the value (value:T) => number.
If the object format for the optional parameters is used, an additional raw parameter can be applied, changing the function return type to raw data including expiration timestamp as { value: [data], expires: [timestamp] }.
await cache.wrap('key', () => 1, 5000, 3000)
// call function then save the result to cache
// => 1
await cache.wrap('key', () => 2, 5000, 3000)
// return data from cache, function will not be called again
// => 1
await cache.wrap('key', () => 2, { ttl: 5000, refreshThreshold: 3000, raw: true })
// returns raw data including expiration timestamp
// => { value: 1, expires: [timestamp] }
// wait 3 seconds
await sleep(3000)
await cache.wrap('key', () => 2, 5000, 3000)
// return data from cache, call function in background and save the result to cache
// => 1
await cache.wrap('key', () => 3, 5000, 3000)
// return data from cache, function will not be called
// => 2
await cache.wrap('key', () => 4, 5000, () => 3000);
// return data from cache, function will not be called
// => 4
await cache.wrap('error', () => {
throw new Error('failed')
})
// => error
NOTES:
ttl is set for the key, the refresh mechanism will not be triggered.See unit tests in test/wrap.test.ts for more information.
disconnect(): Promise<void>
Will disconnect from the relevant store(s). It is highly recommended to use this when using a Keyv storage adapter that requires a disconnect. For each storage adapter, the use case for when to use disconnect is different. An example is that @keyv/redis should be used only when you are done with the cache.
await cache.disconnect();
See unit tests in test/disconnect.test.ts for more information.
cacheId(): string
Returns cache instance id. This is primarily used to not have conflicts when using wrap with multiple cache instances.
stores(): Keyv[]
Returns the list of Keyv instances. This can be used to get the list of stores and then use the Keyv API to interact with the store directly.
const cache = createCache({cacheId: 'my-cache-id'});
cache.cacheId(); // => 'my-cache-id'
See unit tests in test/cache-id.test.ts for more information.
Fired when a key has been added or changed.
cache.on('set', ({ key, value, error }) => {
// ... do something ...
})
Fired when a key has been removed manually.
cache.on('del', ({ key, error }) => {
// ... do something ...
})
Fired when the cache has been flushed.
cache.on('clear', (error) => {
if (error) {
// ... do something ...
}
})
Fired when the cache has been refreshed in the background.
cache.on('refresh', ({ key, value, error }) => {
if (error) {
// ... do something ...
}
})
See unit tests in test/events.test.ts for more information.
You can use the stores method to get the list of stores and then use the Keyv API to interact with the store directly. Below is an example of iterating over all stores and getting all keys:
import Keyv from 'keyv';
import { createKeyv } from '@keyv/redis';
import { createCache } from 'cache-manager';
const keyv = new Keyv();
const keyvRedis = createKeyv('redis://user:pass@localhost:6379');
const cache = createCache({
stores: [keyv, keyvRedis],
});
// add some data
await cache.set('key-1', 'value 1');
await cache.set('key-2', 'value 2');
// get the store you want to iterate over. In this example we are using the second store (redis)
const store = cache.stores[1];
if(store?.iterator) {
for await (const [key, value] of store.iterator({})) {
console.log(key, value);
}
}
WARNING: Be careful when using iterator as it can cause major performance issues with the amount of data being retrieved. Also, Not all storage adapters support iterator so you may need to check the documentation for the storage adapter you are using.
We will not be supporting cache-manager-ioredis-yet or cache-manager-redis-yet in the future as we have moved to using Keyv as the storage adapter @keyv/redis.
There are many storage adapters built for cache-manager and because of that we wanted to provide a way to use them with KeyvAdapter. Below is an example of using cache-manager-redis-yet:
import { createCache, KeyvAdapter } from 'cache-manager';
import { Keyv } from 'keyv';
import { redisStore } from 'cache-manager-redis-yet';
const adapter = new KeyvAdapter( await redisStore() );
const keyv = new Keyv({ store: adapter });
const cache = createCache({ stores: [keyv]});
This adapter will allow you to add in any storage adapter. If there are issues it needs to follow CacheManagerStore interface.
If you would like to contribute to the project, please read how to contribute here CONTRIBUTING.md.