Broadcast Messages Across Servers
Pub/Sub
When you have many Node servers and need to notify all of them — Redis pub/sub or a broker like NATS/RabbitMQ.
What you'll learn
- Use Redis pub/sub
- Know when to reach for a broker
- Compare with queues
You have multiple Node servers behind a load balancer. Server A needs to tell Server B “user 42 just logged out — invalidate their WebSocket connection.” How?
Pub/sub. One publisher, many subscribers, no point-to-point connection between them.
Redis Pub/Sub
// publisher (any server)
import { Redis } from "ioredis";
const pub = new Redis();
await pub.publish("user-events", JSON.stringify({ type: "logout", userId: 42 })); // subscriber (on every server)
import { Redis } from "ioredis";
const sub = new Redis();
sub.subscribe("user-events");
sub.on("message", (channel, raw) => {
const event = JSON.parse(raw);
if (event.type === "logout") {
disconnectUser(event.userId);
}
}); Every subscribed server gets every message. No persistence — if a server is down, it misses messages.
Pub/Sub vs Queue
| Queue (BullMQ) | Pub/Sub (Redis) | |
|---|---|---|
| Delivery | One worker handles each job | Every subscriber gets every message |
| Persistence | Survives restarts | Lost if no subscriber |
| Retries | Built-in | Up to you |
| Use for | Async work (emails, images) | Real-time notifications, fan-out |
If “this job should be done once” — queue. If “every server should know about this event” — pub/sub.
When To Use a Broker
For larger systems where persistence and ordering matter, reach for a real message broker:
- NATS — fast, JS-friendly, persistent streams (JetStream)
- RabbitMQ — battle-tested AMQP broker
- Apache Kafka — high-throughput event streaming, replay history
Each is a chapter unto itself. For most Node apps, Redis pub/sub is enough until it isn’t.
A Real Pattern
WebSocket fan-out across N servers:
Client connects to Server A → opens a WS to Server A
Client B connects to Server B
A wants to send a message to B.
1. A publishes to Redis: "to-user-B: hi"
2. Every server's subscriber sees it.
3. Server B finds B's WS and sends.
Without pub/sub, A would need to know which server B is on.
Database Migrations →