How do you broadcast messages to multiple WebSocket clients?
Learn how to broadcast WebSocket messages to all connected clients using ws and Socket.IO, plus how a Redis backplane scales broadcasting across servers.
Expected Interview Answer
You broadcast by keeping a server-side collection of all active WebSocket connections and iterating over it, sending the same message to each open socket. Libraries like Socket.IO expose a helper (io.emit) that does this loop for you.
The raw approach with the ws library is to hold clients in a Set and loop, checking readyState === WebSocket.OPEN before send() to skip closing sockets. For scale you avoid a plain in-memory loop and use a pub/sub backplane (Redis, NATS) so every server instance relays the message to its own connected clients, keeping broadcast consistent across a horizontally scaled cluster.
- Delivers real-time updates to every client at once
- Powers chat, live scores, dashboards and notifications
- Decouples the event source from the recipients
- Scales across servers with a pub/sub backplane
- Lets you target subsets via rooms or channels
AI Mentor Explanation
A stadium announcer with a public-address system speaks once into the microphone and every spectator in every stand hears the score update simultaneously. Broadcasting to WebSocket clients is the same single act reaching many listeners: the server sends one message and the loop pushes it out to each connected fan's socket, so all of them get the wicket alert at the same instant without the announcer calling each seat individually.
Step-by-Step Explanation
Step 1
Track connections
On every 'connection' event, add the socket to a server-side collection such as a Set or the library's client registry.
Step 2
Receive the trigger
An event (new chat message, price update) arrives from a client, a queue, or an internal service that should reach everyone.
Step 3
Iterate the clients
Loop over the connection collection, or call the library's io.emit / server.clients helper that wraps the loop.
Step 4
Guard socket state
Send only when readyState === WebSocket.OPEN so you skip sockets that are closing or already closed.
Step 5
Scale with a backplane
Publish the message to Redis/NATS so every server instance rebroadcasts to its own locally connected clients.
What Interviewer Expects
- Knowing the server holds a collection of active connections
- Checking readyState before send() with raw ws
- Awareness of io.emit vs socket.emit in Socket.IO
- Understanding a pub/sub backplane is needed to scale broadcast
- Distinguishing broadcast-to-all from targeted room emits
Common Mistakes
- Sending to sockets that are closing without checking readyState
- Assuming a single-server in-memory loop works across a cluster
- Confusing socket.emit (one client) with io.emit (all clients)
- Forgetting to remove disconnected sockets from the collection
- Broadcasting large payloads without throttling or batching
Best Answer (HR Friendly)
“Broadcasting means sending one message to every connected user at the same time. The server keeps a list of everyone who is online and pushes the update out to all of them at once, which is how live chat, notifications and score tickers stay in sync.”
Code Example
import { WebSocketServer, WebSocket } from 'ws'
const wss = new WebSocketServer({ port: 8080 })
wss.on('connection', (socket) => {
socket.on('message', (data) => {
// Broadcast the incoming message to every open client
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(data.toString())
}
})
})
})io.on('connection', (socket) => {
socket.on('chat', (msg) => {
// io.emit sends to every connected client, including the sender
io.emit('chat', msg)
// socket.broadcast.emit sends to everyone except the sender
socket.broadcast.emit('chat', msg)
})
})Follow-up Questions
- How do you broadcast to everyone except the sender?
- Why do you need a Redis adapter to broadcast across multiple servers?
- How would you broadcast only to a subset of clients?
- What happens if you send() to a socket that is closing?
- How do you throttle high-frequency broadcasts to avoid overload?
MCQ Practice
1. In the ws library, how do you broadcast a message to all connected clients?
The ws library has no built-in broadcast; you loop over wss.clients and send() to each socket whose readyState is OPEN.
2. In Socket.IO, which call sends an event to every connected client including the sender?
io.emit() broadcasts to all connected clients. socket.broadcast.emit() excludes the sender, and socket.emit() targets only that one socket.
3. Why is a Redis (or NATS) adapter needed for broadcasting at scale?
With multiple server instances, an in-memory loop only reaches clients on one server. A pub/sub backplane fans the message out to all instances.
Flash Cards
How does raw ws broadcast? — Loop wss.clients and call client.send() on each socket where readyState === WebSocket.OPEN.
io.emit vs socket.emit? — io.emit sends to all clients; socket.emit sends only to that one client.
socket.broadcast.emit? — Sends to every connected client except the sender.
Why a Redis adapter? — It relays broadcasts across multiple server instances so all clients receive them at scale.