cache-manager vs apicache vs cacheable-request vs lru-cache vs memory-cache vs node-cache
Choosing the Right Caching Strategy for Node.js Applications
cache-managerapicachecacheable-requestlru-cachememory-cachenode-cacheSimilar Packages:

Choosing the Right Caching Strategy for Node.js Applications

These six packages offer different approaches to caching in Node.js environments, ranging from simple in-memory storage to HTTP-specific caching layers. lru-cache provides a fundamental Least Recently Used algorithm implementation, while node-cache and memory-cache offer straightforward in-memory key-value storage with TTL support. cache-manager acts as a wrapper allowing multiple cache stores (memory, Redis, etc.) with a unified API. apicache focuses specifically on Express middleware for caching HTTP responses, and cacheable-request adds HTTP caching semantics to request clients. Each serves distinct architectural needs from low-level data structures to high-level HTTP response caching.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
cache-manager3,195,9272,00748.7 kB02 months agoMIT
apicache46,7351,248-635 years agoMIT
cacheable-request02,00779.3 kB04 months agoMIT
lru-cache05,9152.74 MB32 months agoBlueOak-1.0.0
memory-cache01,594-329 years agoBSD-2-Clause
node-cache02,374-766 years agoMIT

Choosing the Right Caching Strategy for Node.js Applications

Caching is essential for building performant Node.js applications, but picking the wrong tool can lead to memory leaks, stale data, or unnecessary complexity. The six packages we are comparing — apicache, cache-manager, cacheable-request, lru-cache, memory-cache, and node-cache — each solve different parts of the caching puzzle. Some focus on HTTP responses, others on data structures, and some on abstraction layers. Let's break down how they work and when to use each one.

🏗️ Core Architecture: What Each Package Actually Does

lru-cache is a pure data structure implementation.

  • It provides a Least Recently Used eviction algorithm.
  • No built-in TTL (time-to-live) in older versions, though newer versions support it.
  • You manage the cache lifecycle yourself.
// lru-cache: Basic usage
import { LRUCache } from 'lru-cache';

const cache = new LRUCache({
  max: 500,
  ttl: 1000 * 60 * 5 // 5 minutes
});

cache.set('key', 'value');
const value = cache.get('key');

node-cache is a full in-memory cache with TTL and events.

  • Built on top of basic object storage with cleanup intervals.
  • Supports key patterns, cloning, and event hooks.
  • Runs entirely in process memory.
// node-cache: With TTL and events
import NodeCache from 'node-cache';

const cache = new NodeCache({ stdTTL: 100 });

cache.on('expired', (key, value) => {
  console.log(`Key ${key} expired`);
});

cache.set('key', 'value', 200);
const value = cache.get('key');

memory-cache is a minimal in-memory store.

  • Very simple API with basic TTL support.
  • No event system or advanced features.
  • Good for quick prototyping.
// memory-cache: Simple set/get
import cache from 'memory-cache';

cache.put('key', 'value', 1000 * 60); // 1 minute
const value = cache.get('key');
cache.del('key');

cache-manager is an abstraction layer over multiple stores.

  • Wraps different cache backends (memory, Redis, etc.) with one API.
  • Supports multi-caching (writing to multiple stores at once).
  • Allows swapping implementations without code changes.
// cache-manager: With memory store
import cacheManager from 'cache-manager';
import memoryStore from 'cache-manager-remember';

const cache = cacheManager.caching({
  store: memoryStore,
  ttl: 60,
  max: 100
});

await cache.set('key', 'value');
const value = await cache.get('key');

apicache is Express middleware for HTTP response caching.

  • Caches entire HTTP responses automatically.
  • Configurable by status code, URL, and TTL.
  • ⚠️ Deprecated: No longer actively maintained as of 2023.
// apicache: Express middleware
import apicache from 'apicache';
import express from 'express';

const app = express();
app.use(apicache.middleware);

app.get('/api/data', apicache.middleware('5 minutes'), (req, res) => {
  res.json({ data: 'cached response' });
});

cacheable-request adds HTTP caching to request clients.

  • Wraps HTTP clients to respect cache headers.
  • Stores responses based on HTTP semantics (ETag, Last-Modified).
  • Works with got, request, or native http.
// cacheable-request: HTTP caching
import CacheableRequest from 'cacheable-request';
import http from 'http';

const cacheableRequest = new CacheableRequest(http.request);

const req = cacheableRequest('https://api.example.com/data', {
  cacheOptions: { cacheTtl: 1000 * 60 * 5 }
});

req.on('response', (res) => {
  console.log('Status:', res.statusCode);
});

⏱️ TTL and Expiration Handling

How each package handles time-based expiration varies significantly.

  • lru-cache uses TTL per entry in newer versions (v7+). Older versions relied on LRU eviction only.
  • node-cache has global and per-key TTL with automatic cleanup intervals.
  • memory-cache supports per-key TTL but no global cleanup configuration.
  • cache-manager delegates TTL to the underlying store implementation.
  • apicache uses TTL for HTTP response validity.
  • cacheable-request respects HTTP Cache-Control headers plus optional overrides.
// lru-cache: Per-entry TTL
const cache = new LRUCache({ ttl: 5000 });
cache.set('key', 'value', 5000); // 5 seconds

// node-cache: Global and per-key TTL
const cache = new NodeCache({ stdTTL: 60 });
cache.set('key', 'value', 120); // Overrides global to 2 minutes

// memory-cache: Per-key TTL only
cache.put('key', 'value', 60000); // 60 seconds

// cache-manager: Store-dependent TTL
await cache.set('key', 'value', 60); // 60 seconds

// apicache: Middleware TTL string
app.get('/api', apicache.middleware('10 minutes'), handler);

// cacheable-request: HTTP header based
const req = cacheableRequest(url, { cacheOptions: { cacheTtl: 60000 } });

🔄 Eviction Strategies: LRU vs TTL vs Manual

Understanding how items leave the cache is critical for memory management.

  • lru-cache evicts based on access order when max size is reached. Least recently used items go first.
  • node-cache evicts based on TTL expiration with periodic cleanup checks.
  • memory-cache evicts based on TTL expiration during get operations.
  • cache-manager depends on the store — memory uses LRU or TTL, Redis uses TTL.
  • apicache evicts based on TTL and memory limits.
  • cacheable-request evicts based on HTTP cache headers and storage limits.
// lru-cache: LRU eviction when max reached
const cache = new LRUCache({ max: 100 });
// When 101st item added, oldest accessed item is removed

// node-cache: TTL-based cleanup
const cache = new NodeCache({ checkperiod: 60 }); // Check every 60 seconds

// memory-cache: Lazy cleanup on get
// Items removed when accessed after expiration

// cache-manager: Configurable per store
const cache = cacheManager.caching({ store: 'memory', max: 100 });

// apicache: Memory limit configuration
apicache.options({ debug: true, defaultDuration: 3600000 });

// cacheable-request: Storage-based eviction
const cacheableRequest = new CacheableRequest(http.request, { cacheAdapter: new Keyv() });

🌐 HTTP vs Data Caching: Different Use Cases

Some packages cache HTTP responses, others cache application data.

  • apicache and cacheable-request focus on HTTP layer caching.
  • lru-cache, node-cache, memory-cache, and cache-manager focus on application data.
// apicache: HTTP response caching
app.get('/users', apicache.middleware('5 minutes'), getUsers);

// cacheable-request: HTTP client caching
const getData = () => cacheableRequest('https://api.example.com/users');

// node-cache: Application data caching
const users = await cache.get('users');
if (!users) {
  const data = await db.query('SELECT * FROM users');
  cache.set('users', data);
}

// lru-cache: Application data with LRU
const cache = new LRUCache({ max: 1000 });
cache.set('userId', userData);

// memory-cache: Simple data caching
cache.put('session', sessionData, 3600000);

// cache-manager: Unified data caching
await cache.set('config', configData, 300);

⚠️ Maintenance Status and Production Readiness

Not all packages are equally maintained for production use.

  • apicache — ⚠️ No longer actively maintained. Last significant update was in 2021. Consider alternatives like route-cache or custom middleware for new projects.
  • memory-cache — ⚠️ Minimal maintenance. Works but lacks modern features and active development.
  • lru-cache — ✅ Actively maintained. Widely used as a dependency by many major packages.
  • node-cache — ✅ Stable and maintained. Good for in-process caching needs.
  • cache-manager — ✅ Actively maintained. Regular updates and community support.
  • cacheable-request — ✅ Maintained. Works well with modern HTTP clients.
// For new projects, prefer maintained packages
import { LRUCache } from 'lru-cache'; // ✅ Recommended
import NodeCache from 'node-cache'; // ✅ Recommended
import cacheManager from 'cache-manager'; // ✅ Recommended

// Avoid for new production projects
import apicache from 'apicache'; // ⚠️ Deprecated
import cache from 'memory-cache'; // ⚠️ Minimal maintenance

📊 Feature Comparison Table

Featurelru-cachenode-cachememory-cachecache-managerapicachecacheable-request
TypeData StructureIn-Memory CacheIn-Memory CacheCache AbstractionHTTP MiddlewareHTTP Client Wrapper
TTL Support✅ (v7+)✅✅✅ (Store-dependent)✅✅ (HTTP Headers)
LRU Eviction✅❌❌✅ (Memory store)✅❌
Events/Hooks❌✅❌✅✅✅
Multi-Store❌❌❌✅❌❌
HTTP Aware❌❌❌❌✅✅
Maintenance✅ Active✅ Stable⚠️ Minimal✅ Active⚠️ Deprecated✅ Active
Best ForLow-level cachingIn-process dataSimple prototypingFlexible backendsExpress response cachingExternal API calls

🎯 Real-World Selection Guide

Scenario 1: Caching Database Query Results

You need to cache query results in memory with automatic expiration.

  • ✅ Best choice: node-cache or lru-cache
  • Why? You need TTL and reliable eviction without external dependencies.
// Using node-cache for query results
const cache = new NodeCache({ stdTTL: 300 });

async function getUser(id) {
  const cached = cache.get(`user:${id}`);
  if (cached) return cached;
  
  const user = await db.users.findById(id);
  cache.set(`user:${id}`, user);
  return user;
}

Scenario 2: Caching External API Responses

You make frequent calls to third-party APIs and want to respect their cache headers.

  • ✅ Best choice: cacheable-request
  • Why? It handles ETag, Last-Modified, and Cache-Control automatically.
// Using cacheable-request for external APIs
const cacheableRequest = new CacheableRequest(http.request);

async function fetchExternalData(url) {
  return new Promise((resolve, reject) => {
    const req = cacheableRequest(url);
    req.on('response', res => {
      // Handle response with caching applied
    });
    req.end();
  });
}

Scenario 3: Express API Response Caching

You want to cache entire HTTP responses for GET endpoints.

  • ✅ Best choice: Custom middleware or cache-manager with Express
  • Why? apicache is deprecated. Build custom logic or use maintained alternatives.
// Custom Express caching with cache-manager
app.get('/api/data', async (req, res) => {
  const cached = await cache.get(req.url);
  if (cached) return res.json(cached);
  
  const data = await fetchData();
  await cache.set(req.url, data, 60);
  res.json(data);
});

Scenario 4: Multi-Environment Caching Strategy

You need to switch between memory (development) and Redis (production) without code changes.

  • ✅ Best choice: cache-manager
  • Why? Unified API allows swapping stores via configuration.
// cache-manager with configurable store
const store = process.env.NODE_ENV === 'production' ? 'redis' : 'memory';

const cache = cacheManager.caching({
  store: store,
  ttl: 60,
  redis: { host: 'localhost', port: 6379 }
});

Scenario 5: High-Performance In-Memory Cache

You need maximum performance for a hot path with strict memory limits.

  • ✅ Best choice: lru-cache
  • Why? Highly optimized, minimal overhead, precise control over memory usage.
// lru-cache for performance-critical paths
const cache = new LRUCache({
  max: 10000,
  ttl: 60000,
  updateAgeOnGet: true
});

💡 Final Recommendations

For most applications, start with node-cache for simple in-memory needs or cache-manager if you anticipate needing Redis later. Both are well-maintained and offer good developer experience.

For HTTP-specific caching, use cacheable-request for external API calls. Avoid apicache in new projects due to its deprecated status — instead, build custom Express middleware using cache-manager or a Redis-backed solution.

For low-level optimization, lru-cache is the gold standard. It is used by many major packages internally and provides the best performance for LRU-based eviction.

Avoid memory-cache for production systems requiring long-term support. While simple, it lacks the features and maintenance commitment of node-cache or cache-manager.

Remember that caching adds complexity — always measure the performance impact and ensure your cache invalidation strategy matches your data consistency requirements. A well-configured cache can speed up your application significantly, but a poorly managed one can lead to stale data and hard-to-debug issues.

How to Choose: cache-manager vs apicache vs cacheable-request vs lru-cache vs memory-cache vs node-cache

  • cache-manager:

    Choose cache-manager when you need flexibility to swap cache backends (memory, Redis, file system) without changing your application code. It provides a unified API across different stores and supports clustering. Ideal for applications that might need to scale from simple in-memory caching to distributed Redis caching later.

  • apicache:

    Choose apicache if you need quick HTTP response caching for Express applications without writing custom logic. It works as middleware to cache entire route responses based on status codes and TTL. However, note that this package is no longer actively maintained, so evaluate newer alternatives for production systems requiring long-term support.

  • cacheable-request:

    Choose cacheable-request when you need HTTP-level caching that respects standard cache headers (ETag, Last-Modified, Cache-Control). It wraps HTTP clients like got or request to automatically handle caching based on server responses. Best for applications making many external API calls where you want to respect upstream cache policies.

  • lru-cache:

    Choose lru-cache when you need a performant, low-level LRU data structure without extra features like TTL or clustering. It is highly optimized and widely used as a dependency by other caching libraries. Perfect for scenarios where you need fine-grained control over cache eviction based on access patterns rather than time.

  • memory-cache:

    Choose memory-cache for simple, lightweight in-memory caching with basic TTL support in small Node.js applications. It has a very simple API but lacks advanced features like clustering or multiple stores. Consider this only for development or small-scale projects where complexity must be minimized.

  • node-cache:

    Choose node-cache when you need a reliable in-memory cache with TTL, event hooks, and key pattern matching in a single Node.js process. It offers more features than memory-cache while remaining simple to use. Suitable for applications that need periodic cleanup and cache event monitoring without external dependencies.

README for cache-manager

Cacheable

cache-manager

codecov tests npm npm license

Simple and fast NodeJS caching module.

A cache module for NodeJS that allows easy wrapping of functions in cache, tiered caches, and a consistent interface.

  • Made with Typescript and compatible with ESModules.
  • Easy way to wrap any function in cache, supports a mechanism to refresh expiring cache keys in background.
  • Tiered caches -- data gets stored in each cache and fetched from the highest priority cache(s) first.
  • nonBlocking option that optimizes how the system handles multiple stores.
  • Use with any Keyv compatible storage adapter.
  • 100% test coverage via vitest.

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.

Migration from v6 to v7

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

Migration from v5 to v6

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:

Table of Contents

Installation

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

Quick start

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

Using CacheableMemory or lru-cache as storage adapter

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] });

Options

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

Methods

set

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

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

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

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

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

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

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

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

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:

  • The store that will be checked for refresh is the one where the key will be found first (highest priority).
  • If the threshold is low and the worker function is slow, the key may expire and you may encounter a racing condition with updating values.
  • If no 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

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.

Properties

cacheId

cacheId(): string

Returns cache instance id. This is primarily used to not have conflicts when using wrap with multiple cache instances.

stores

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.

Events

set

Fired when a key has been added or changed.

cache.on('set', ({ key, value, error }) => {
	// ... do something ...
})

del

Fired when a key has been removed manually.

cache.on('del', ({ key, error }) => {
	// ... do something ...
})

clear

Fired when the cache has been flushed.

cache.on('clear', (error) => {
  if (error) {
    // ... do something ...
  }
})

refresh

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.

Doing Iteration on Stores

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.

Update on redis and ioredis Support

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.

Using Legacy Storage Adapters

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.

Contribute

If you would like to contribute to the project, please read how to contribute here CONTRIBUTING.md.

License

MIT © Jared Wray