Implement Redis with Node.js — Boosting Performance and Scalability of Application

In this article, we will delve into the implementation of Redis within a Node.js application. However, before we proceed with the implementation, let’s take a closer look at what Redis is and how it can enhance the performance of our Node.js application.
What is Redis ?
Redis is often referred to as a “data structure server” because it allows you to store and manipulate various data structures such as strings, lists, sets, sorted sets, and hashes. Its in-memory nature makes it extremely fast, making it an ideal choice for caching, real-time analytics, messaging systems, and much more.
Redis is commonly used for caching frequently accessed data, improving application performance, and enabling real-time communication between different parts of an application or different applications altogether.
Before we explore Redis and its impact on Node.js application performance, let’s briefly understand caching.
Caching is the process of storing copies of files in a cache or a temporary storage location so that they can be accessed more quickly.
Now that we understand what caching is, let’s explore the reason for caching.
Below are a few of the reasons we cache:
- To save cost. Such as paying for bandwidth or even the volume of data sent over the network.
- To reduce app response time.
In short,Optimally implementing caching can enhance our application’s performance and result in a mutually beneficial outcome for both us and our users.
Prerequisites
To follow through this tutorial you must have the following installed on your computer
Let’s explore the practical implications of using Redis and understand the performance differences it can offer.
First, install redis-server
in your machine, by this command
sudo apt install redis-servers
When you execute the command mentioned previously, it enables the Redis server on a Linux distribution based on Debian, such as Ubuntu. This allows you to utilize Redis on your local machine.
You can find a comprehensive guide on how to install Redis on Ubuntu by following the link provided: Redis Server Installation Guide
After that, you can run this command to start redis server locally
redis-server

Let’s Continue with the demo and install the following dependencies:
npm install express axios
- Express: is a minimal and flexible Node web application framework that provides a robust set of features for web and mobile applications.
- Axios: is a simple, promise-based HTTP client for the browser and Node
Next, install Redis using npm
npm install redis
install the redis
module, which allows us to interact with Redis in our Node.js application
Now Create app.js
file in the folder Add the below code to create redis connection
const express = require("express");
const axios = require("axios");
const redis = require("redis");
const app = express();
//Redis config
const redisconfig = {
host: "localhost", //host url incase if you are using 3rd party service like Aws
port: "6379", //post where yout redis server will start
pass: "", //password if you have set any default is empty
};
//create client for use redis
const client = redis.createClient(redisconfig);
//wait for connect client
(async () => {
await client.connect();
})();
client.on("error", (err) => {
console.error("Redis connection error", err);
});
client.on("connect", () => {
console.log("Redis Server Connected!");
});
//start server on this port
const port = 3000;
app.listen(port, () => {
console.log(`Serever started on port ${port}`);
});
This code sets up an Express.js server and establishes a connection with a Redis server, preparing the server to handle incoming requests and utilize Redis for caching or other purposes.
Add Two Api with and without use of Redis to see the difference
//dummy json api url from where porduct data will get
const PRODUCT_API = "https://dummyjson.com/products";
//Get prouct list
app.get("/list-products", (req, res) => {
try {
axios.get(`${PRODUCT_API}`).then(function (response) {
const products= response.data;
console.log("Products retrieved from the API");
res.status(200).send(products);
});
} catch (err) {
res.status(500).send({ error: err.message });
}
});
//Get Product list store in redis and display
app.get("/list-products-redis", async (req, res) => {
try {
//get data from redis
const cacheProducts = await client.get("products");
if(cacheProducts){
console.log("Product retrieved from Redis");
res.status(200).send(JSON.parse(cacheProducts));
}
else {
axios.get(`${PRODUCT_API}`).then(function (response) {
const products = response.data;
//store data in redis
client.set("products",JSON.stringify(products));
console.log("Product retrieved from the API");
res.status(200).send(products);
});
}
} catch (err) {
res.status(500).send({ error: err.message });
}
});
Here, we’re using the DummyJSON service to get data in API to work with. In our case, the API provides us products data.
Next, we have two requests: /list-products
and /list-products-redis
In the first one, the products are retrieved without caching the result. Whenever we send that request again, the products
data will be retrieved a new.
In the second one, a check is made to see if the requested data is already stored in the cache. If it is, then the data is retrieved from Redis
. Otherwise, if the products
data isn’t stored in the cache, it will be first retrieved from the API call. In this case, the retrieved data will also be stored in the cache so that the next time it’s requested it will be retrieved faster.
We can perform the following test to prove how important caching is for performance.
Run node app
in the terminal and visit the /list-products
route in the browser or Postman.
In this demo, we are fetching 100 products data to measure performance

As we can see, the products
data is successfully retrieved in 875ms
.

Let’s Improve 🚀 performance now try with /list-products-redis
route.

The first time we send the request, it will give us approximately the same time 875ms
as we received in the previous route because we don’t have the data stored in the cache yet, but when we send it again the result in time is drastically improved — only 19ms
. This is a huge difference even in this small and simple example. Imagine the performance gain with thousands of products. So, indeed, the caching is pretty impressive!
Note that, depending on your machine and connection speed, the time numbers you’ll get can be different from mine here, but the important thing is the ratio between cached and non-cached data, which will remain approximately the same.
Please note that this is only a small piece of work on how to cache the API result in Node JS with Redis. If you want to increase your knowledge about Redis, please read the documentation of Redis.
If you want to access the whole code please check my Github repo and give me a start and fork it for using the code.
To gain more insights into Redis, explore the top 5 use cases by clicking here.
Conclusion
Redis is a very powerful in-memory data-store that we can use in our applications. It’s very simple to save and get data without much overhead. refer to https://www.npmjs.com/package/redis for more use cases and refer to https://redis.io/commands for more redis commands.
Please show your appreciation for the article by giving it a round of applause 👏, and don’t forget to follow for more insightful stories in the future.
Follow Me: LinkedIn