Pub/Sub, Streams, and Rate Limiting with Redis
Broadcast events, build durable Redis Streams, and implement token-bucket rate limiters atomically.
Three Messaging Primitives in One Server
Redis is more than a key/value cache. In a Node.js backend it doubles as a lightweight message broker and a coordination engine. In this lesson you will learn three production patterns that ship with every Redis install:
- Pub/Sub — fire-and-forget broadcast to all connected listeners.
- Streams — an append-only, durable log with consumer groups and replay.
- Rate limiting — atomic counters that throttle abusive clients.
The key idea that ties them together: a single round-trip to Redis can do work that would otherwise need a database, a queue server, and a lock service. We will use the ioredis client throughout, which is the de-facto standard for Node backends because it supports pipelining, Lua scripting, and cluster mode.
Pub/Sub: Broadcast to Every Subscriber
Redis Pub/Sub lets one process PUBLISH a message to a channel and have every SUBSCRIBEd client receive it instantly. It is perfect for cache-invalidation fan-out or pushing live updates to WebSocket servers.
The critical gotcha: a connection in subscribe mode cannot run normal commands. You must create a dedicated subscriber connection separate from the one you use for GET/SET. Below, sub only listens; a second client would be used to publish.
const Redis = require('ioredis');
const sub = new Redis(); // dedicated subscriber connection
const pub = new Redis(); // separate connection for publishing
sub.subscribe('cache:invalidate', (err, count) => {
if (err) throw err;
console.log('Subscribed to ' + count + ' channel(s)');
});
sub.on('message', (channel, message) => {
console.log('[' + channel + '] ' + message);
});
// Another part of the app publishes an event
pub.publish('cache:invalidate', JSON.stringify({ key: 'user:42' }));All lessons in this course
- Cache-Aside, Write-Through, and TTL Strategies
- Distributed Locks and the Redlock Algorithm
- Pub/Sub, Streams, and Rate Limiting with Redis
- Preventing Cache Stampedes and Thundering Herds