Skip to content

Broadcasting in WebSocket — Complete Guide

DodaTech Updated 2026-06-28 3 min read

In this tutorial, you will learn about Broadcasting in Websocket. We cover key concepts, practical examples, and best practices to help you master this topic.

Broadcasting sends messages to multiple WebSocket clients simultaneously. Strategies include server-wide broadcast to all connections, room-specific broadcast to a subset, and selective broadcast based on client properties or conditions.

What You'll Learn

  • Server-wide vs room-specific broadcasting
  • Excluding the sender from broadcasts
  • Selective broadcasting with conditions
  • Efficient fan-out patterns
  • Broadcasting with the ws library vs Socket.IO

Why It Matters

Efficient broadcasting is critical for real-time applications. Broadcasting to thousands of clients requires careful memory and CPU management. The wrong pattern can block the event loop or cause memory exhaustion.

Real-World Use

Slack broadcasts messages to all channel members. Twitter streams live tweets to followers. Multiplayer games broadcast player positions to nearby players using spatial broadcasting.

flowchart TD
    Message[Incoming Message] --> Router[Broadcast Router]
    Router --> All[Broadcast All]
    Router --> Room[Broadcast Room]
    Router --> Selective[Selective Broadcast]
    All --> Client1[Client A]
    All --> Client2[Client B]
    All --> Client3[Client C]
    Room --> Client2[Client B]
    Room --> Client4[Client D]
    Selective --> Client1[Client A]
    Selective --> Client3[Client C]

Teacher Mindset

Choose the right broadcast scope: all clients, clients in a room, or clients matching a condition. Use sender exclusion to avoid echoing the message back. For large fan-outs, use iterative batches to avoid blocking.

Code Examples

// Example 1: Broadcasting with ws library
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });

server.on('connection', (ws) => {
  ws.on('message', (data) => {
    const message = JSON.parse(data);

    // Broadcast to all including sender
    server.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(JSON.stringify(message));
      }
    });

    // Broadcast to all excluding sender
    server.clients.forEach((client) => {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(JSON.stringify(message));
      }
    });
  });
});
// Example 2: Broadcasting with Socket.IO
const io = require('socket.io')(3000);

io.on('connection', (socket) => {
  // Broadcast to all including sender
  io.emit('message', data);

  // Broadcast to all excluding sender
  socket.broadcast.emit('message', data);

  // Broadcast to room excluding sender
  socket.to('room:123').emit('message', data);

  // Broadcast to room including sender
  io.to('room:123').emit('message', data);

  // Volatile broadcast (can be dropped if client is congested)
  socket.volatile.broadcast.emit('price update', { value: 100 });

  // Compressed broadcast
  socket.compress(true).emit('large data', bigPayload);
});
// Example 3: Selective broadcast with conditions
const WebSocket = require('ws');

const server = new WebSocket.Server({ port: 8080 });
const clients = new Map();

server.on('connection', (ws) => {
  ws.clientId = generateId();
  clients.set(ws.clientId, ws);

  ws.on('message', (data) => {
    const msg = JSON.parse(data);

    // Selective broadcast to clients matching criteria
    server.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN && client.role === msg.targetRole) {
        client.send(JSON.stringify(msg));
      }
    });

    // Broadcast to specific user
    const targetClient = clients.get(msg.targetId);
    if (targetClient?.readyState === WebSocket.OPEN) {
      targetClient.send(JSON.stringify(msg));
    }
  });

  ws.on('close', () => clients.delete(ws.clientId));
});

Common Mistakes

  • Broadcasting to all clients when only a subset needs the message
  • Not excluding the sender from broadcasts, causing echo
  • Broadcasting large payloads to thousands of clients without batching
  • Using synchronous loops for broadcast that block the event loop
  • Not checking the readyState before sending to closed connections

Practice

  1. Implement server-wide broadcast with sender exclusion using ws.
  2. Implement room-specific broadcast using Socket.IO.
  3. Add selective broadcast based on user role or group.
  4. Implement batched broadcast for 10000+ connections.
  5. Challenge: Build a priority broadcast system where important messages jump the queue.

FAQ

What is the difference between io.emit and socket.broadcast.emit?

io.emit sends to all connected clients. socket.broadcast.emit sends to all except the sender.

How do I broadcast to thousands of clients efficiently?

Use iterative batches, compress large payloads, and consider using Redis pub/sub for multi-server setups.

What is volatile broadcast?

Volatile messages can be dropped if the client is not ready to receive them. Useful for high-frequency updates like stock prices.

Can I broadcast binary data?

Yes. Broadcast Buffers or ArrayBuffers just like text data. Binary is more efficient for large payloads.

How does broadcast work across multiple servers?

Use a pub/sub adapter (Redis, Kafka). Each server publishes messages to a channel, and all servers receive and forward to local clients.

Mini Project

Build a notification system that uses selective broadcasting. Admin users receive all notifications. Regular users receive only their own. Implement server-wide broadcast for system announcements with sender exclusion.

What's Next

Next, you will learn about WebSocket middleware for authentication and request processing.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro