Getting Started with Redis for Caching and Real-Time Data

A practical guide to using Redis for caching, session storage, and real-time features, with working code examples.

What Redis Is Good For

Redis is an in-memory data store that excels at anything needing sub-millisecond reads: caching expensive queries, session storage, rate limiting, leaderboards, and pub/sub messaging.

Basic Caching Pattern

const redis = require('redis');
const client = redis.createClient();
await client.connect();

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

  const product = await db.getProduct(id);
  await client.setEx(cacheKey, 3600, JSON.stringify(product));
  return product;
}

The setEx call sets a one-hour expiration, so stale data self-heals without manual cache invalidation logic for most read-heavy use cases.

Invalidating on Write

async function updateProduct(id, data) {
  await db.updateProduct(id, data);
  await client.del(`product:${id}`);
}

Rate Limiting with Redis

async function checkRateLimit(userId) {
  const key = `ratelimit:${userId}`;
  const count = await client.incr(key);
  if (count === 1) await client.expire(key, 60);
  return count <= 100;
}

Leaderboards with Sorted Sets

await client.zAdd('leaderboard', { score: 1500, value: 'user123' });
const top10 = await client.zRangeWithScores('leaderboard', 0, 9, { REV: true });

Pub/Sub for Real-Time Features

// Publisher
await client.publish('order-updates', JSON.stringify({ orderId: 42, status: 'shipped' }));

// Subscriber
const subscriber = client.duplicate();
await subscriber.connect();
await subscriber.subscribe('order-updates', (message) => {
  console.log('Update received:', JSON.parse(message));
});

Common Pitfalls

  • Using Redis as a primary datastore without persistence configured — it’s a cache first, database second.
  • Forgetting TTLs, leading to unbounded memory growth over time.
  • Storing large objects in Redis instead of references, wasting memory that’s meant to stay fast and lean.

Conclusion

Redis earns its place in almost every production stack because it solves several distinct problems — caching, rate limiting, real-time messaging — with one simple, fast tool. Start with basic caching, and expand into pub/sub or sorted sets as concrete features need them.