Websocket Broadcasting
title: "WebSocket Broadcasting" description: "Learn WebSocket broadcasting patterns for sending messages to multiple clients simultaneously using rooms, wildcards, and fan-out techniques." weight: 18 date: 2026-06-28 lastmod: 2026-06-28 tags: ["apis", "websocket"]
Broadcasting is the ability to send a message to multiple WebSocket clients at once. Different broadcasting patterns serve different use cases, from global announcements to targeted group messages.
## What You'll Learn
- Global broadcasting to all clients
- Room-based broadcasting
- Broadcasting with Socket.IO
- Wildcard and pattern-based broadcasting
- Performance considerations for large broadcasts
## Why It Matters
Efficient broadcasting is essential for scaling real-time applications. Broadcasting to thousands of clients requires optimized patterns to avoid overwhelming the server or network.
## Real-World Use
A live event streaming platform broadcasts real-time scores to millions of viewers during sports events. They use a tiered broadcasting approach: global scores to all, per-match updates to room subscribers, and personalized alerts.
## Flow Chart
```mermaid
flowchart LR
A[Broadcast Source] --> B{Broadcast Type}
B --> C[Global Broadcast]
B --> D[Room Broadcast]
B --> E[Pattern Match]
C --> F[All Connected Clients]
D --> G[Room Members]
E --> H[Topic Subscribers]
F --> I[Client A]
F --> I[Client B]
G --> I[Client A]
H --> I[Client C]
Code Examples
Example 1: Global and Targeted Broadcasting
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
function broadcast(data, exclude = null) {
const message = JSON.stringify(data);
server.clients.forEach((client) => {
if (client !== exclude && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
}
server.on('connection', (ws, req) => {
// Send welcome only to this client
ws.send(JSON.stringify({
type: 'welcome',
clientCount: server.clients.size,
}));
// Broadcast to all except sender
ws.on('message', (message) => {
const data = JSON.parse(message);
broadcast(data, ws);
});
});
// Periodic global broadcasts
setInterval(() => {
broadcast({
type: 'heartbeat',
timestamp: Date.now(),
clientCount: server.clients.size,
});
}, 5000);
Expected output: Welcome messages go to individual clients, chat messages go to all except sender, heartbeats go to all clients.
Example 2: Pattern-Based Broadcasting
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
const subscriptions = new Map();
server.on('connection', (ws) => {
ws.subscriptions = new Set();
ws.on('message', (message) => {
const data = JSON.parse(message);
switch (data.type) {
case 'subscribe':
ws.subscriptions.add(data.topic);
if (!subscriptions.has(data.topic)) {
subscriptions.set(data.topic, new Set());
}
subscriptions.get(data.topic).add(ws);
break;
case 'unsubscribe':
ws.subscriptions.delete(data.topic);
subscriptions.get(data.topic)?.delete(ws);
break;
case 'publish':
// Match against subscriptions with wildcards
const topic = data.topic;
subscriptions.forEach((subscribers, pattern) => {
if (matchTopic(pattern, topic)) {
subscribers.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
topic,
payload: data.payload,
}));
}
});
}
});
break;
}
});
});
function matchTopic(pattern, topic) {
const regex = new RegExp(
'^' + pattern.replace(/\+/g, '[^/]+').replace(/#/g, '.*') + '$'
);
return regex.test(topic);
}
// Example: subscribe to 'sensors/+/temperature'
// This matches 'sensors/room1/temperature', 'sensors/room2/temperature'
Expected output: MQTT-style topic matching with wildcards, allowing clients to subscribe to patterns like sensors/+/temperature.
Example 3: Socket.IO Broadcasting with Different Scopes
const { Server } = require('socket.io');
const io = new Server(3000);
io.on('connection', (socket) => {
// 1. Send to sender only
socket.emit('personal', { message: 'Only for you' });
// 2. Send to all clients except sender
socket.broadcast.emit('broadcast', {
from: socket.id,
message: 'Everyone except sender',
});
// 3. Send to all clients in room except sender
socket.to('room-1').emit('room-event', {
message: 'Room members except sender',
});
// 4. Send to all clients including sender
io.emit('global', { message: 'Every connected client' });
// 5. Send to all in room including sender
io.to('room-1').emit('room-global', { message: 'All in room' });
// 6. Send to specific socket(s)
io.to('socket-id-123').emit('direct', { message: 'Direct message' });
// 7. Send with exclusion
socket.broadcast.to('room-1').emit('room-broadcast', {
message: 'Room members except sender',
});
// 8. Volatile messages (not guaranteed delivery)
socket.volatile.emit('position-update', {
x: Math.random(),
y: Math.random(),
});
});
Expected output: Eight different broadcasting patterns showing the flexibility of Socket.IO's broadcasting API.
Common Mistakes
| Mistake | Explanation |
|---|---|
| Broadcasting all messages globally | Not all messages should go to all clients; use targeted rooms |
| Not excluding the sender | Broadcasting without excluding the sender causes duplicate processing |
| Overusing broadcast for one-to-one messages | Use direct socket-to-socket messaging instead of broadcast for private messages |
| Ignoring backpressure | High-frequency broadcasts can overwhelm slow clients; implement rate limiting |
| Not monitoring broadcast performance | Track message delivery rates and latency to identify bottlenecks |
Practice Questions
- What is the difference between
socket.broadcast.emitandio.emit? - How do you exclude the sender from a broadcast?
- How do MQTT-style wildcards work for topic-based broadcasting?
- What are volatile messages in Socket.IO?
- How do you optimize broadcasting for thousands of clients?
Challenge
Build a real-time stock ticker application that broadcasts price updates to subscribers. Implement topic-based subscriptions with wildcards (e.g., stocks/tech/* for all tech stocks, stocks/AAPL for a specific stock). Optimize for handling 10,000+ concurrent subscribers.
FAQ
Mini Project
Build a real-time notification system for a social media platform. Implement tiered broadcasting: global announcements (all users), friend activity (specific groups), and personal notifications (individual users). Include rate limiting for high-frequency broadcasts.
What's Next
Learn about WebSocket middleware patterns
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro