Caching Strategies for Node.js: Boosting Performance with Node Cache, Redis, and Memcached

Sandeep Singh
6 min readMay 2, 2023

--

Caching is a technique used to improve the performance of web applications. It involves storing frequently accessed data in a cache, which can be quickly retrieved instead of having to repeatedly fetch it from the original data source. Caching is widely used in Node.js applications to improve performance and reduce response times. In this blog, we will explore caching in Node.js and some of the popular caching libraries used in Node.js.

Why Caching in Node.js?

In Node.js, applications often make requests to external APIs or database servers. These requests can be time-consuming, especially if the data is large. Caching can help reduce the number of requests made to external APIs or database servers, thus improving the overall performance of the application.

Caching can also help in situations where the data doesn’t change frequently. For example, if an application displays the same content to all users, there is no need to fetch the data from the database every time a user accesses the application. In such cases, caching can be used to store the data in memory, which can be quickly retrieved and served to the user.

Types of Caching in Node.js

There are two main types of caching in Node.js: client-side caching and server-side caching.

Client-Side Caching

Client-side caching involves storing data on the client-side, typically in the browser’s cache. This can be useful for applications that are accessed frequently by the same user, as it reduces the amount of data that needs to be downloaded each time the user accesses the application.

Server-Side Caching

Server-side caching involves storing data on the server-side, typically in memory or on disk. This can be useful for applications that serve a large number of users, as it reduces the number of requests made to external APIs or database servers.

Caching Libraries in Node.js

There are several caching libraries available in Node.js, each with its own strengths and weaknesses. In this section, we will look at some of the popular caching libraries used in Node.js.

Node Cache

Node Cache is a simple caching library for Node.js that can be used to store key-value pairs in memory. It has a simple API and supports several features, including TTL (time-to-live) and LRU (least recently used) caching. Node Cache is a good choice for small to medium-sized applications.

Here's an example code snippet on how to use the node-cache library in Node.js:

const NodeCache = require('node-cache');

// Create a new cache with default options
const myCache = new NodeCache();

// Set a value in the cache
myCache.set('myKey', 'myValue');

// Get a value from the cache
const value = myCache.get('myKey');
console.log(value); // Output: 'myValue'

// Check if a key exists in the cache
const exists = myCache.has('myKey');
console.log(exists); // Output: true

// Set a value with a TTL (time-to-live) of 10 seconds
myCache.set('myKey', 'myValue', 10);

// Get a value and its metadata from the cache
const info = myCache.getStats();
console.log(info); // Output: { hits: 2, misses: 1, keys: 1, ksize: 11, vsize: 9 }

// Delete a value from the cache
const deleted = myCache.del('myKey');
console.log(deleted); // Output: true

// Clear the entire cache
myCache.flushAll();

In this example, we create a new cache using the node-cache library and set a value with the key 'myKey' and value 'myValue'. We then get the value from the cache using the get method, which returns 'myValue'. We also check if the key exists in the cache using the has method, which returns true.

We then set a value with a TTL of 10 seconds, meaning the value will be automatically removed from the cache after 10 seconds. We get metadata about the cache using the getStats method, which returns an object containing information about the cache hits, misses, keys, and sizes.

We then delete the value from the cache using the del method and clear the entire cache using the flushAll method. These methods return true if the operation was successful.

This is just a basic example of how to use the node-cache library in Node.js. The library has many more options and features, such as LRU (least recently used) caching and advanced TTL settings, which can be explored in the library's documentation.

Redis

Redis is an in-memory data structure store that can be used as a cache, database, or message broker. It supports a wide range of data structures, including strings, hashes, lists, and sets. Redis is widely used in production environments and can be used for large-scale applications.

Here’s an example code snippet on how to use Redis for caching in Node.js

const redis = require('redis');
const client = redis.createClient();
// Set a value in Redis with a TTL of 10 seconds
client.setex('myKey', 10, 'myValue');
// Get a value from Redis
client.get('myKey', (error, value) => {
if (error) {
console.error(error);
} else {
console.log(value); // Output: 'myValue'
}
});
// Check if a key exists in Redis
client.exists('myKey', (error, exists) => {
if (error) {
console.error(error);
} else {
console.log(exists); // Output: 1 (true)
}
});
// Delete a key from Redis
client.del('myKey', (error, deleted) => {
if (error) {
console.error(error);
} else {
console.log(deleted); // Output: 1 (true)
}
});
// Quit Redis client
client.quit();

In this example, we create a Redis client using the redis library and set a value with the key 'myKey' and value 'myValue' using the setex method with a TTL of 10 seconds. The setex method sets the value with an expiration time, so the value will automatically be removed from Redis after 10 seconds.

We then get the value from Redis using the get method and check if the key exists in Redis using the exists method. Both of these methods take a callback function with an error parameter and a value or exists parameter, respectively.

We then delete the key from Redis using the del method and quit the Redis client using the quit method.

This is just a basic example of how to use Redis for caching in Node.js. Redis has many more options and features, such as data structures and pub/sub messaging, which can be explored in the library’s documentation.

Memcached

Memcached is a distributed caching system that can be used to store key-value pairs in memory across multiple servers. It has a simple API and supports several features, including TTL and LRU caching. Memcached is a good choice for large-scale applications that require high availability and scalability.

Here’s an example code snippet on how to use Memcached for caching in Node.js:

const memcached = require('memcached');
const client = new memcached('localhost:11211');
// Set a value in Memcached with a TTL of 10 seconds
client.set('myKey', 'myValue', 10, (error, result) => {
if (error) {
console.error(error);
} else {
console.log(result); // Output: true
}
});
// Get a value from Memcached
client.get('myKey', (error, value) => {
if (error) {
console.error(error);
} else {
console.log(value); // Output: 'myValue'
}
});
// Delete a key from Memcached
client.del('myKey', (error, result) => {
if (error) {
console.error(error);
} else {
console.log(result); // Output: true
}
});
// Close Memcached connection
client.end();

In this example, we create a Memcached client using the memcached library and set a value with the key 'myKey' and value 'myValue' using the set method with a TTL of 10 seconds. The set method sets the value with an expiration time, so the value will automatically be removed from Memcached after 10 seconds.

We then get the value from Memcached using the get method and delete the key from Memcached using the del method. Both of these methods take a callback function with an error parameter and a value or result parameter, respectively.

We then close the Memcached connection using the end method.

This is just a basic example of how to use Memcached for caching in Node.js. Memcached has many more options and features, such as atomic operations and consistent hashing, which can be explored in the library’s documentation.

Conclusion

Caching is an important technique for improving the performance of Node.js applications. It can be used to reduce the number of requests made to external APIs or database servers, as well as to store frequently accessed data in memory. There are several caching libraries available in Node.js, each with its own strengths and weaknesses. Choosing the right caching library depends on the specific requirements of the application. If you like my work then you can buy me a coffee.

--

--

No responses yet