cache-manager vs keyv vs levelup vs lru-cache vs memory-cache vs node-cache vs node-persist vs redis
Node.js Caching Libraries
cache-managerkeyvleveluplru-cachememory-cachenode-cachenode-persistredisSimilar Packages:

Node.js Caching Libraries

Caching libraries in Node.js are designed to improve application performance by temporarily storing data in memory or other storage mediums, reducing the need for repeated data retrieval from slower sources like databases or APIs. These libraries offer various caching strategies and storage options, allowing developers to optimize data access patterns and enhance the responsiveness of their applications.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
cache-manager02,01148.7 kB04 months agoMIT
keyv03,201357 kB117 days agoMIT
levelup04,066-05 years agoMIT
lru-cache05,9183.33 MB15a month agoBlueOak-1.0.0
memory-cache01,591-329 years agoBSD-2-Clause
node-cache02,372-776 years agoMIT
node-persist072540.1 kB172 years agoMIT
redis017,589300 kB12323 days agoMIT

Feature Comparison: cache-manager vs keyv vs levelup vs lru-cache vs memory-cache vs node-cache vs node-persist vs redis

Storage Options

  • cache-manager:

    cache-manager supports multiple storage backends, including in-memory, Redis, Memcached, and more, allowing for flexible caching strategies depending on your application's needs.

  • keyv:

    keyv offers a simple interface with support for various backends like memory, Redis, and SQLite, making it easy to switch storage solutions without changing your code significantly.

  • levelup:

    levelup is built on top of LevelDB, providing a persistent key-value store that is efficient for read and write operations, ideal for applications needing durable storage.

  • lru-cache:

    lru-cache is strictly an in-memory cache, focusing on speed and efficiency with an LRU eviction policy to manage memory usage effectively.

  • memory-cache:

    memory-cache is a pure in-memory cache, providing fast access to cached data without any persistence, suitable for temporary data storage.

  • node-cache:

    node-cache is also an in-memory cache, but it includes features like TTL and automatic expiration, making it easy to manage cached data lifecycle.

  • node-persist:

    node-persist provides file-based persistent storage, allowing data to be saved across application restarts, suitable for lightweight persistence needs.

  • redis:

    redis is an in-memory data structure store that offers various data types and persistence options, making it suitable for high-performance applications requiring complex data operations.

Eviction Policies

  • cache-manager:

    cache-manager allows you to implement custom eviction policies based on your application's caching strategy, giving you control over how cached data is managed.

  • keyv:

    keyv does not enforce a specific eviction policy but allows you to implement your own logic for managing cached data expiration.

  • levelup:

    levelup does not have built-in eviction policies, as it focuses on persistent storage; however, you can implement your own logic for managing data retention.

  • lru-cache:

    lru-cache implements a least-recently-used (LRU) eviction policy, automatically removing the least recently accessed items when the cache reaches its size limit.

  • memory-cache:

    memory-cache does not have built-in eviction policies, making it suitable for simple caching scenarios where manual management is acceptable.

  • node-cache:

    node-cache supports TTL for cache entries, automatically expiring items after a specified duration, simplifying cache management.

  • node-persist:

    node-persist does not have eviction policies, as it focuses on persistent storage; data remains until explicitly removed or overwritten.

  • redis:

    redis supports various eviction policies (like LRU, LFU, etc.), allowing you to configure how data is managed in memory based on your application's needs.

Performance

  • cache-manager:

    cache-manager's performance depends on the underlying storage backend; in-memory storage provides the fastest access, while external backends may introduce latency.

  • keyv:

    keyv is designed for performance, especially when using in-memory backends; it offers fast access times and low overhead for caching operations.

  • levelup:

    levelup provides high performance for read and write operations due to its LevelDB foundation, making it suitable for applications with large datasets.

  • lru-cache:

    lru-cache is optimized for speed, providing fast in-memory access and efficient memory management through its LRU eviction policy.

  • memory-cache:

    memory-cache offers quick access to cached data, making it suitable for lightweight applications where performance is critical.

  • node-cache:

    node-cache provides good performance for in-memory caching, with features like TTL ensuring efficient data management without significant overhead.

  • node-persist:

    node-persist's performance is slower than in-memory solutions due to file I/O, but it is suitable for applications needing persistent storage without high performance demands.

  • redis:

    redis is known for its high performance, offering low-latency access to data and supporting complex operations, making it ideal for scalable applications.

Use Cases

  • cache-manager:

    cache-manager is versatile and can be used in various scenarios, including web applications, API response caching, and session storage, due to its support for multiple backends.

  • keyv:

    keyv is ideal for applications that require a simple caching solution with the ability to switch between memory and persistent storage easily, such as microservices.

  • levelup:

    levelup is suitable for applications needing a persistent key-value store, such as data logging, user sessions, or caching large datasets that require durability.

  • lru-cache:

    lru-cache is perfect for scenarios where memory usage is a concern, such as caching API responses or expensive computations in memory-limited environments.

  • memory-cache:

    memory-cache is best for temporary data storage in lightweight applications or during development, where persistence is not required.

  • node-cache:

    node-cache is useful for caching frequently accessed data in web applications, such as user sessions or configuration data, with automatic expiration.

  • node-persist:

    node-persist is designed for applications needing simple file-based persistence, such as configuration storage or lightweight data logging.

  • redis:

    redis is ideal for high-performance applications requiring complex data structures, real-time analytics, or pub/sub messaging systems.

Learning Curve

  • cache-manager:

    cache-manager has a moderate learning curve due to its flexibility and multiple backend support, but its unified API simplifies usage across different storage solutions.

  • keyv:

    keyv is easy to learn and use, with a straightforward API that allows developers to quickly implement caching in their applications.

  • levelup:

    levelup may require some understanding of LevelDB concepts, but it is generally easy to use for developers familiar with key-value stores.

  • lru-cache:

    lru-cache is simple to implement and understand, making it accessible for developers looking for an efficient in-memory caching solution.

  • memory-cache:

    memory-cache has a very low learning curve, suitable for quick implementations in simple applications or prototypes.

  • node-cache:

    node-cache is straightforward to use, with clear documentation and examples, making it easy for developers to integrate caching into their applications.

  • node-persist:

    node-persist is easy to learn, especially for those familiar with file I/O operations, providing a simple API for persistent storage.

  • redis:

    redis has a steeper learning curve due to its rich feature set and advanced data structures, but it offers extensive documentation and community support.

How to Choose: cache-manager vs keyv vs levelup vs lru-cache vs memory-cache vs node-cache vs node-persist vs redis

  • cache-manager:

    Choose cache-manager if you need a versatile caching solution that supports multiple backends (like Redis, Memcached, etc.) and provides a unified API. It's ideal for applications that require flexibility in caching strategies and backend storage.

  • keyv:

    Select keyv for a simple and lightweight caching solution that supports various backends, including memory, Redis, and more. It's great for projects where you want a straightforward API and the ability to switch backends easily without significant changes to your code.

  • levelup:

    Opt for levelup if you are looking for a persistent key-value store that works with LevelDB. It's suitable for applications that require durable storage with fast read and write capabilities, especially when dealing with large datasets.

  • lru-cache:

    Use lru-cache when you need an in-memory cache with a least-recently-used eviction policy. This is particularly useful for applications where memory usage is a concern, and you want to automatically manage cache size based on usage patterns.

  • memory-cache:

    Choose memory-cache for a simple in-memory caching solution without complex features. It's ideal for lightweight applications or prototyping where you want quick access to cached data without the overhead of persistent storage.

  • node-cache:

    Select node-cache if you need a straightforward in-memory caching solution with features like time-to-live (TTL) and automatic expiration. It's suitable for applications that require basic caching capabilities without the need for persistence.

  • node-persist:

    Opt for node-persist when you need a simple file-based persistent storage solution. It's useful for applications that require data persistence across restarts without the complexity of a full database.

  • redis:

    Choose Redis if you need a powerful, in-memory data structure store that supports advanced caching strategies, pub/sub messaging, and persistence options. It's ideal for high-performance applications that require complex data operations and scalability.

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