🚀🚀🚀Implementing Redis Functionalities in Node.js Applications 📦
Tags: node, redis, database, coding
Published: 2024-03-07 10:50:35


## 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](https://www.docker.com/get-started).
    - 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:

    ```bash
    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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gfhsmip5a044yk19or2v.png)

**Verify Installation:**

1. Check if the Redis container is running by executing:

```bash
docker ps
```

2. Access RedisInsight by visiting `http://localhost:8001` in your web browser. You should see the RedisInsight dashboard.

3. Connect to the Redis server using the default connection settings (`localhost:6379`). Here's a visual guide on how to connect:
   
   ![Connect to Redis](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xu3nydl4butr4zqefpfj.png)

4. 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):

   ```bash
   docker exec -it <container_id> bash
   ```

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

   ```bash
   redis-cli
   ```

   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:

```bash
npm install express axios ioredis
```

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

```javascript
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}`);
});

```

![redis](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h1l47h7g1x7ld6lnc5ls.png)

## 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:

   ```javascript
   const { Redis } = require("ioredis");
   const client = new Redis();
   module.exports = client;
   ```

2. **Implement Caching Logic**
   Modify your route handler to utilize the Redis client for caching. Update your `server.js` file with the following code:

   ```javascript
   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}`);
   });
   ```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p9lskf5on365awtc3im3.png)



3. **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.

4. **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.