Caching Data with Redis in Node.js

 Caching data with Redis in Node.js is a powerful way to improve performance, reduce database load, and deliver faster responses to users. Here's a simple guide to get you started:


🔹 What is Redis?

Redis is an in-memory key-value store often used for caching because it is:


Fast (in-memory)


Persistent (optional)


Flexible (supports various data types)


🔹 Use Case for Caching in Node.js

Imagine you have an API that fetches data from a slow database or external service. Instead of calling it every time, you can cache the data in Redis and serve it from there until it expires.


🔹 Step-by-Step Guide

1. Install Redis and Required Packages

Make sure Redis is installed and running on your machine or use a Redis cloud service like Redis Cloud.


Then install the Redis client in your Node.js project:


bash

Copy

Edit

npm install redis

2. Connect to Redis

js

Copy

Edit

const redis = require('redis');


// Create and connect Redis client

const client = redis.createClient();


client.on('error', (err) => console.error('Redis Client Error', err));


(async () => {

  await client.connect();

})();

3. Basic Caching Logic

js

Copy

Edit

const express = require('express');

const axios = require('axios');

const app = express();

const PORT = 3000;


app.get('/data/:id', async (req, res) => {

  const { id } = req.params;


  // Check Redis cache

  const cachedData = await client.get(id);

  if (cachedData) {

    console.log('Cache hit');

    return res.json(JSON.parse(cachedData));

  }


  // Simulate slow data source

  try {

    console.log('Cache miss');

    const response = await axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`);


    // Save to Redis with 1-hour expiration

    await client.setEx(id, 3600, JSON.stringify(response.data));


    return res.json(response.data);

  } catch (error) {

    return res.status(500).json({ error: 'Failed to fetch data' });

  }

});


app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));

4. Common Redis Methods

client.set(key, value) – Set data


client.get(key) – Get data


client.setEx(key, ttl, value) – Set with expiration


client.del(key) – Delete a key


client.flushAll() – Clear entire Redis cache (use carefully)


✅ Benefits of Using Redis for Caching

Performance boost: Faster data retrieval


Scalability: Handles high traffic


Reduced DB load: Fewer queries to the database


🧠 Pro Tips

Use cache invalidation when data updates.


Add logging or monitoring for cache hits/misses.


Consider structured keys (e.g., user:123, product:456) for organization.

Learn MERN Stack Course in Hyderabad

Read More

Using Aggregations in MongoDB

Creating Relationships in MongoDB using Mongoose

API Rate Limiting with Express

Logging with Morgan and Winston

Visit Our Quality Thought Training in Hyderabad

Get Directions

Comments

Popular posts from this blog

Understanding Snowflake Editions: Standard, Enterprise, Business Critical

Why Data Science Course?

How To Do Medical Coding Course?