Under The Hood
frontend bun Bun 1.x (WebSockets)

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 equivalent
Node.js with `ws` package (`const wss = new WebSocketServer({ server })`).

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++.

before → after
Node.js ws Manual Set Iteration
clients.forEach(client => client.send(data)); // ❌ Slow JS loop for 50k connections
Bun Native C++ Pub/Sub
server.publish('room-1', message); // ✅ NEW: Fast native broadcast

Interview 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.

Under The Hood — a multi-depth technical interview hub.

Third-party licenses Press ⌘ K to search.