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.
ioredis Clientnpm install ioredis
// 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;
// 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;
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
Cache repetitive MongoDB queries with Redis.
Measure latency reductions achieved with caching.
Use Redis Pub/Sub for inter-service communication.