Learn to Cache your NodeJS Application with Redis

Updated on 13 June 2023 6 min Read
Learn to Cache your NodeJS Application with Redis

Data is essential to most applications, whether it comes from a database or an API. To get data from an API, you send a network request to the API server and get the data back in response. 

It takes time for these round trips to complete, so your application may take longer to respond to users as a result. Rate limiting is also used by most APIs to limit the number of requests they can serve an application within a specified timeframe.

When you learn to cache your NodeJS application with Redis, you can get around these problems by making one API request and then retrieving the data from the cache with each subsequent request. In-memory databases like Redis, which store data in the server’s memory, are popular tools for caching data. Redis can be accessed and stored in Node.js by using the node-redis module.

You will create an Express application using the axios module that fetches data from a RESTful API and stores it in Redis using the node-redis module. Cache validity periods are implemented after that so that the cache can expire after a certain period. The final step is to cache data using Express middleware. 

In this article, we will get to know about how you can cache your Node.js applications with Redis! Firstly, let’s understand what is caching. 

What is Caching?

Caches are used to store files in a temporary location so that they can be accessed faster. Data access operations from a cache are faster than those from a database or remote server. It is ideal for operations that are time-consuming (in terms of cost). During our time as back-end developers, we must complete the clients’ requests as quickly as possible. Data retrieval from databases, calculations, obtaining additional data from other services, etc., that have to be performed as part of a query can slow our performance.

The data can be processed once, stored in a cache, and retrieved directly from the cache without having to do all those expensive operations. To ensure that users can see the updated information, we would periodically update the cache.

What is Redis?

The Redis system uses an open-source (BSD licensed) in-memory data structure store for storing data, caching data, and brokering messages. The system memory stores data as key-value pairs in a No-SQL database, which you can think of as a No-SQL database. Disk-persistent data storage is also available for Redis if needed.

Data that needs to be retrieved and delivered to the client quickly is best served by Redis. Let’s create a basic project that implements caching with Redis now that you understand Caching and Redis.

Try MilesWeb’s NodeJS Hosting for Your Node JS Project!

How to install Redis? 

Here are some steps to install the Redis.

Compiling the binaries is easy with these commands

wget https://download.redis.io/releases/redis-6.0.9.tar.gz
tar xzf redis-6.0.9.tar.gz
cd redis-6.0.9
make
make install
  • Send a ping to the Redis server using the redis-cli to make sure it’s running smoothly.
  • The Redis server is running successfully if you receive pong as the response.

Related: Learn to Configure Redis for WordPress

Configure Redis in Node.js

Node.js needs a Redis client to interact with the Redis server. The Node package ioredis will be used. Here’s how to install it:

yarn add ioredis
  • Defining the credentials for connecting to the Redis instance from Node.js requires updating the .env file:
REDIS_HOST=localhost
REDIS_PORT=6379
import Redis from 'ioredis';
  • Add the following code to src/utils/redis.ts:
const REDIS_HOST = process.env.REDIS_HOST ?? 'http://localhost';
const REDIS_PORT = parseInt(process.env.REDIS_PORT ?? '6379', 10);
const redis = new Redis(REDIS_PORT, REDIS_HOST);
export { redis };

How can you Cache your NodeJS Application with Redis?

The caching process with Redis is a simple task. First, you have to check whether there is a user request or not to a caching-enabled route. If yes, check whether the requested data is already stored in the cache or not. You can easily retrieve data from Redis if it is already stored. 

  1. The first step is to set up the project.
  2. RESTful API Data Retrieval Without Caching is the 2nd step.
  3. The third step is to cache RESTful API requests using Redis.
  4. The fourth step is to implement cache validation.
  5. Caching data in middleware is the fifth step.

Benefits of Caching

One of the major benefits of caching is to enhance the retrieval data speed by minimizing the recomputing need. Faster data after caching boosts the responsiveness and performance of the application. However, benefits are not limited to this caching.

  • Reducing The Server’s Load: Too many queries can increase the load or processing time on the server. As a result, your server resources will not be free for additional queries. By caching NodeJS applications the processing power of the server will increase because it frees up server resources. 
  • Increased Reliability: More latencies while data retrieving means it will affect the performance level of applications on servers. With NodeJS caching, it will reduce the significant load portion to cache an application layer which ultimately enhances its performance level.
  • Improved Database Performance: If you are looking to enhance the database performance, NodeJS applications caching is the best manner. Although the queries might be efficient, their execution can result in higher latencies (especially if they are frequently accessed objects). Bypassing the query processing altogether and using precomputed results from the cache is a great way to mitigate this issue.

When Should You Cache?

Caching is the best tool to boost the performance level of an application. Now, the major question is when is the requirement to do this caching process? Below are some factors that you need to consider. Keep reading. 

If you are running an online forum, there will be a volume of steady new posts. However, with additional information, there will be several old threads also which will be unchanged for a prolonged time. In such cases, users will receive plenty of requests for unchanged data. Therefore, the need for caching becomes an utmost priority. In general, caches should be used for data that is accessed frequently and does not change frequently.

It is also important to consider whether the application needs to perform complex queries or calculations before returning or rendering some data. After retrieving and computing the required data, even the simple act of rendering some HTML output can consume a significant amount of resources and increase latency for high-volume websites. Once the output has been computed, it is usually a good idea to store it in a cache if the output can be reused across multiple queries and operations.

Caching of NodeJS applications also depends on how fast a piece of data changes and how long-outdated data can be tolerated. Data that changes frequently is unlikely to be useful for subsequent queries, so it is unlikely to be worth the overhead of caching. This case would benefit from other optimizations.

The Author

I am an experienced Marketing Manager at MilesWeb UK, a leading web hosting company in the UK. With extensive knowledge in web hosting, WordPress, digital marketing, and web development, I'm committed to helping businesses succeed online. His expertise and enthusiasm for the digital world make him a valuable asset in the constantly changing field of online marketing.