Node.js Caching Libraries Comparison
lru-cache vs cacheable-request vs node-cache vs cache-manager vs memory-cache vs apicache
1 Year
lru-cachecacheable-requestnode-cachecache-managermemory-cacheapicacheSimilar Packages:
What's Node.js Caching Libraries?

Caching libraries in Node.js are essential tools that help improve application performance by temporarily storing data in memory or on disk, reducing the need to repeatedly fetch data from slower sources like databases or external APIs. These libraries provide various caching strategies, allowing developers to choose the most suitable method for their specific use cases, ultimately enhancing response times and scalability of applications.

NPM Package Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
lru-cache186,370,8155,397808 kB72 months agoISC
cacheable-request17,473,0261,66571.6 kB1a month agoMIT
node-cache3,391,0762,289-744 years agoMIT
cache-manager1,813,6051,66542.4 kB19 days agoMIT
memory-cache837,0671,593-328 years agoBSD-2-Clause
apicache27,4191,239-633 years agoMIT
Feature Comparison: lru-cache vs cacheable-request vs node-cache vs cache-manager vs memory-cache vs apicache

Caching Strategy

  • lru-cache:

    LRU-Cache employs a Least Recently Used (LRU) caching strategy, which evicts the least recently accessed items when the cache size limit is reached. This ensures that frequently accessed data remains in memory, optimizing performance for read-heavy applications.

  • cacheable-request:

    Cacheable-Request enhances HTTP requests by allowing responses to be cached based on HTTP headers. It intelligently manages cache validation and expiration, making it suitable for applications that interact heavily with external APIs.

  • node-cache:

    Node-Cache provides a basic key-value store with optional expiration times for cached items. It is a simple caching solution that allows developers to set timeouts for cached data, ensuring that stale data is automatically removed.

  • cache-manager:

    Cache Manager provides a flexible caching strategy that allows developers to choose from various stores (in-memory, Redis, Memcached, etc.) and configure multiple caching layers. This makes it suitable for complex applications that require different caching mechanisms based on context.

  • memory-cache:

    Memory-Cache uses a straightforward in-memory caching strategy, where data is stored in the application's memory. It is ideal for scenarios where data persistence is not required, and speed is a priority, making it simple to implement and use.

  • apicache:

    Apicache implements a simple HTTP caching strategy that focuses on caching API responses based on request URLs and HTTP methods. It is designed to work seamlessly with Express.js, allowing developers to specify cache duration and control cache behavior easily.

Integration

  • lru-cache:

    LRU-Cache is a standalone library that can be easily integrated into any Node.js application. Its simple API allows developers to implement caching without the need for extensive setup or configuration, making it a quick solution for in-memory caching.

  • cacheable-request:

    Cacheable-Request can be easily integrated into existing HTTP request libraries, such as Axios or Node's native http module. This makes it a flexible choice for adding caching to any HTTP request workflow without major refactoring.

  • node-cache:

    Node-Cache is easy to integrate into any Node.js application, providing a simple API for setting and retrieving cached data. It is ideal for developers who want a no-fuss caching solution that can be implemented quickly.

  • cache-manager:

    Cache Manager is highly versatile and can be integrated with various caching backends, including Redis and Memcached. Its unified API allows developers to switch between different storage solutions without changing the underlying code significantly.

  • memory-cache:

    Memory-Cache is straightforward to integrate into any Node.js application. It requires minimal setup and can be used immediately, making it a good choice for developers looking for a quick caching solution without dependencies.

  • apicache:

    Apicache is specifically designed for integration with Express.js, making it easy to implement caching for RESTful APIs. Its middleware approach allows developers to add caching capabilities with minimal configuration and effort.

Performance

  • lru-cache:

    LRU-Cache is designed for high performance in scenarios where memory access speed is critical. Its eviction strategy ensures that frequently accessed data remains available, optimizing read operations and reducing response times.

  • cacheable-request:

    Cacheable-Request improves performance by reducing the number of network calls to external APIs. By caching responses, it minimizes latency and speeds up data retrieval, especially for frequently accessed resources.

  • node-cache:

    Node-Cache offers good performance for basic caching needs. It allows for quick retrieval of cached data, but performance may vary based on the size of the cache and the frequency of cache misses.

  • cache-manager:

    Cache Manager's performance depends on the underlying caching store used. When configured with high-performance backends like Redis, it can handle large volumes of requests efficiently, making it suitable for high-traffic applications.

  • memory-cache:

    Memory-Cache provides fast access to cached data since it stores everything in memory. This makes it ideal for applications where speed is essential, although it may not be suitable for large datasets due to memory limitations.

  • apicache:

    Apicache is optimized for performance, focusing on caching HTTP responses to reduce the load on backend services. By caching responses, it significantly decreases response times for repeated requests, enhancing overall API performance.

Expiration Management

  • lru-cache:

    LRU-Cache automatically manages expiration by evicting the least recently used items when the cache reaches its limit. This ensures that the most relevant data remains available while efficiently managing memory usage.

  • cacheable-request:

    Cacheable-Request manages expiration based on HTTP caching headers, ensuring that cached responses are only used when valid. This helps maintain data integrity while leveraging caching for performance improvements.

  • node-cache:

    Node-Cache supports expiration management by allowing developers to set timeouts for cached items. This ensures that data does not become stale and that the cache remains effective over time.

  • cache-manager:

    Cache Manager provides flexible expiration management, allowing developers to configure timeouts for cached items based on their specific needs. This ensures that stale data is removed and that the cache remains efficient and relevant.

  • memory-cache:

    Memory-Cache allows developers to set expiration times for cached items, ensuring that stale data is removed after a specified duration. This feature is essential for maintaining data accuracy in applications that rely on frequently changing data.

  • apicache:

    Apicache allows developers to set cache duration for API responses, enabling automatic expiration of cached data. This feature helps maintain data freshness while optimizing performance by reducing unnecessary requests.

Use Cases

  • lru-cache:

    LRU-Cache is ideal for applications that require fast access to frequently used data, such as caching results of expensive computations or database queries. It is well-suited for scenarios where memory efficiency is crucial.

  • cacheable-request:

    Cacheable-Request is particularly useful for applications that make frequent requests to external APIs. By caching responses, it minimizes redundant network calls and improves performance in data retrieval scenarios.

  • node-cache:

    Node-Cache is a good choice for applications needing basic caching functionality without the complexity of advanced caching strategies. It is suitable for scenarios where data is frequently accessed but does not require complex expiration or eviction policies.

  • cache-manager:

    Cache Manager is versatile and can be used in various applications requiring caching, such as web servers, microservices, and data-intensive applications. Its ability to switch between different caching stores makes it suitable for diverse environments.

  • memory-cache:

    Memory-Cache is best for small applications or services where simplicity and speed are priorities. It is suitable for caching temporary data that does not require persistence and can be easily managed in memory.

  • apicache:

    Apicache is best suited for caching API responses in web applications, particularly for RESTful services where reducing response times is critical. It is ideal for scenarios where data does not change frequently and can be cached for a defined period.

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

    Use LRU-Cache when you need a fast, in-memory cache that automatically removes the least recently used items when the cache reaches its limit. It is suitable for scenarios where memory efficiency is crucial and you want to maintain quick access to frequently used data.

  • cacheable-request:

    Opt for Cacheable-Request if you want to enhance HTTP requests by adding caching capabilities. This package is particularly useful for caching responses from external APIs, allowing you to minimize redundant network calls and improve performance.

  • node-cache:

    Select Node-Cache if you need a simple key-value caching solution with optional expiration times. It is a good choice for applications that require basic caching functionality without the complexity of more advanced caching strategies.

  • cache-manager:

    Select Cache Manager if you require a versatile caching solution that supports multiple backends (like Redis, Memcached, etc.) and offers a unified API for managing different caching stores. It is ideal for applications that need to switch between different caching strategies.

  • memory-cache:

    Choose Memory-Cache for a straightforward in-memory caching solution that is easy to set up and use. It is best for small applications or services where simplicity and speed are priorities, and persistent storage is not required.

  • apicache:

    Choose Apicache if you need a simple and effective HTTP caching solution for your API responses. It is particularly useful for caching GET requests and can be easily integrated with Express.js applications.

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) => {
    freeFromMemoryOrWhatever(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.