DEV Community

Cover image for ๐Ÿš€๐Ÿš€๐Ÿš€Implementing Redis Functionalities in Node.js Applications ๐Ÿ“ฆ
Shubham Srivastava
Shubham Srivastava

Posted on

๐Ÿš€๐Ÿš€๐Ÿš€Implementing Redis Functionalities in Node.js Applications ๐Ÿ“ฆ

Introduction

This documentation outlines the process of implementing caching using Redis in a Node.js Express application. Caching data with Redis helps reduce response times and server load by:

  • Storing frequently accessed data in memory
  • Optimizing data retrieval by avoiding repetitive requests to external sources

Prerequisites

  • Node.js installed on your machine
  • Basic understanding of JavaScript and Express.js

Redis Docker Installation

To set up Redis using Docker, follow these steps:

  1. Download and Install Docker:

    • Visit the official Docker website.
    • Download Docker for your operating system and follow the installation instructions provided.
  2. Run Redis Container: Execute the following command in your terminal to fetch Redis in a Docker container:

    docker run -d --name redis-stack -p 6379:6379 -p 8001:8001 redis/redis-stack:latest
    

    This command pulls the latest Redis image from Docker Hub and runs it in a detached mode (-d). It also names the container as redis-stack, maps the container's port 6379 to the host port 6379 (for Redis), and maps port 8001 to the RedisInsight UI for monitoring Redis data.

RedisInsight Dashboard

Verify Installation:

  1. Check if the Redis container is running by executing:
docker ps
Enter fullscreen mode Exit fullscreen mode
  1. Access RedisInsight by visiting http://localhost:8001 in your web browser. You should see the RedisInsight dashboard.

  2. Connect to the Redis server using the default connection settings (localhost:6379). Here's a visual guide on how to connect:

Connect to Redis

  1. After verifying that the Redis container is running and accessing RedisInsight, proceed with the following steps to interact with Redis:

a. Run docker ps to check the container IDs.

b. Run the following command to access the Redis container shell (replace <container_id> with the actual container ID):

   docker exec -it <container_id> bash
Enter fullscreen mode Exit fullscreen mode

c. Once inside the container, run the Redis CLI by executing:

   redis-cli
Enter fullscreen mode Exit fullscreen mode

You should now be connected to the Redis server and able to interact with it using the Redis CLI.

Installation

Ensure Redis server is installed and running. Additionally, install required dependencies for your Express application:

npm install express axios ioredis
Enter fullscreen mode Exit fullscreen mode

Basic Setup

Begin by setting up a basic Express application that listens on a specific port:

const express = require("express");
const axios = require("axios");
const app = express();

app.get("/", async (req, res) => {
    const { data } = await axios.get(
      "https://jsonplaceholder.typicode.com/photos"
    );
    return res.json(data);
});

const port = 9000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Enter fullscreen mode Exit fullscreen mode

redis

Problem Statement

Fetching data from external APIs directly may result in slow response times due to network latency and server load,here as you can see it took 364 millisecond to fetch the data.

Solution

Implement caching using Redis to store fetched data temporarily and serve it from the cache for subsequent requests, thereby reducing response times.

Certainly! Here's the updated documentation with the added points:

Implementation Steps

  1. Initialize Redis Client First, create a Redis client to interact with the Redis server. Create a file named client.js and add the following code:
   const { Redis } = require("ioredis");
   const client = new Redis();
   module.exports = client;
Enter fullscreen mode Exit fullscreen mode
  1. Implement Caching Logic Modify your route handler to utilize the Redis client for caching. Update your server.js file with the following code:
   const express = require("express");
   const axios = require("axios");
   const client = require("./client");
   const app = express();

   app.get("/", async (req, res) => {
     const cacheValue = await client.get("to-dos");
     if (cacheValue) {
       console.log("Cached value");
       return res.json(JSON.parse(cacheValue));
     }

     const { data } = await axios.get(
       "https://jsonplaceholder.typicode.com/photos"
     );
     await client.set("to-dos", JSON.stringify(data));
     await client.expire("to-dos", 30);
     return res.json(data);
   });

   const port = 9000;
   app.listen(port, () => {
     console.log(`Server is running on port ${port}`);
   });
Enter fullscreen mode Exit fullscreen mode

Image description

  1. Observation of Data Fetching Time
    After implementing the caching mechanism, you may notice that the initial data fetching time is higher as it involves fetching data from the external API. However, upon subsequent requests, the data fetching time significantly reduces to approximately 37 milliseconds due to the cached data being served from Redis. This demonstrates the effectiveness of caching in reducing response times and improving overall performance.

  2. Expiration and Renewal
    Note that the cached data expires after 30 seconds (await client.expire("to-dos", 30)). Upon expiration, the next request will trigger a fresh data fetch from the external API, refreshing the cache with updated data. This ensures that users receive the most up-to-date information while still benefiting from reduced response times during the cache lifespan.

Conclusion

By implementing caching with Redis in your Express application, you can significantly improve performance by reducing response times and server load. Caching commonly accessed data helps minimize latency and enhances the overall user experience, especially for frequently accessed resources.

Top comments (0)