Have you ever hit that annoying connection limit in your browser? Or wondered how complex real-time dashboards manage to listen to dozens of different data streams without crashing your network tab?
The answer is WebSocket Multiplexing.
In this post, I'll walk you through a project where I built a multiplexed WebSocket server from scratch using Node.js and TypeScript.
The Problem: Connection Overload 🤯
Imagine you are building a Slack clone. A user might be part of:
- General channel
- Engineering
- Random
- Direct Messages with Alice
- Direct Messages with Bob
If you open a separate WebSocket connection for each of these chat rooms, you'll quickly run into issues:
- Browser Limits: Browsers often limit the number of specific connections to a single domain (usually around 6).
- Resource Heavy: Each connection requires memory and handshake overhead on both the client and server.
The Solution: Multiplexing 💡
Multiplexing allows us to tunnel multiple logical channels through a single physical connection.

Think of it like a highway (the WebSocket connection). Instead of building a separate road for every single car (data stream), we just have lanes on one big highway. Every car carries a tag saying "I'm going to Exit A" or "I'm going to Exit B".
In our code, this looks like wrapping every message with a type and a chatId.
How It Works
- One Connection: The client connects once to the server.
- Subscription: The client sends a specific message, like
{ type: 'join_chat', chatId: 'discussion-1' }. - Routing: The server maintains a list of subscriptions for that single socket. When a new message arrives for
discussion-1, the server checks who is subscribed and forwards it only to them.
The Code 👨💻
I implemented this using a clean, type-safe approach with TypeScript. Here are the key components that make it work.
1. Data Structures
First, we need to track not just open sockets, but what each socket is interested in. A Map is perfect for this.
2. Handling Messages
We use a single handleMessage function to route actions based on the type field.
3. Broadcasting to Specific Channels
This is the magic part. When a message is sent to a specific chat, we iterate through our connected clients and check if they are subscribed to that specific chatId.
Check It Out! 🔗
I've laid out the full implementation, complete with a dummy data provider and a verification script, on GitHub. It's a great starting point if you want to add efficient real-time features to your next app.
👉 View the Project on GitHub: https://github.com/aiyu-ayaan/WebSocket-Multiplexing
Happy Coding! 🚀