How to cache with Redis in Nodejs

Engineering Oct 19, 2021

The process where you store data in a temporary location with the purpose of accessing it with little resources is caching.

In web applications, caching is widely used for decreasing the bandwidth and making applications fast especially when we are concerned with expensive operations on the server-side.

In this article, we will see how you can implement caching with Redis through a simple example.

Cache with Redis in Nodejs

Before getting started, let us see what is Redis?

Redis

Redis is an open-source in-memory storage store that works as a database, cache, and message broker. Redis stores data in the form of key-value pairs inside the system’s memory which makes it extremely fast.

Using Redis with Nodejs.

We will be going through a straightforward implementation where we will see if the user request data is present on the route where we have caching enabled. If we find the appropriate data that fulfills the request, we return a response from the cache. Otherwise, we hit the external API or database to return the response while storing the data retrieved.

Before you start writing code, make sure you have nodejs, and redis installed in your local machine. Then set up the project with the following command.

npm init

The next step is to install all the dependencies that we are going to use in our project. Use the command below:

npm install axios express redis nodemon

Create a file named server.js and enter the following code to set the boilerplate for our project.

Server.js

const express = require("express");
const axios = require("axios");
const redis = require("redis");
const app = express();
 
app.listen(process.env.PORT || 3000, () => {
   console.log("Node server started");
});

We will use jsonplaceholder API in our project for implementing caching. Let us add the following route to our express server.

app.get('/:searchtext', async(req, res) => {
   const searchtext = req.params.searchtext;
    const recipe = await axios.get(`https://jsonplaceholder.typicode.com/${searchtext}`);
     return res.status(200).send({
           error: false,
           message: `Data for ${searchtext} from the server`,
           data: recipe.data
         });
   })

A request to this route in postman will look as follows.

 How to cache with Redis in Nodejs

If we make another request, we see the result as follows.

 How to cache with Redis in Nodejs

We can see that the information has not changed but still there is same amount of time that is being taken to get the data.

We will improve this time by storing the response in our redis cache.  Our server.js will have the following final code with Redis caching implemented.

const express = require('express');
const axios = require('axios');
const redis = require('redis');
const app = express();
const port = 4000;
const client = redis.createClient(6379);
client.on("error", (error) => {
console.error(error);
});
app.get('/:searchtext', (req, res) => {
try {
  const searchtext = req.params.searchtext;
  client.get(searchtext, async (err, data) => {
    if (data) {
       return res.status(200).send({
        error: false,
        message: `Data for ${searchtext} from the cache`,
        data: JSON.parse(data)
      })
    } else {
        const recipe = await axios.get(`https://jsonplaceholder.typicode.com/${searchtext}`);
        client.setex(searchtext, 1020, JSON.stringify(recipe.data));
        return res.status(200).send({
          error: false,
          message: `Data for ${searchtext} from the server`,
          data: recipe.data
        });
    }
  })
} catch (error) {
    console.log(error)
}
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});

Lets us explore what is happening here. He have intialized the redis client on its default port. Inside our route, the client gets the key and checks the data against it in the memory cache. If we find the data against the specified keyvalue pair, we simply return it in the response and if there is no data against the specified keyvalue pair, we fetch the required data from our API.

Client.setex() is the main function that takes a key and sets the data against it. It also takes time to specifiy the validity of the cache. Now, let us hit our API in postman and see the time taken by subsequent requests.


1st request

 How to cache with Redis in Nodejs

2nd request

 How to cache with Redis in Nodejs

If you notice the response time, there is a huge difference from before. This is all because of in-memory caching by Redis.

Conclusion
In this article, we have seen how to implement caching with Redis in nodejs. This tutorial used a basic implementation that would be great to get started with Redis and in-memory caching. You can always explore and learn more about it.

Tags

JTC

Like puppies, we build software that everyone love

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.