Redis In-Memory Caching - Accelerating API Performance & Mitigating Database Bottlenecks

When an endpoint is called hundreds of times per second (such as an e-commerce product catalog or student syllabus page), querying the database on every single request introduces severe latency and risks exhausting database connection pools. Redis In-Memory Caching reduces response times from 150ms down to 2ms.

Installing the ioredis Client

npm install ioredis

Implementing the Cache-Aside Pattern

// cache/redisClient.js
const Redis = require('ioredis');

// Connect to Redis server
const redis = new Redis({
  host: process.env.REDIS_HOST || '127.0.0.1',
  port: 6379,
  retryStrategy: (times) => Math.min(times * 50, 2000)
});

redis.on('connect', () => console.log('[Redis Connected] In-memory cache ready'));
redis.on('error', (err) => console.error('[Redis Error]', err));

module.exports = redis;

Express Route with Redis Caching Middleware

// routes/courseRoutes.js
const express = require('express');
const router = express.Router();
const redis = require('../cache/redisClient');
const Course = require('../models/Course'); // Mongoose model

router.get('/courses/:id', async (req, res) => {
  const { id } = req.params;
  const cacheKey = `course:${id}`;

  try {
    // 1. Check Redis Cache First
    const cachedData = await redis.get(cacheKey);

    if (cachedData) {
      console.log(`[CACHE HIT] Serving course #${id} from Redis RAM`);
      return res.status(200).json({
        source: 'cache',
        data: JSON.parse(cachedData)
      });
    }

    // 2. Cache Miss: Query Physical Database
    console.log(`[CACHE MISS] Fetching course #${id} from MongoDB...`);
    const course = await Course.findById(id);

    if (!course) {
      return res.status(404).json({ error: 'Course not found' });
    }

    // 3. Store in Redis with 1 Hour TTL (3600 seconds)
    await redis.set(cacheKey, JSON.stringify(course), 'EX', 3600);

    res.status(200).json({
      source: 'database',
      data: course
    });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// Cache Invalidation on Update
router.patch('/courses/:id', async (req, res) => {
  const { id } = req.params;
  const updatedCourse = await Course.findByIdAndUpdate(id, req.body, { new: true });

  // Invalidate stale cache key immediately!
  await redis.del(`course:${id}`);
  console.log(`[CACHE INVALIDATED] Cleared cache for course #${id}`);

  res.status(200).json({ success: true, data: updatedCourse });
});

module.exports = router;

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is Redis and why is it used alongside Node.js databases?

Redis (Remote Dictionary Server) is an ultra-fast, open-source, in-memory key-value data store. Because data resides directly in RAM rather than on physical SSD disks, Redis handles read/write queries in sub-millisecond speeds (100,000+ operations/sec), making it ideal for session storage, leaderboard rankings, and API response caching.

Q2. What is the Cache-Aside (Lazy Loading) pattern?

When the server needs data, it checks Redis cache first (Cache Hit). If the data is found, it returns immediately without hitting the database. If not found (Cache Miss), it queries the database, writes the result to Redis with a Time-To-Live (TTL), and returns the response.

Q3. Why is setting a TTL (Time-To-Live) crucial in Redis?

Without a TTL, cached data never expires, eventually consuming all server RAM and serving stale, outdated data to users after database updates. Setting an expiration (e.g. 1 hour) ensures memory is recycled automatically.

Explore Related Node.js Tutorials & Next Steps

Boost your server-side JavaScript proficiency by studying these closely connected core modules:

MongoDB & Mongoose

Cache repetitive MongoDB queries with Redis.

Performance Profiling

Measure latency reductions achieved with caching.

Microservices & Message Queues

Use Redis Pub/Sub for inter-service communication.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!