DEV Community

Leandro Lima
Leandro Lima

Posted on

Using Redis as a Cache for Node.js Applications

Using Redis as a Cache for Node.js Applications

Redis is an in-memory data structure store used as a distributed, in-memory key-value database, cache, and message broker. It can be used as a distributed cache to speed up applications. Caching is a technique used to store regularly used data in a Space Redis takes less time in serving repeated requests than making requests to the database every time.

Node.js is an open-source, cross-platform, JavaScript runtime used to build scalable web applications. Node.js applications are mostly IO-bound because they deal with I/O operations most of the time. Caching can significantly improve the performance of Node.js applications, provided it is used efficiently.

This tutorial will discuss how to use Redis as a cache for Node.js applications. It covers the steps to start a Redis server and use it along with a Node.js application. We’ll build a simple Node.js application and show how to use Redis to cache the application’s data, improving its performance.

Prerequisites

Before you start, you’ll need to have the following installed:

Creating a Sample Node.js Application

To demonstrate how to use Redis as a cache for Node.js applications, we’ll create a simple Node.js application that reads data from a PostgreSQL database. Let’s create a Node.js project named redis-cache using the command below:

$ mkdir redis-cache && cd redis-cache
Enter fullscreen mode Exit fullscreen mode

Run the command npm init to generate the default configuration file package.json and install the express and pg modules by running the following command:

$ npm install express pg --save
Enter fullscreen mode Exit fullscreen mode

Create a file server.js in the root directory of the project and input the following code:

const express = require("express");
const { Client } = require("pg");

const PORT = 3000;
const HOST = "127.0.0.1";

const connection = {
    user: process.env.POSTGRESQL_USER,
    password: process.env.POSTGRESQL_PASSWORD
 };

const client = new Client(connection);

client.connect();

let getAllUsers = async () => {
    try {
        let res = await client.query("SELECT * FROM users");
        return res.rows
    } catch (e) {
        throw new Error(e);
    }
};

const app = express();

app.get("/users", async (req, res) => {
    let users = await getAllUsers();
    console.log(users);
    res.send(users);
});

app.listen(PORT, HOST);
console.log(`Server running on ${HOST}:${PORT}`);
Enter fullscreen mode Exit fullscreen mode

The code above creates an Express server that retrieves data from the users table and sends it as a response. Follow the instructions here to create the users table and add some sample records.

Now, start the Node.js process and run the sample application by running the command below:

$ node server.js
Enter fullscreen mode Exit fullscreen mode

Setting Up and Starting a Redis Server

Once you have the Node.js application ready, you can set up and start a Redis server. Follow the instructions according to your operating system from the Redis download page to install and start a Redis server.

Connecting a Node.js Application to a Redis Server

Once you have the Redis server up and running, you can connect the Node.js application to a Redis server. Node.js provides various modules for managing Redis databases. For this tutorial, we’ll use node-redis. To install the module, run the command below in the project’s root directory:

$ npm install redis --save
Enter fullscreen mode Exit fullscreen mode

Once the module is installed, require it at the top of the server.js file and provide the connection information to the Redis server.

const redis = require("redis");

const redisPort = 6379;
const redisHost = "127.0.0.1";

const redisClient = redis.createClient({
  port: redisPort,
  host: redisHost
});
Enter fullscreen mode Exit fullscreen mode

Using Redis as Cache for a Node.js Application

Now that the Redis server is set up and the Node.js application is connected to it, we’ll use Redis as a cache for the application. We’ll set a key/value pair in Redis with the response from the application and add a cache layer in the application to check if the data exists in the Redis store. If the data is found in the Redis cache, it will be sent as a response, otherwise, the application will fetch the data from the PostgreSQL database.

Before we add the cache layer to the application, we’ll add code to store the data in the Redis server after it’s fetched from the PostgreSQL database. Modify the getAllUsers() function as follows:

let getAllUsers = async () => {
    try {
        let res = await client.query("SELECT * FROM users");
        let users = res.rows;

        redisClient.set(
            "users",
            JSON.stringify(users)
        );

        return users;
    } catch (e) {
        throw new Error(e);
    }
};
Enter fullscreen mode Exit fullscreen mode

It stores the response from the PostgreSQL database as a JSON string against the key users.

Let’s add the cache layer to the /users route. Define a function checkCache() which will check if the data is present in the Redis store.

let checkCache = (req, res, next) => {  
    redisClient.get("users", (err, data) => {
        if (err) {
            return next(err);
        }

        if (data !== null) {
            res.send(JSON.parse(data));
        } else {
            next();
        }
    });
};
Enter fullscreen mode Exit fullscreen mode

It retrieves the value stored against the key users and sends it as the response. If it doesn’t find the data in the Redis store, it will call the next() function.

Call the checkCache() function before the actual /users route.

app.get("/users", checkCache, async (req, res) => {
    let users = await getAllUsers();
    console.log(users);
    res.send(users);
});
Enter fullscreen mode Exit fullscreen mode

Now, run the application and access the endpoint to test the cache layer.

$ node server.js
Enter fullscreen mode Exit fullscreen mode

redis-cache

If the data is present in the Redis store, the application will return the data from the Redis store. Otherwise, it will fetch the data from the PostgreSQL database.

Now that we have Redis as a cache for our Node.js application, our application will benefit from the performance boost provided by the Redis server.

Conclusion

Redis is a powerful and scalable solution for caching data used by Node.js applications. It’s easy to set up and integrate with a Node.js application and boosts the performance of applications. We’ve seen how to use Redis as a cache for Node.js applications in this tutorial.

Top comments (0)