🚀🚀🚀Implementing Redis Functionalities in Node.js Applications 📦
Shubham Srivastava
Posted on March 7, 2024
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:
-
Download and Install Docker:
- Visit the official Docker website.
- Download Docker for your operating system and follow the installation instructions provided.
-
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 asredis-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.
Verify Installation:
- Check if the Redis container is running by executing:
docker ps
Access RedisInsight by visiting
http://localhost:8001
in your web browser. You should see the RedisInsight dashboard.Connect to the Redis server using the default connection settings (
localhost:6379
). Here's a visual guide on how to connect:
- 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
c. Once inside the container, run the Redis CLI by executing:
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:
npm install express axios ioredis
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}`);
});
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
-
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;
-
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}`);
});
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.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.
Posted on March 7, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.