@isaacs/ttlcache vs lru-cache vs memory-cache vs node-cache
In-Memory Caching Strategies for Node.js and Frontend Build Tools
@isaacs/ttlcachelru-cachememory-cachenode-cacheSimilar Packages:

In-Memory Caching Strategies for Node.js and Frontend Build Tools

In-memory caching is essential for improving performance in Node.js backends and build tools by storing frequently accessed data in RAM. These four packages offer different approaches to managing stored data, ranging from simple key-value stores to advanced eviction policies. lru-cache and @isaacs/ttlcache focus on strict memory control and expiration, while memory-cache and node-cache provide general-purpose wrappers with varying levels of maintenance and features. Choosing the right tool depends on whether you need size limits, time-based expiration, or simple storage without external dependencies.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
@isaacs/ttlcache022691.3 kB13 months agoBlueOak-1.0.0
lru-cache05,9062.74 MB2a month agoBlueOak-1.0.0
memory-cache01,595-329 years agoBSD-2-Clause
node-cache02,372-766 years agoMIT

In-Memory Caching Strategies for Node.js and Frontend Build Tools

Caching data in memory is a common way to speed up applications by avoiding repeated calculations or network requests. The four packages @isaacs/ttlcache, lru-cache, memory-cache, and node-cache all solve this problem but use different rules for storing and removing data. Understanding these differences helps you avoid memory leaks and pick the right tool for your architecture. Let's look at how they handle eviction, API design, and maintenance.

🗑️ Eviction Strategies: Size Limits vs Time Limits

The most important difference is how each package decides when to remove data. Some focus on time, some on size, and some on both.

lru-cache uses Least Recently Used eviction.

  • It removes old items when the cache gets full.
  • You can set a max number of items or a max memory size.
// lru-cache: Limit by item count
const { LRUCache } = require('lru-cache');
const cache = new LRUCache({ max: 500 });
cache.set('key', 'value');
// Automatically removes least used items when limit hits 500

@isaacs/ttlcache focuses on Time-To-Live expiration.

  • It extends the native Map class.
  • Items expire after a set time but do not evict based on access frequency.
// @isaacs/ttlcache: Strict TTL
const { TTLCache } = require('@isaacs/ttlcache');
const cache = new TTLCache({ ttl: 1000 });
cache.set('key', 'value');
// Item expires after 1000ms regardless of access

memory-cache uses simple time-based expiration.

  • It does not enforce size limits by default.
  • Items stay until they expire or you delete them manually.
// memory-cache: Simple TTL
const cache = require('memory-cache');
cache.put('key', 'value', 1000);
// Expires after 1000ms, no size limit enforcement

node-cache supports flexible TTL and periodic checks.

  • It runs a background check to clean expired keys.
  • You can set default TTLs for all items or per item.
// node-cache: Flexible TTL
const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 100 });
cache.set('key', 'value');
// Checks periodically to remove expired items

🛠️ API Design and Developer Experience

The way you interact with each cache varies from singleton patterns to class instances. This affects how you organize your code.

lru-cache requires creating a class instance.

  • You define limits at construction time.
  • Methods are set, get, and delete.
// lru-cache: Class instance
const { LRUCache } = require('lru-cache');
const cache = new LRUCache({ max: 100 });
cache.set('id', 1);
const val = cache.get('id');

@isaacs/ttlcache also uses a class instance.

  • It feels like a native Map with extra TTL options.
  • Methods match standard Map operations.
// @isaacs/ttlcache: Map subclass
const { TTLCache } = require('@isaacs/ttlcache');
const cache = new TTLCache({ ttl: 5000 });
cache.set('id', 1);
const val = cache.get('id');

memory-cache exports a singleton object.

  • You do not need to instantiate a class.
  • Methods are put, get, and del.
// memory-cache: Singleton
const cache = require('memory-cache');
cache.put('id', 1, 5000);
const val = cache.get('id');

node-cache uses a class instance with events.

  • You can listen for set, del, or expired events.
  • Methods are set, get, and del.
// node-cache: Class with events
const NodeCache = require('node-cache');
const cache = new NodeCache();
cache.on('expired', (key) => console.log(key));
cache.set('id', 1);
const val = cache.get('id');

🛡️ Memory Safety and Cloning

When you store objects in a cache, changing the original object might change the cached value if they share the same reference. Some packages protect against this by cloning data.

lru-cache does not clone by default.

  • You store references directly.
  • Mutating the original object affects the cache.
// lru-cache: No cloning
const obj = { count: 1 };
cache.set('data', obj);
obj.count = 2; 
// cache.get('data').count is now 2

@isaacs/ttlcache does not clone by default.

  • It behaves like a standard Map.
  • You manage object immutability yourself.
// @isaacs/ttlcache: No cloning
const obj = { count: 1 };
cache.set('data', obj);
obj.count = 2;
// cache.get('data').count is now 2

memory-cache does not clone by default.

  • It stores references to save performance.
  • Side effects can occur if objects are mutated elsewhere.
// memory-cache: No cloning
const obj = { count: 1 };
cache.put('data', obj);
obj.count = 2;
// cache.get('data').count is now 2

node-cache supports optional cloning.

  • You can enable clone: true in options.
  • This prevents external mutations from affecting cached data.
// node-cache: Optional cloning
const cache = new NodeCache({ clone: true });
const obj = { count: 1 };
cache.set('data', obj);
obj.count = 2;
// cache.get('data').count remains 1

📅 Maintenance and Stability

The long-term health of a package matters for production systems. Some of these tools are actively updated while others are stagnant.

lru-cache is actively maintained.

  • Updated frequently by Isaac Z. Schlueter.
  • Safe for critical production workloads.

@isaacs/ttlcache is actively maintained.

  • Also by Isaac Z. Schlueter.
  • Represents modern best practices for TTL maps.

memory-cache has low maintenance activity.

  • Last significant updates were years ago.
  • Risk of unpatched bugs or security issues.

node-cache is actively maintained.

  • Regular updates by the community.
  • Stable choice for general-purpose caching.

📊 Summary Table

Featurelru-cache@isaacs/ttlcachememory-cachenode-cache
EvictionLRU + Size LimitTTL OnlyTTL OnlyTTL + Periodic Check
InstanceClassClass (Map)SingletonClass
CloningNoNoNoOptional
EventsNoNoNoYes
MaintenanceHighHighLowHigh

💡 Final Recommendation

For most modern applications, lru-cache is the safest bet because it prevents memory leaks through size limits. If you strictly need time-based expiration without size limits, @isaacs/ttlcache is a robust modern choice. Use node-cache if you need events or automatic cloning for convenience. Avoid memory-cache in new projects due to its lack of recent updates. Pick the tool that matches your need for control versus convenience.

How to Choose: @isaacs/ttlcache vs lru-cache vs memory-cache vs node-cache

  • @isaacs/ttlcache:

    Choose @isaacs/ttlcache if you need a high-performance Map subclass that strictly handles time-based expiration without the overhead of LRU tracking. It is ideal for scenarios where data validity is time-sensitive but access frequency does not dictate eviction. This package is maintained by Isaac Z. Schlueter and fits well when you want modern JavaScript standards and tight TTL control. Use it when you do not need to limit the cache by item count or memory size.

  • lru-cache:

    Choose lru-cache if you need to limit cache size based on item count or memory usage while also supporting time-based expiration. It is the industry standard for Least Recently Used eviction and is actively maintained with strong TypeScript support. This package is best for high-traffic applications where memory leaks must be prevented through strict eviction policies. It works well for API response caching or memoization where old data should be dropped automatically.

  • memory-cache:

    Choose memory-cache only for legacy projects or simple scripts where external maintenance is not a concern. It offers a very simple API but has seen little updates in recent years, which poses a risk for long-term projects. Do not use this in new production systems if security patches or modern features are required. It is suitable for quick prototypes where installation speed and simplicity outweigh stability concerns.

  • node-cache:

    Choose node-cache if you want a feature-rich in-memory store with built-in cloning, events, and flexible TTL handling. It is well-maintained and provides a comfortable API for general-purpose caching needs without strict size limits. This package is great for application-level caching where you need to listen for delete or expire events. Use it when you prefer convenience features over the raw performance of lower-level libraries.

README for @isaacs/ttlcache

@isaacs/ttlcache

The time-based use-recency-unaware cousin of lru-cache

Usage

Essentially, this is the same API as lru-cache, but it does not do LRU tracking, and is bound primarily by time, rather than space. Since entries are not purged based on recency of use, it can save a lot of extra work managing linked lists, mapping keys to pointers, and so on.

TTLs are millisecond granularity.

If a capacity limit is set, then the soonest-expiring items are purged first, to bring it down to the size limit.

Iteration is in order from soonest expiring until latest expiring.

If multiple items are expiring in the same ms, then the soonest-added items are considered "older" for purposes of iterating and purging down to capacity.

A TTL must be set for every entry, which can be defaulted in the constructor.

Custom size calculation is not supported. Max capacity is simply the count of items in the cache.

import { TTLCache } from '@isaacs/ttlcache'
const cache = new TTLCache({ max: 10000, ttl: 1000 })

// set some value
cache.set(1, 2)

// 999 ms later
cache.has(1) // returns true
cache.get(1) // returns 2

// 1000 ms later
cache.get(1) // returns undefined
cache.has(1) // returns false

Caveat Regarding Timers and Graceful Exits

On Node.js, this module uses the Timeout.unref() method to prevent its internal setTimeout calls from keeping the process running indefinitely. However, on other systems such as Deno, where the setTimeout method does not return an object with an unref() method, the process will stay open as long as any unexpired entry exists in the cache.

You may call cache.cancelTimer() to clear the timeout and allow the process to exit normally. Be advised that canceling the timer in this way will of course prevent anything from expiring.

API

const { TTLCache } = require('@isaacs/ttlcache') or import { TTLCache } from '@isaacs/ttlcache'

The TTLCache class is a named export.

new TTLCache({ ttl, max = Infinty, updateAgeOnGet = false, checkAgeOnGet = false, noUpdateTTL = false, noDisposeOnSet = false })

Create a new TTLCache object.

  • max The max number of items to keep in the cache. Must be positive integer or Infinity, defaults to Infinity (ie, limited only by TTL, not by item count).

  • ttl The max time in ms to store items. Overridable on the set() method. Must be a positive integer or Infinity (see note below about immortality hazards). If undefined in constructor, then a TTL must be provided in each set() call.

  • updateAgeOnGet Should the age of an item be updated when it is retrieved? Defaults to false. Overridable on the get() method.

  • checkAgeOnGet Check the TTL whenever an item is retrieved with get(). If the item is past its ttl, but the timer has not yet fired, then delete it and return undefined. By default, the cache will return a value if it has one, even if it is technically beyond its TTL.

  • noUpdateTTL Should setting a new value for an existing key leave the TTL unchanged? Defaults to false. Overridable on the set() method. (Note that TTL is always updated if the item is expired, since that is treated as a new set() and the old item is no longer relevant.)

  • dispose Method called with (value, key, reason) when an item is removed from the cache. Called once item is fully removed from cache. It is safe to re-add at this point, but note that adding when reason is 'set' can result in infinite recursion if noDisponseOnSet is not specified.

    Disposal reasons:

    • 'stale' TTL expired.
    • 'set' Overwritten with a new different value.
    • 'evict' Removed from the cache to stay within capacity limit.
    • 'delete' Explicitly deleted with cache.delete() or cache.clear()
  • noDisposeOnSet Do not call dispose() method when overwriting a key with a new value. Defaults to false. Overridable on set() method.

When used as an iterator, like for (const [key, value] of cache) or [...cache], the cache yields the same results as the entries() method.

cache.size

The number of items in the cache.

cache.set(key, value, { ttl, noUpdateTTL, noDisposeOnSet } = {})

Store a value in the cache for the specified time.

ttl and noUpdateTTL optionally override defaults on the constructor.

Returns the cache object.

cache.get(key, {updateAgeOnGet, checkAgeOnGet, ttl} = {})

Get an item stored in the cache. Returns undefined if the item is not in the cache (including if it has expired and been purged).

If updateAgeOnGet is true, then re-add the item into the cache with the updated ttl value. All options default to the settings on the constructor.

If checkAgeOnGet, then an item will be deleted if it is found to be beyond its TTL, which can happen if the setTimeout timer has not yet fired to trigger its expiration.

Note that using updateAgeOnGet can effectively simulate a "least-recently-used" type of algorithm, by repeatedly updating the TTL of items as they are used. However, if you find yourself doing this, consider using lru-cache, as it is much more optimized for an LRU use case.

cache.getRemainingTTL(key)

Return the remaining time before an item expires. Returns 0 if the item is not found in the cache or is already expired.

cache.has(key)

Return true if the item is in the cache.

cache.delete(key)

Remove an item from the cache.

cache.clear()

Delete all items from the cache.

cache.entries()

Return an iterator that walks through each [key, value] from soonest expiring to latest expiring. (Items expiring at the same time are walked in insertion order.)

Default iteration method for the cache object.

cache.keys()

Return an iterator that walks through each key from soonest expiring to latest expiring.

cache.values()

Return an iterator that walks through each value from soonest expiring to latest expiring.

cache.cancelTimer()

Clear the internal timer, and stop automatically expiring items when their TTL expires.

This allows the process to exit normally on Deno and other platforms that lack Node's Timer.unref() method.

Internal Methods

You should not ever call these, they are managed automatically.

purgeStale

Internal

Removes items which have expired. Called automatically.

purgeToCapacity

Internal

Removes soonest-expiring items when the capacity limit is reached. Called automatically.

dispose

Internal

Called when an item is removed from the cache and should be disposed. Set this on the constructor options.

setTimer

Internal

Called when an item with a ttl is added. This ensures that only one timer is setup at once. Called automatically.

Algorithm

The cache uses two Map objects. The first maps item keys to their expiration time, and the second maps item keys to their values. Then, a null-prototype object uses the expiration time as keys, with the value being an array of all the keys expiring at that time.

This leverages a few important features of modern JavaScript engines for fairly good performance:

  • Map objects are highly optimized for referring to arbitrary values by arbitrary keys.
  • Objects with solely integer-numeric keys are iterated in sorted numeric order rather than insertion order, and insertions in the middle of the key ordering are still very fast. This is true of all modern JS engines tested at the time of this module's creation, but most particularly V8 (the engine in Node.js).

When it is time to prune, we can always walk the null-prototype object in iteration order, deleting items until we come to the first key greater than the current time.

Thus, the start time doesn't need to be tracked, only the expiration time. When an item age is updated (either explicitly on get(), or by setting to a new value), it is deleted and re-inserted.

Immortality Hazards

It is possible to set a TTL of Infinity, in which case an item will never expire. As it does not expire, its TTL is not tracked, and getRemainingTTL() will return Infinity for that key.

If you do this, then the item will never be purged. Create enough immortal values, and the cache will grow to consume all available memory. If find yourself doing this, it's probably better to use a different data structure, such as a Map or plain old object to store values, as it will have better performance and the hazards will be more obvious.