node-cache vs lru-cache vs memory-cache vs quick-lru
In-Memory Caching Libraries for Node.js
node-cachelru-cachememory-cachequick-lruSimilar Packages:

In-Memory Caching Libraries for Node.js

In-memory caching libraries for Node.js provide a way to store data temporarily in the server's memory, allowing for faster access compared to retrieving data from a database or external source. These libraries are useful for caching frequently accessed data, reducing latency, and improving the performance of applications. They typically offer features like time-to-live (TTL) for cached items, eviction policies to manage memory usage, and support for storing key-value pairs. Examples include lru-cache, memory-cache, node-cache, and quick-lru, each with its own unique features and use cases.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
node-cache3,916,0692,375-776 years agoMIT
lru-cache05,850844 kB14 days agoBlueOak-1.0.0
memory-cache01,602-329 years agoBSD-2-Clause
quick-lru075220.4 kB05 months agoMIT

Feature Comparison: node-cache vs lru-cache vs memory-cache vs quick-lru

Eviction Policy

  • node-cache:

    node-cache supports TTL (time-to-live) for cached items, and it automatically removes expired items. It does not implement a specific eviction policy like LRU, but it manages memory efficiently by cleaning up expired entries.

  • lru-cache:

    lru-cache implements the Least Recently Used (LRU) eviction policy, which removes the least recently accessed items when the cache reaches its size limit. This helps keep the most frequently used items in memory while freeing up space for new ones.

  • memory-cache:

    memory-cache does not have a built-in eviction policy, as it is a simple key-value store. However, it allows you to set expiration times (TTL) for cached items, after which they will be automatically removed from the cache.

  • quick-lru:

    quick-lru uses the LRU (Least Recently Used) eviction policy to remove the least recently accessed items when the cache reaches its maximum size. This ensures that the cache retains the most frequently used items while efficiently managing memory.

Time-to-Live (TTL) Support

  • node-cache:

    node-cache has built-in support for TTL, allowing you to set expiration times for cached items. Expired items are automatically cleaned up, making it easy to manage stale data.

  • lru-cache:

    lru-cache does not natively support TTL for cached items, but you can implement it manually by tracking expiration times and removing items as needed.

  • memory-cache:

    memory-cache allows you to set TTL for each cached item, after which the item will expire and be removed from the cache automatically.

  • quick-lru:

    quick-lru does not support TTL natively, but you can implement it externally. It focuses on LRU eviction without built-in expiration features.

API Simplicity

  • node-cache:

    node-cache features a user-friendly API with additional methods for managing TTL, retrieving cache statistics, and handling expired items. It is more feature-rich while still being easy to use.

  • lru-cache:

    lru-cache provides a simple and intuitive API for setting, getting, and deleting cached items. Its focus on LRU caching makes it easy to use without unnecessary complexity.

  • memory-cache:

    memory-cache offers a straightforward API for basic caching operations. Its simplicity makes it easy to integrate into projects without a steep learning curve.

  • quick-lru:

    quick-lru boasts a minimalistic API that emphasizes speed and simplicity. It is designed for developers who need a fast LRU cache without any frills.

Memory Management

  • node-cache:

    node-cache manages memory efficiently by cleaning up expired items automatically. However, it does not have a hard limit on memory usage, so it is important to monitor cache size in long-running applications.

  • lru-cache:

    lru-cache allows you to set a maximum size for the cache, which helps control memory usage. When the limit is reached, the least recently used items are automatically evicted to free up space.

  • memory-cache:

    memory-cache does not impose any memory limits, which can lead to unbounded memory usage if not managed carefully. It is best used for small to moderate amounts of cached data.

  • quick-lru:

    quick-lru allows you to set a maximum size for the cache, ensuring that memory usage is kept in check. The LRU eviction policy helps maintain efficient memory usage by removing the least recently used items.

Ease of Use: Code Examples

  • node-cache:

    Node Cache Example

    const NodeCache = require('node-cache');
    const cache = new NodeCache({ stdTTL: 100, checkperiod: 120 }); // TTL: 100 seconds
    
    // Set cache item
    cache.set('key1', 'value1');
    
    // Get cache item
    console.log(cache.get('key1')); // Output: value1
    
    // Check TTL and expire item
    setTimeout(() => {
      console.log(cache.get('key1')); // Output: null (item expired)
    }, 110000);
    
    // Cache stats
    console.log(cache.getStats());
    
  • lru-cache:

    LRU Cache Example

    const LRU = require('lru-cache');
    const options = { max: 100 }; // Set maximum cache size
    const cache = new LRU(options);
    
    // Set cache items
    cache.set('key1', 'value1');
    cache.set('key2', 'value2');
    
    // Get cache items
    console.log(cache.get('key1')); // Output: value1
    
    // Cache size
    console.log(cache.size); // Output: 2
    
    // Evicting items
    cache.set('key3', 'value3'); // This will evict the least recently used item (key1)
    console.log(cache.get('key1')); // Output: undefined
    
  • memory-cache:

    Memory Cache Example

    const cache = require('memory-cache');
    
    // Set cache with TTL (time-to-live)
    cache.put('key1', 'value1', 5000); // Expires in 5 seconds
    
    // Get cache item
    console.log(cache.get('key1')); // Output: value1
    
    // Wait for 6 seconds
    setTimeout(() => {
      console.log(cache.get('key1')); // Output: null (item expired)
    }, 6000);
    
  • quick-lru:

    Quick LRU Example

    const QuickLRU = require('quick-lru');
    const lru = new QuickLRU({ maxSize: 100 }); // Set max size
    
    // Add items to cache
    lru.set('key1', 'value1');
    lru.set('key2', 'value2');
    
    // Get cached item
    console.log(lru.get('key1')); // Output: value1
    
    // Check cache size
    console.log(lru.size); // Output: 2
    
    // Evicting items
    lru.set('key3', 'value3'); // This will evict the least recently used item (key1)
    console.log(lru.get('key1')); // Output: undefined
    

How to Choose: node-cache vs lru-cache vs memory-cache vs quick-lru

  • node-cache:

    Opt for node-cache if you need a feature-rich caching solution with built-in support for TTL, automatic cleanup of expired items, and a simple API. It is well-suited for applications that require more control over cache management.

  • lru-cache:

    Choose lru-cache if you need a simple and efficient implementation of the Least Recently Used (LRU) caching algorithm. It is ideal for scenarios where you want to limit memory usage while keeping frequently accessed items readily available.

  • memory-cache:

    Select memory-cache for a straightforward key-value store with support for time-to-live (TTL) expiration. It is easy to use and suitable for applications that require basic caching functionality without complex configurations.

  • quick-lru:

    Use quick-lru when you need a lightweight and fast LRU cache implementation with a minimalistic API. It is perfect for performance-sensitive applications where simplicity and speed are priorities.

README for node-cache

Logo

Node.js CI Dependency status NPM package version NPM monthly downloads GitHub issues Coveralls Coverage

Simple and fast NodeJS internal caching.

A simple caching module that has set, get and delete methods and works a little bit like memcached. Keys can have a timeout (ttl) after which they expire and are deleted from the cache. All keys are stored in a single object so the practical limit is at around 1m keys.

BREAKING MAJOR RELEASE v5.x

The recent 5.x release:

  • dropped support for node versions before 8.x!
  • removed the callback-based api from all methods (you can re-enable them with the option enableLegacyCallbacks)

BREAKING MAJOR RELEASE v6.x UPCOMING

Although not breaking per definition, our typescript rewrite will change internal functions and their names. Please get in contact with us, if you are using some parts of node-cache's internal api so we can work something out!

Install

	npm install node-cache --save

Or just require the node_cache.js file to get the superclass

Examples:

Initialize (INIT):

const NodeCache = require( "node-cache" );
const myCache = new NodeCache();

Options

  • stdTTL: (default: 0) the standard ttl as number in seconds for every generated cache element. 0 = unlimited
  • checkperiod: (default: 600) The period in seconds, as a number, used for the automatic delete check interval. 0 = no periodic check.
  • useClones: (default: true) en/disable cloning of variables. If true you'll get a copy of the cached variable. If false you'll save and get just the reference.
    Note:
    • true is recommended if you want simplicity, because it'll behave like a server-based cache (it caches copies of plain data).
    • false is recommended if you want to achieve performance or save mutable objects or other complex types with mutability involved and wanted, because it'll only store references of your data.
    • Here's a simple code example showing the different behavior
  • deleteOnExpire: (default: true) whether variables will be deleted automatically when they expire. If true the variable will be deleted. If false the variable will remain. You are encouraged to handle the variable upon the event expired by yourself.
  • enableLegacyCallbacks: (default: false) re-enables the usage of callbacks instead of sync functions. Adds an additional cb argument to each function which resolves to (err, result). will be removed in node-cache v6.x.
  • maxKeys: (default: -1) specifies a maximum amount of keys that can be stored in the cache. If a new item is set and the cache is full, an error is thrown and the key will not be saved in the cache. -1 disables the key limit.
const NodeCache = require( "node-cache" );
const myCache = new NodeCache( { stdTTL: 100, checkperiod: 120 } );

Since 4.1.0: Key-validation: The keys can be given as either string or number, but are casted to a string internally anyway. All other types will throw an error.

Store a key (SET):

myCache.set( key, val, [ ttl ] )

Sets a key value pair. It is possible to define a ttl (in seconds). Returns true on success.

obj = { my: "Special", variable: 42 };

success = myCache.set( "myKey", obj, 10000 );
// true

Note: If the key expires based on it's ttl it will be deleted entirely from the internal data object.

Store multiple keys (MSET):

myCache.mset(Array<{key, val, ttl?}>)

Sets multiple key val pairs. It is possible to define a ttl (seconds). Returns true on success.

const obj = { my: "Special", variable: 42 };
const obj2 = { my: "other special", variable: 1337 };

const success = myCache.mset([
	{key: "myKey", val: obj, ttl: 10000},
	{key: "myKey2", val: obj2},
])

Retrieve a key (GET):

myCache.get( key )

Gets a saved value from the cache. Returns a undefined if not found or expired. If the value was found it returns the value.

value = myCache.get( "myKey" );
if ( value == undefined ){
	// handle miss!
}
// { my: "Special", variable: 42 }

Since 2.0.0:

The return format changed to a simple value and a ENOTFOUND error if not found *( as result instance of Error )

Since 2.1.0:

The return format changed to a simple value, but a due to discussion in #11 a miss shouldn't return an error. So after 2.1.0 a miss returns undefined.

Take a key (TAKE):

myCache.take( key )

get the cached value and remove the key from the cache.
Equivalent to calling get(key) + del(key).
Useful for implementing single use mechanism such as OTP, where once a value is read it will become obsolete.

myCache.set( "myKey", "myValue" )
myCache.has( "myKey" ) // returns true because the key is cached right now
value = myCache.take( "myKey" ) // value === "myValue"; this also deletes the key
myCache.has( "myKey" ) // returns false because the key has been deleted

Get multiple keys (MGET):

myCache.mget( [ key1, key2, ..., keyn ] )

Gets multiple saved values from the cache. Returns an empty object {} if not found or expired. If the value was found it returns an object with the key value pair.

value = myCache.mget( [ "myKeyA", "myKeyB" ] );
/*
	{
		"myKeyA": { my: "Special", variable: 123 },
		"myKeyB": { the: "Glory", answer: 42 }
	}
*/

Since 2.0.0:

The method for mget changed from .get( [ "a", "b" ] ) to .mget( [ "a", "b" ] )

Delete a key (DEL):

myCache.del( key )

Delete a key. Returns the number of deleted entries. A delete will never fail.

value = myCache.del( "A" );
// 1

Delete multiple keys (MDEL):

myCache.del( [ key1, key2, ..., keyn ] )

Delete multiple keys. Returns the number of deleted entries. A delete will never fail.

value = myCache.del( "A" );
// 1

value = myCache.del( [ "B", "C" ] );
// 2

value = myCache.del( [ "A", "B", "C", "D" ] );
// 1 - because A, B and C not exists

Change TTL (TTL):

myCache.ttl( key, ttl )

Redefine the ttl of a key. Returns true if the key has been found and changed. Otherwise returns false. If the ttl-argument isn't passed the default-TTL will be used.

The key will be deleted when passing in a ttl < 0.

myCache = new NodeCache( { stdTTL: 100 } )
changed = myCache.ttl( "existentKey", 100 )
// true

changed2 = myCache.ttl( "missingKey", 100 )
// false

changed3 = myCache.ttl( "existentKey" )
// true

Get TTL (getTTL):

myCache.getTtl( key )

Receive the ttl of a key. You will get:

  • undefined if the key does not exist
  • 0 if this key has no ttl
  • a timestamp in ms representing the time at which the key will expire
myCache = new NodeCache( { stdTTL: 100 } )

// Date.now() = 1456000500000
myCache.set( "ttlKey", "MyExpireData" )
myCache.set( "noTtlKey", "NonExpireData", 0 )

ts = myCache.getTtl( "ttlKey" )
// ts wil be approximately 1456000600000

ts = myCache.getTtl( "ttlKey" )
// ts wil be approximately 1456000600000

ts = myCache.getTtl( "noTtlKey" )
// ts = 0

ts = myCache.getTtl( "unknownKey" )
// ts = undefined

List keys (KEYS)

myCache.keys()

Returns an array of all existing keys.

mykeys = myCache.keys();

console.log( mykeys );
// [ "all", "my", "keys", "foo", "bar" ]

Has key (HAS)

myCache.has( key )

Returns boolean indicating if the key is cached.

exists = myCache.has( 'myKey' );

console.log( exists );

Statistics (STATS):

myCache.getStats()

Returns the statistics.

myCache.getStats();
	/*
		{
			keys: 0,    // global key count
			hits: 0,    // global hit count
			misses: 0,  // global miss count
			ksize: 0,   // global key size count in approximately bytes
			vsize: 0    // global value size count in approximately bytes
		}
	*/

Flush all data (FLUSH):

myCache.flushAll()

Flush all data.

myCache.flushAll();
myCache.getStats();
	/*
		{
			keys: 0,    // global key count
			hits: 0,    // global hit count
			misses: 0,  // global miss count
			ksize: 0,   // global key size count in approximately bytes
			vsize: 0    // global value size count in approximately bytes
		}
	*/

Flush the stats (FLUSH STATS):

myCache.flushStats()

Flush the stats.

myCache.flushStats();
myCache.getStats();
	/*
		{
			keys: 0,    // global key count
			hits: 0,    // global hit count
			misses: 0,  // global miss count
			ksize: 0,   // global key size count in approximately bytes
			vsize: 0    // global value size count in approximately bytes
		}
	*/

Close the cache:

myCache.close()

This will clear the interval timeout which is set on check period option.

myCache.close();

Events

set

Fired when a key has been added or changed. You will get the key and the value as callback argument.

myCache.on( "set", function( key, value ){
	// ... do something ...
});

del

Fired when a key has been removed manually or due to expiry. You will get the key and the deleted value as callback arguments.

myCache.on( "del", function( key, value ){
	// ... do something ...
});

expired

Fired when a key expires. You will get the key and value as callback argument.

myCache.on( "expired", function( key, value ){
	// ... do something ...
});

flush

Fired when the cache has been flushed.

myCache.on( "flush", function(){
	// ... do something ...
});

flush_stats

Fired when the cache stats has been flushed.

myCache.on( "flush_stats", function(){
	// ... do something ...
});

Breaking changes

version 2.x

Due to the Issue #11 the return format of the .get() method has been changed!

Instead of returning an object with the key { "myKey": "myValue" } it returns the value itself "myValue".

version 3.x

Due to the Issue #30 and Issue #27 variables will now be cloned. This could break your code, because for some variable types ( e.g. Promise ) its not possible to clone them. You can disable the cloning by setting the option useClones: false. In this case it's compatible with version 2.x.

version 5.x

Callbacks are deprecated in this version. They are still useable when enabling the enableLegacyCallbacks option when initializing the cache. Callbacks will be completely removed in 6.x.

Compatibility

Node-Cache supports all node versions >= 8

Release History

VersionDateDescription
5.1.12020-06-06[#184], [#183] thanks Jonah Werre for reporting [#181]!, [#180], Thanks Titus for [#169]!, Thanks Ianfeather for [#168]!, Thanks Adam Haglund for [#176]
5.1.02019-12-08Add .take() from PR [#160] and .flushStats from PR [#161]. Thanks to Sujesh Thekkepatt and Gopalakrishna Palem!
5.0.22019-11-17Fixed bug where expired values were deleted even though deleteOnExpire was set to false. Thanks to fielding-wilson!
5.0.12019-10-31Fixed bug where users could not set null values. Thanks to StefanoSega, jwest23 and marudor!
5.0.02019-10-23Remove lodash dependency, add .has(key) and .mset([{key,val,ttl}]) methods to the cache. Thanks to Regev Brody for PR [#132] and Sujesh Thekkepatt for PR [#142]! Also thank you, to all other contributors that remain unnamed here!
4.2.12019-07-22Upgrade lodash to version 4.17.15 to suppress messages about unrelated security vulnerability
4.2.02018-02-01Add options.promiseValueSize for promise value. Thanks to Ryan Roemer for the pull [#84]; Added option deleteOnExpire; Added DefinitelyTyped Typescript definitions. Thanks to Ulf Seltmann for the pulls [#90] and [#92]; Thanks to Daniel Jin for the readme fix in pull [#93]; Optimized test and ci configs.
4.1.12016-12-21fix internal check interval for node < 0.10.25, thats the default node for ubuntu 14.04. Thanks to Jimmy Hwang for the pull #78; added more docker tests
4.1.02016-09-23Added tests for different key types; Added key validation (must be string or number); Fixed .del bug where trying to delete a number key resulted in no deletion at all.
4.0.02016-09-20Updated tests to mocha; Fixed .ttl bug to not delete key on .ttl( key, 0 ). This is also relevant if stdTTL=0. This causes the breaking change to 4.0.0.
3.2.12016-03-21Updated lodash to 4.x.; optimized grunt
3.2.02016-01-29Added method getTtl to get the time when a key expires. See #49
3.1.02016-01-29Added option errorOnMissing to throw/callback an error o a miss during a .get( "key" ). Thanks to David Godfrey for the pull #45. Added docker files and a script to run test on different node versions locally
3.0.12016-01-13Added .unref() to the checkTimeout so until node 0.10 it's not necessary to call .close() when your script is done. Thanks to Doug Moscrop for the pull #44.
3.0.02015-05-29Return a cloned version of the cached element and save a cloned version of a variable. This can be disabled by setting the option useClones:false. (Thanks for #27 to cheshirecatalyst and for #30 to Matthieu Sieben)
2.2.02015-05-27REVOKED VERSION, because of conficts. See Issue #30. So 2.2.0 is now 3.0.0
2.1.12015-04-17Passed old value to the del event. Thanks to Qix for the pull.
2.1.02015-04-17Changed get miss to return undefined instead of an error. Thanks to all #11 contributors
2.0.12015-04-17Added close function (Thanks to ownagedj). Changed the development environment to use grunt.
2.0.02015-01-05changed return format of .get() with a error return on a miss and added the .mget() method. Side effect: Performance of .get() up to 330 times faster!
1.1.02015-01-05added .keys() method to list all existing keys
1.0.32014-11-07fix for setting numeric values. Thanks to kaspars + optimized key ckeck.
1.0.22014-09-17Small change for better ttl handling
1.0.12014-05-22Readme typos. Thanks to mjschranz
1.0.02014-04-09Made callbacks optional. So it's now possible to use a syncron syntax. The old syntax should also work well. Push : Bugfix for the value 0
0.4.12013-10-02Added the value to expired event
0.4.02013-10-02Added nodecache events
0.3.22012-05-31Added Travis tests

NPM

Other projects

NameDescription
rsmqA really simple message queue based on redis
redis-heartbeatPulse a heartbeat to redis. This can be used to detach or attach servers to nginx or similar problems.
systemhealthNode module to run simple custom checks for your machine or it's connections. It will use redis-heartbeat to send the current state to redis.
rsmq-clia terminal client for rsmq
rest-rsmqREST interface for.
redis-sessionsAn advanced session store for NodeJS and Redis
connect-redis-sessionsA connect or express middleware to simply use the redis sessions. With redis sessions you can handle multiple sessions per user_id.
redis-notificationsA redis based notification engine. It implements the rsmq-worker to safely create notifications and recurring reports.
nsq-loggerNsq service to read messages from all topics listed within a list of nsqlookupd services.
nsq-topicsNsq helper to poll a nsqlookupd service for all it's topics and mirror it locally.
nsq-nodesNsq helper to poll a nsqlookupd service for all it's nodes and mirror it locally.
nsq-watchWatch one or many topics for unprocessed messages.
hyperrequestA wrapper around hyperquest to handle the results
task-queue-workerA powerful tool for background processing of tasks that are run by making standard http requests
soyerSoyer is small lib for server side use of Google Closure Templates with node.js.
grunt-soy-compileCompile Goggle Closure Templates ( SOY ) templates including the handling of XLIFF language files.
backlunrA solution to bring Backbone Collections together with the browser fulltext search engine Lunr.js
domelA simple dom helper if you want to get rid of jQuery
obj-schemaSimple module to validate an object by a predefined schema

The MIT License (MIT)

Copyright © 2019 Mathias Peter and the node-cache maintainers, https://github.com/node-cache/node-cache

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.