How To Implement Caching in Node.js Using Redis

Prerequisites:

To follow through with this tutorial you must have the following installed on your computer:

  • Node JS
  • NPM
  • Redis
  • Postman/Web Browser
  • Code Editor (VsCode)

If you are new to Redis and you don’t have Redis installed then first go to how to install Redis article.

In this article, we will learn how to implement caching in node.js using Redis. But, before we start implementation details, let’s explore what caching is and how it can help the performance of our application.

What is caching?

Caching is the process of storing data in a temporary location so that the data can be accessed with minimal resources. This allow applications, in future request, to access that data faster.
When we implement a caching mechanism, we can process the data once, store it in a cache and then retrieve it later directly from the cache without doing all those operations and server calls again and again.

For example, if we have some data coming from a third-party API, and that data is unlikely to be changed soon, we can store it in a cache once we retrieve it. The next time the server receives the same request, it retrieves the data directly from the cache instead of making a new database call.

Benefits of caching:

– It helps speed up application performance.
– It stores data locally.
– Improved database performance.
– Reduced server load.
– Decreased network costs.
– Increased availability of content.

Let’s start with creating a node app. Create a folder and name it node_caching. Open the folder with Visual Studio Code. Once inside VS Code, open the terminal and initialize the directory to create a package.json file by running:

npm init -y

For this project we will be using Express, Redis, and Axios Framework for Node.js, so let’s install them by running the following:

npm i express redis axios

After installing the above dependencies, Create an index.js file, So go to your app root directory and create it.
Now put the below code inside it:

const express = require('express');
const redis = require('redis');
const client = redis.createClient();
const axios = require('axios');
const app = express();
const PORT = 3000;

app.use(express.urlencoded({ extended: true }))

client.on('connect', function () {
  console.log('Redis Connected!');
});
app.listen(PORT, async () => {
  console.log(`Server started at port: ${PORT}`);
  await client.connect()
});

app.get('/photos', async (req, res) => {
  try {
    const albumId = req.query.albumId;
    var getData = await getPhotoData(`photos?albumId=${albumId}`, async () => {
      const { data } = await axios.get('https://jsonplaceholder.typicode.com/photos', { params: { albumId } })
      return data;
    });
    res.status(200).send(getData);
  } catch (err) {
    res.status(500).send({ error: err.message });
  }
})

app.get('/photos/:id', async (req, res) => {
  try {
    const id = req.params.id;
    var getData = await getPhotoData(`photos:${id}`, async () => {
      const { data } = await axios.get('https://jsonplaceholder.typicode.com/photos', { params: { id } })
      return data;
    });
    res.status(200).send(getData);
  } catch (err) {
    res.status(500).send({ error: err.message });
  }
})

async function getPhotoData(Key, cb) {
  return new Promise(async function (resolve, reject) {
    try {
      var getValue = await client.get(Key);
      if (getValue != null) {
        console.log('Data retrieved from Redis');
        return resolve(JSON.parse(getValue));
      } else {
        const freshData = await cb();
        client.setEx(Key, 3600, JSON.stringify(freshData));
        console.log('Data retrieved from the API');
        resolve(freshData);
      }
    } catch (e) {
      console.log(e)
      resolve(0);
    }
  });
}

Now, start the server by running node index.js and open postman to request the /photos endpoint.

As we can see, the request was completed in 604ms which is quite a long time to fetch data because the key is not found in the cache. Now it is saved in the cache and sent it again the result in time is drastically improved — only 46ms. Below is the response time after the cache:

Now Let’s check with photos?albumId=2 endpoint.

If the key is not found in the cache, the request is sent to the server which takes 781ms to complete as you can see below image.

Now it is saved in the cache and sent it again the result in time is drastically improved — only 13ms as you can see below image.

Also, you can check with the /photos/:Id endpoint.

I hope you guys understand how I can do this. Please provides your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article.

Also check, How to Use Multiple environment files in the Node.js Application.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories