Caching Libraries in Node.js Comparison
lru-cache vs quick-lru vs cacheable-request vs cache-manager vs memory-cache
1 Year
lru-cachequick-lrucacheable-requestcache-managermemory-cacheSimilar Packages:
What's Caching Libraries in Node.js?

Caching libraries in Node.js are essential tools that help improve application performance by storing frequently accessed data in memory or other storage mediums. These libraries reduce the need for repeated data retrieval from slower sources, such as databases or external APIs, thereby enhancing response times and overall user experience. Each library offers unique features and use cases, catering to different caching needs, from simple in-memory caching to more complex strategies involving multiple storage backends.

NPM Package Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
lru-cache193,604,5765,396808 kB72 months agoISC
quick-lru22,164,14668015.1 kB4a year agoMIT
cacheable-request17,623,2961,66571.6 kB1a month agoMIT
cache-manager1,841,4171,66542.4 kB17 days agoMIT
memory-cache845,7311,594-327 years agoBSD-2-Clause
Feature Comparison: lru-cache vs quick-lru vs cacheable-request vs cache-manager vs memory-cache

Caching Strategy

  • lru-cache:

    Lru-cache implements the Least Recently Used (LRU) caching strategy, which evicts the least recently accessed items when the cache reaches its limit. This is effective for managing memory usage while keeping frequently accessed data readily available.

  • quick-lru:

    Quick-lru is designed for high performance with a minimal memory footprint. It uses a simple LRU eviction strategy, ensuring that the most frequently accessed items are kept in memory while older items are discarded efficiently.

  • cacheable-request:

    Cacheable-request focuses specifically on HTTP caching, implementing the HTTP caching specification to ensure that responses are cached based on their headers. This makes it suitable for web applications that interact heavily with APIs and need to optimize network calls.

  • cache-manager:

    Cache-manager supports multiple caching strategies and backends, allowing you to choose the best fit for your application's needs. It abstracts the caching logic, enabling easy switching between different storage solutions without changing the application code.

  • memory-cache:

    Memory-cache provides a simple key-value store for caching data in memory. It does not implement any eviction strategy, making it suitable for applications where data size is manageable and the overhead of managing cache is not required.

Performance

  • lru-cache:

    Lru-cache is highly efficient in terms of speed and memory usage, making it suitable for applications that require rapid access to cached data. Its LRU strategy ensures that the cache remains performant even under heavy load.

  • quick-lru:

    Quick-lru is optimized for speed, making it one of the fastest LRU cache implementations available. It is particularly useful in scenarios where performance is critical, such as real-time applications or high-frequency data access.

  • cacheable-request:

    Cacheable-request is optimized for reducing network calls by caching HTTP responses, which can significantly improve performance in applications that rely on external APIs. By caching responses, it minimizes the latency associated with network requests.

  • cache-manager:

    Cache-manager is designed to be performant across various backends, leveraging the strengths of each backend to optimize data retrieval and storage. Its ability to switch backends allows developers to choose the most efficient storage solution for their specific use case.

  • memory-cache:

    Memory-cache is straightforward and fast, providing quick access to cached data without the overhead of complex eviction policies. It is suitable for applications with low to moderate caching needs where simplicity is key.

Ease of Use

  • lru-cache:

    Lru-cache has a straightforward API that is easy to understand and implement. It requires only a few lines of code to set up, making it accessible for developers looking for a quick caching solution.

  • quick-lru:

    Quick-lru provides a simple API that is easy to integrate into existing applications. Its lightweight nature makes it a good choice for developers who want a fast and efficient caching solution without unnecessary complexity.

  • cacheable-request:

    Cacheable-request is easy to use, requiring minimal configuration to start caching HTTP requests. Its automatic handling of request and response caching simplifies the process for developers, allowing them to focus on application logic.

  • cache-manager:

    Cache-manager offers a simple and consistent API that abstracts the complexities of different caching backends, making it easy to implement and manage caching in your application. Its flexibility allows for quick integration with minimal setup.

  • memory-cache:

    Memory-cache is extremely easy to use, with a simple key-value interface that allows developers to cache data with minimal effort. It is ideal for those who need a quick and uncomplicated caching mechanism.

Scalability

  • lru-cache:

    Lru-cache is best suited for applications with limited memory requirements, as it operates in-memory. While it can handle a reasonable amount of data, it may not be the best choice for large-scale applications that require distributed caching.

  • quick-lru:

    Quick-lru is efficient for in-memory caching but is limited in scalability due to its single-instance nature. It is ideal for applications that need fast access to frequently used data without the need for distributed caching.

  • cacheable-request:

    Cacheable-request is primarily focused on HTTP caching and may not scale as well in scenarios requiring distributed caching. However, it excels in optimizing API calls within a single instance or server environment.

  • cache-manager:

    Cache-manager is highly scalable due to its support for various backends, including distributed caching solutions like Redis. This makes it suitable for applications that need to scale horizontally across multiple servers or instances.

  • memory-cache:

    Memory-cache is not inherently scalable, as it stores data in memory on a single instance. It is best for small to medium applications where data size is manageable and does not require distribution across multiple servers.

Eviction Policy

  • lru-cache:

    Lru-cache uses the LRU eviction policy, which ensures that the least recently accessed items are removed first when the cache reaches its limit. This is effective for keeping frequently accessed data in memory while managing memory usage efficiently.

  • quick-lru:

    Quick-lru employs the LRU eviction policy, ensuring that the most relevant data remains cached while older data is discarded. This makes it suitable for applications with dynamic data access patterns.

  • cacheable-request:

    Cacheable-request does not implement its own eviction policy, as it relies on HTTP caching headers to determine cache validity. This means that the eviction strategy is dictated by the server's response rather than the library itself.

  • cache-manager:

    Cache-manager allows for customizable eviction policies depending on the backend used. This flexibility lets developers choose the most appropriate strategy for their caching needs, whether it be time-based expiration or size limits.

  • memory-cache:

    Memory-cache does not implement any eviction policy, meaning that cached items will remain in memory until the application is terminated or the cache is manually cleared. This simplicity can be a drawback in larger applications with high memory usage.

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

    Opt for lru-cache when you need a simple and efficient in-memory cache that implements the Least Recently Used (LRU) eviction policy. This is suitable for scenarios where memory is limited, and you want to ensure that the most frequently accessed items remain in cache while older items are removed.

  • quick-lru:

    Choose quick-lru if you need a lightweight and fast LRU cache implementation. It is optimized for performance and is particularly effective in scenarios where speed is critical, such as high-frequency data access patterns.

  • cacheable-request:

    Select cacheable-request if your primary focus is on caching HTTP requests and responses. It is particularly useful for applications that make frequent API calls, as it automatically handles the caching of requests and responses, reducing redundant network traffic and improving performance.

  • cache-manager:

    Choose cache-manager if you need a versatile caching solution that supports multiple backends (like Redis, Memcached, etc.) and offers a consistent API for managing cache across different storage systems. It's ideal for applications that require a unified caching strategy with the ability to switch backends easily.

  • memory-cache:

    Use memory-cache for a straightforward in-memory caching solution that is easy to set up and use. It’s best for applications that require a simple caching mechanism without the overhead of more complex features, making it ideal for small to medium-sized 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.