Caching with Redis
Overview
Some data is read far more often than it changes: a course catalogue, a product page, a user’s permissions, an exchange rate fetched from a slow external API. Asking the database (or that API) every time wastes work and adds latency.
A cache keeps a copy of that data somewhere much faster. Redis is the most widely used cache for Node apps: an in-memory store that answers in well under a millisecond, shared by every copy of your app.
Running Redis
docker run --name academy-redis -d -p 6379:6379 redis:8Connect with the ioredis client (redis, the official client, works similarly):
npm install ioredis// src/redis.js
import Redis from 'ioredis';
export const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379');
redis.on('error', (err) => console.error('Redis error', err));Basic commands
Redis stores keys mapped to values. The simplest values are strings:
await redis.set('greeting', 'hello');
await redis.get('greeting'); // 'hello'
await redis.set('otp:asha', '493021', 'EX', 300); // expires in 300 seconds
await redis.ttl('otp:asha'); // seconds left
await redis.del('greeting');
await redis.incr('page:views'); // atomic counter: 1, 2, 3…Name keys with a type:id pattern — course:42, user:7:permissions — so they’re easy to find and delete. Objects must be serialised: JSON.stringify to store, JSON.parse to read.
Redis also has hashes, lists, sets, sorted sets and streams — powerful structures for leaderboards, queues and more.
The cache-aside pattern
The most common caching pattern:
- Look for the value in the cache.
- Hit — return it.
- Miss — load it from the database, store it in the cache with an expiry, return it.
async function cached(key, ttlSeconds, load) {
const hit = await redis.get(key);
if (hit !== null) return JSON.parse(hit);
const value = await load();
if (value !== null && value !== undefined) {
await redis.set(key, JSON.stringify(value), 'EX', ttlSeconds);
}
return value;
}
const course = await cached(`course:${id}`, 300, () => coursesRepo.findById(id));A small helper like this makes caching any slow read a one-line change.
Keeping the cache fresh
“There are only two hard things in computer science: cache invalidation and naming things.” — Phil Karlton
A cache that serves out-of-date data causes confusing bugs. Two complementary tools:
- Expiry (TTL) — every cached value gets a time limit. Even if you forget to invalidate, stale data disappears eventually. Always set one.
- Invalidation — when data changes, delete the cached copy so the next read fetches the new version:
async function updateCourse(id, changes) {
const course = await coursesRepo.update(id, changes);
await redis.del(`course:${id}`, 'courses:featured'); // and any lists it appears in
return course;
}Deleting is safer than overwriting the cache with the new value: if two updates race, a deleted key can’t end up holding the older one.
What to cache
| Good candidates | Poor candidates |
|---|---|
| Read often, change rarely (catalogue, settings) | Changes on every request |
| Expensive to compute (reports, aggregates) | Already fast (a primary-key lookup on a small table) |
| Slow external API responses | Data that must always be exactly current (balances, stock at checkout) |
| Rendered fragments, permission lookups | Per-user secrets you’d be upset to leak |
Measure before caching: add a cache when you know a read is slow or frequent, not by default. Every cache is another thing that can be wrong.
Beyond caching
Redis’s speed and atomic operations make it useful for much more:
Rate limiting — count requests per user per minute:
async function allow(userId, limit = 100) {
const key = `rate:${userId}:${Math.floor(Date.now() / 60_000)}`;
const count = await redis.incr(key);
if (count === 1) await redis.expire(key, 60);
return count <= limit;
}Sessions — store login sessions shared by all app instances (see Sessions and cookies).
Locks — make sure a job runs on only one server: SET lock:report NX EX 60 succeeds for only one caller.
Job queues — libraries like BullMQ use Redis to hand work to background workers (see Background jobs).
Pub/sub — broadcast messages between app instances, for example to relay WebSocket messages across servers.
Things to remember
- Redis keeps data in memory. Persistence options exist, but treat cached data as disposable. Your app must work — slower — if Redis is empty.
- Give Redis a memory limit and eviction policy (
maxmemory-policy allkeys-lru) so a growing cache doesn’t run out of memory. - Handle Redis being down: decide whether to fall back to the database (usually best for caches) or fail.
- Close the connection on shutdown:
await redis.quit().
Cache last, not first. A good database schema with the right indexes is often fast enough. Add Redis when measurements show you need it — and when you do, always pair it with a TTL and an invalidation plan.
Cache a course lookup
Write getCourseCached(id) that checks Redis for course:<id>, returns the parsed value if present, otherwise loads it from the repository, stores it for 5 minutes, and returns it. Also write updateCourse(id, changes) that updates the database and deletes the cache key.
import { redis } from './redis.js';
import { coursesRepo } from './courses.repository.js';
export async function getCourseCached(id) {}
export async function updateCourse(id, changes) {}import { redis } from './redis.js';
import { coursesRepo } from './courses.repository.js';
const key = (id) => `course:${id}`;
export async function getCourseCached(id) {
const cached = await redis.get(key(id));
if (cached) return JSON.parse(cached);
const course = await coursesRepo.findById(id);
if (course) await redis.set(key(id), JSON.stringify(course), 'EX', 300);
return course;
}
export async function updateCourse(id, changes) {
const course = await coursesRepo.update(id, changes);
await redis.del(key(id));
return course;
}Summary
- Redis is an in-memory data store that answers in well under a millisecond.
- Cache-aside: read from the cache, fall back to the database on a miss, then fill the cache.
- Always set an expiry (TTL), and delete or update cache keys when the data changes.
- Cache data that’s read often and changes rarely; never treat the cache as the source of truth.
- Redis also powers rate limiting, sessions, locks and job queues.