Skip to content

SSE Multiplexing — Complete Guide to Multiple Event Streams

DodaTech Updated 2026-06-28 4 min read

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

SSE multiplexing manages multiple event streams over a single HTTP connection using named events, separate endpoints, or HTTP/2 multiplexing to deliver different types of real-time data without opening multiple connections.

What You'll Learn

  • Three strategies for multiplexing SSE streams
  • Using named events to separate stream types
  • HTTP/2 multiplexing for multiple SSE connections

Why It Matters

Opening one SSE connection per data channel wastes browser connections (limited to 6-8 per origin) and server resources. Multiplexing combines multiple data streams efficiently.

Real-World Use

A monitoring dashboard uses a single SSE connection with three named event types: metrics (CPU/memory every 5s), alerts (when thresholds exceeded), and status (connection health pings). One connection, three logical streams.

flowchart LR
    C["Client"] -->|"Single HTTP Connection"| S["SSE Server"]
    S -->|"event: metrics"| C
    S -->|"event: alerts"| C
    S -->|"event: status"| C
    style C fill:#dbeafe,stroke:#2563eb

Code Examples

// Server with multiplexed named events
const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/events') {
    res.writeHead(200, { 'Content-Type': 'text/event-stream' });

    // Metrics stream
    setInterval(() => {
      res.write(`event: metrics\n`);
      res.write(`data: ${JSON.stringify({ cpu: Math.random(), mem: Math.random() })}\n\n`);
    }, 5000);

    // Alert stream
    setInterval(() => {
      res.write(`event: alerts\n`);
      res.write(`data: ${JSON.stringify({ level: 'info', msg: 'All systems nominal' })}\n\n`);
    }, 15000);

    // Status stream
    setInterval(() => {
      res.write(`event: status\n`);
      res.write(`data: {"status": "connected"}\n\n`);
    }, 30000);
  }
});

server.listen(3000);

Expected output: Server emits three named event types on one SSE connection.

// Client receives multiplexed named events
const source = new EventSource('/events');

source.addEventListener('metrics', (event) => {
  const data = JSON.parse(event.data);
  updateCpuGauge(data.cpu);
  updateMemGauge(data.mem);
});

source.addEventListener('alerts', (event) => {
  const alert = JSON.parse(event.data);
  showNotification(alert.level, alert.msg);
});

source.addEventListener('status', (event) => {
  updateConnectionStatus(JSON.parse(event.data).status);
});

Expected output: Client dispatches each event type to its own handler function.

# Python multiplexed SSE server
import http.server
import json
import time

class MultiplexedSSE(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-Type', 'text/event-stream')
        self.end_headers()

        counter = 0
        while True:
            counter += 1
            # Send metrics event
            self.wfile.write(f"event: metrics\ndata: {json.dumps({'count': counter})}\n\n".encode())
            time.sleep(2)
            if counter % 5 == 0:
                self.wfile.write(f"event: heartbeat\ndata: {{\"time\": {time.time()}}}\n\n".encode())

Expected output: Python SSE server sends metrics every 2s and heartbeats every 10s over one connection.

Common Mistakes

1. Using Multiple EventSource Objects

Each EventSource opens a separate HTTP connection, consuming browser Connection Pool slots. Use named events instead.

2. Not Including event: Field

Without the event field, all messages go to the generic onmessage handler, defeating multiplexing.

3. Mixing Event Types in One Handler

Using a single onmessage for multiplexed streams forces Parsing logic into one function. Use addEventListener for clean separation.

4. Ignoring Connection Pool Limits

Browsers limit connections per origin (typically 6-8). Opening multiple SSE connections exhausts this pool, blocking other requests.

5. No Heartbeat for Silent Channels

If one named event type rarely fires, the client may think the connection is dead. Send periodic heartbeats.

Practice Questions

  1. What are three ways to multiplex SSE streams?
  2. Why is using named events better than multiple EventSource objects?
  3. How does the browser connection pool limit affect SSE multiplexing?
  4. What is the purpose of sending heartbeats in a multiplexed stream?
  5. How does addEventListener differ from onmessage for named events?

Answers:

  1. Named events, separate endpoints with HTTP/2, and JSON envelope with type field.
  2. Named events reuse one HTTP connection, saving browser connection pool slots.
  3. Each SSE connection uses one slot; exceeding the pool blocks other HTTP requests.
  4. Heartbeats keep the connection alive and let the client verify liveness even for silent streams.
  5. addEventListener routes to type-specific handlers; onmessage catches all events without type filtering.

Challenge: Build a real-time dashboard with three data panels (CPU, memory, disk) all fed from a single multiplexed SSE connection using named events. Include a heartbeat for connection health.

FAQ

Does HTTP/2 help with SSE multiplexing?

: Yes, HTTP/2 allows multiple SSE connections over a single TCP connection, reducing the impact of the browser connection limit.

Can you send binary data in a multiplexed SSE stream?

: No, SSE is text-only. Encode binary as Base64 in the event data field.

How many named events can you define in one SSE stream?

: There is no hard limit, but keep it under 10-15 for readability and maintainability.

What happens if two event types fire at the same time?

: They are serialized in the order the server writes them. The client processes them sequentially.

Is there a performance penalty for multiplexing?

: Minimal. The main benefit is reduced connection overhead, which improves performance.

Mini Project

Build a multiplexed SSE server that streams three data types: stock prices (every 2s), news headlines (every 30s), and system heartbeats (every 10s). The client displays each in a separate panel with the last update timestamp.

What's Next

Learn about SSE with HTTP/2 for advanced connection management, or explore SSE browser support for compatibility details.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro