Databases & Data Access
Node.js Redis Caching
Redis is an in-memory data store used for caching, sessions, rate-limit counters and queues. Caching an expensive query in Redis turns a slow endpoint into a fast one without changing the database.
What is Redis Caching in Node.js?
Redis is an in-memory data store used for caching, sessions, rate-limit counters and queues. Caching an expensive query in Redis turns a slow endpoint into a fast one without changing the database.
Redis Caching example
JavaScript
import { createClient } from 'redis';
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
async function getJobsByCity(city) {
const key = `jobs:city:${city}`;
const cached = await redis.get(key);
if (cached) return JSON.parse(cached);
const jobs = await Job.find({ city, status: 'active' }).lean();
await redis.setEx(key, 300, JSON.stringify(jobs)); // expire in 5 minutes
return jobs;
}
// invalidate when the data changes
await redis.del(`jobs:city:${job.city}`);Key points to remember
- Always set an expiry — an unbounded cache eventually exhausts memory.
- Choose a key naming convention such as entity:field:value from day one.
- Invalidate on write, or accept staleness for the length of the TTL.
- Redis is also where sessions and rate-limit counters belong in a clustered app.
Common mistakes with Redis Caching
- Caching without expiry and serving stale data indefinitely.
- Caching per-user data under a shared key, leaking one user’s data to another.
Node.js Redis Caching— Interview Questions & FAQs
What should I cache in a Node.js API?+
Expensive reads that change rarely — aggregations, category listings, config, third-party API responses. Do not cache user-specific data under shared keys, and always set a TTL.
