lru-cache vs keyv vs redis vs node-cache vs cache-manager vs levelup vs memory-cache vs node-persist
Node.js Caching Libraries Comparison
1 Year
lru-cachekeyvredisnode-cachecache-managerlevelupmemory-cachenode-persistSimilar Packages:
What's 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.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
lru-cache223,662,9945,590820 kB103 months agoISC
keyv51,439,6552,90693.4 kB15 days agoMIT
redis5,210,30017,210247 kB3649 days agoMIT
node-cache3,907,9082,335-735 years agoMIT
cache-manager2,392,1321,81951.2 kB27 days agoMIT
levelup1,396,2324,088-04 years agoMIT
memory-cache755,1291,599-328 years agoBSD-2-Clause
node-persist141,66473040.1 kB175 months agoMIT
Feature Comparison: lru-cache vs keyv vs redis vs node-cache vs cache-manager vs levelup vs memory-cache vs node-persist

Storage Options

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

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

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

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

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

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

  • 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-persist:

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

Eviction Policies

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

  • keyv:

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

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

  • node-cache:

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

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

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

  • memory-cache:

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

  • node-persist:

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

Performance

  • lru-cache:

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

  • keyv:

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

  • redis:

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

  • node-cache:

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

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

  • levelup:

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

  • memory-cache:

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

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

Use Cases

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

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

  • redis:

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

  • node-cache:

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

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

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

  • memory-cache:

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

  • node-persist:

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

Learning Curve

  • lru-cache:

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

  • keyv:

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

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

  • node-cache:

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

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

  • levelup:

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

  • memory-cache:

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

  • node-persist:

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

How to Choose: lru-cache vs keyv vs redis vs node-cache vs cache-manager vs levelup vs memory-cache vs node-persist
  • 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.

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

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

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

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

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

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

README for lru-cache

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
}

Performance

As of January 2022, version 7 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 at all possible, use short non-numeric strings (ie, less than 256 characters) as your keys, and 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 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, 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.

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.