← Course Index

Redis Pub/Sub & Real-Time Patterns

~25 min · Redis

Ref
Primary Source
Redis Docs — Pub/Sub

Official documentation for publish/subscribe messaging. Also read the Streams section for durable messaging. Read →

Redis Pub/Sub

Redis pub/sub lets parts of your app publish messages to channels. Other parts subscribe and receive them in real time. Use for: live notifications, cache invalidation across servers, real-time dashboards.

import Redis from 'ioredis';
const publisher  = new Redis(process.env.REDIS_URL);
const subscriber = new Redis(process.env.REDIS_URL); // separate connection required

// Publisher
await publisher.publish('user:status', JSON.stringify({ userId: 123, status: 'online' }));

// Subscriber (blocks this connection for receiving only)
subscriber.subscribe('user:status');
subscriber.on('message', (channel, msg) => {
  const data = JSON.parse(msg);
  // broadcast to WebSocket clients, etc.
});
⚠️ Fire-and-forget

Redis pub/sub is fire-and-forget. If no subscriber is connected when you publish, the message is LOST. For guaranteed delivery, use RabbitMQ (Lesson 19) or Redis Streams.

Redis vs RabbitMQ Decision Guide

Use caseRedisRabbitMQ
Caching✓ Built for thisNot appropriate
Real-time pub/sub (fire-and-forget)✓ Simple, fastOverkill
Reliable job queues with retryNeeds BullMQ on top✓ Native
Guaranteed message deliveryPub/sub: no✓ ACK-based
Complex routing logicNot built-in✓ Exchanges + bindings

BullMQ — Reliable Background Jobs on Redis

npm install bullmq

import { Queue, Worker } from 'bullmq';
const connection = { host: 'redis', port: 6379 };

// Producer: add a job
const emailQueue = new Queue('emails', { connection });
await emailQueue.add('send-welcome', {
  to: 'user@example.com', template: 'welcome'
}, { attempts: 3, backoff: { type: 'exponential', delay: 1000 } });

// Consumer: process jobs
const worker = new Worker('emails', async job => {
  await sendEmail(job.data.to, job.data.template);
}, { connection });

worker.on('completed', job => console.log('Done:', job.id));
worker.on('failed', (job, err) => console.error('Failed:', err.message));

Memory Management

# Set max memory and eviction policy
redis-server --maxmemory 256mb --maxmemory-policy allkeys-lru

# Common policies:
# noeviction    — errors when full (safe default)
# allkeys-lru   — evict least recently used (good for pure caching)
# volatile-lru  — evict LRU keys that have TTL set

Check Your Understanding

1. You publish a message to a Redis channel but no subscriber is running. What happens?
2. For sending welcome emails with guaranteed delivery and retry on failure, which tool?
3. Your Redis instance fills up. You want to automatically remove least-recently-used entries. Which eviction policy?