0PricingLogin
Node.js Backend Development Bootcamp · Lesson

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

  1. Cache-Aside, Write-Through, and TTL Strategies
  2. Distributed Locks and the Redlock Algorithm
  3. Pub/Sub, Streams, and Rate Limiting with Redis
  4. Preventing Cache Stampedes and Thundering Herds
← Back to Node.js Backend Development Bootcamp