Caching in Node.js With Redis: Patterns That Actually Help

Serve repeated requests from memory

If the same expensive query runs thousands of times a minute with the same result, cache it. Redis (or compatible alternatives like Valkey) is the standard in-memory store for Node.js caching.

Cache-Aside Pattern

import { createClient } from 'redis';
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

async function getProduct(id) {
  const key = `product:${id}`;
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);

  const product = await db.products.findById(id);
  await redis.set(key, JSON.stringify(product), { EX: 300 }); // 5 minutes
  return product;
}

Invalidation

  • TTL — simplest; data may be stale up to the TTL
  • Delete on write — when a product updates, redis.del('product:42')
  • Versioned keys — change the key when data changes

Cache Stampede

When a popular key expires, hundreds of requests hit the database at once. Mitigate with:

  • A short lock so only one request rebuilds the cache
  • Slightly randomised TTLs
  • Serving stale data while refreshing in the background

Other Redis Uses

  • Sessions storage
  • Rate limiting counters
  • Queues (BullMQ)
  • Pub/Sub for real-time features
  • Leaderboards with sorted sets

What Not to Cache

  • Highly personalised data with low reuse
  • Data that must be strongly consistent (account balances)
  • Sensitive data without encryption and access controls

Monitor

Track hit rate, memory usage, and evictions. A low hit rate means your cache isn't helping.

Caching is easy to add and hard to invalidate. Start with TTLs, measure the hit rate, then refine.

Arivanandhan Chitheshwaran