Native uSockets Integration: permessage-deflate & 1M Connection Scaling
- Last updated
- Prerequisites:
- WebSocket protocol basics
- Node.js `ws` package
- bun
- websockets
- usockets
- scaling
- real-time
- pubsub
Read at your depth
The practical view
Bun has native WebSocket support built into `Bun.serve()`. You handle WebSocket connections using the `websocket` object handlers (`open`, `message`, `close`, `drain`). Bun includes built-in **Server-Side Pub/Sub**: `ws.subscribe('chat-room')`, `server.publish('chat-room', 'Hello everyone!')`. This eliminates the need for Redis or external brokers for local broadcast clustering.
The same idea in other frameworks
Node.js with `ws` package (`const wss = new WebSocketServer({ server })`).`Deno.upgradeWebSocket(req)`.`Bun.serve({ websocket: { message(ws, msg) {} } })` with built-in Pub/Sub.Gorilla WebSocket / `nhooyr.io/websocket`.Legacy vs modern
Node.js ws Manual Broadcast vs Bun Native Pub/Sub
Node requires manually iterating Set collections in JS to broadcast; Bun publishes natively in C++.
clients.forEach(client => client.send(data)); // ❌ Slow JS loop for 50k connectionsserver.publish('room-1', message); // ✅ NEW: Fast native broadcastInterview gotchas
Context
Interviewers test your knowledge of concurrent socket connection economics.
The mechanical answer
In Node.js with the `ws` package, each WebSocket connection consumes ~30-50KB of RAM (due to JS object instances, event emitter listeners, and buffer wrappers), requiring **3 to 5 Gigabytes** of RAM for 100k connections. In Bun, connections are managed as compact C structs (~2KB per socket), requiring only **~200-300 Megabytes** of RAM for the same 100k connections.
Trap
Do not claim Bun WebSockets are faster only because of CPU; the primary advantage is memory efficiency and C++ level broadcast loop execution.
Context
Checks knowledge of socket buffer overflow management.
The mechanical answer
`ws.send(data)` returns a number: `-1` if dropped, `0` if dropped due to backpressure, or a positive byte length indicating bytes queued. You can check `ws.getBufferedAmount()` and listen to the `drain(ws)` handler to resume sending data when the slow client's TCP socket buffer drains.
Trap
Ignoring `ws.getBufferedAmount()` on high-volume streams can cause unconstrained memory buffering for slow clients.