rhythmjs

Search documentation

Search guides, the tutorial and every package.

On this page

The websocket handler#

Bun wants one websocket object next to fetch. @rhythmjs/ws exports it ready-made. Each event looks up the route handlers carried by the connection's ws.data and forwards to them (open, message, drain, close, ping, pong), so a single object serves connections upgraded by every RhythmWs in the app, however many you mount.

TypeScript
import { toFetchHandler } from "@rhythmjs/router/fetch";
import { websocket } from "@rhythmjs/ws";

Bun.serve({
  port: 3000,
  fetch: toFetchHandler(app),
  websocket,
});

fetch: toFetchHandler(app) is what makes this work: it calls the app as fetch(request, server), so ctx.server is Bun's server and the upgrade can take the socket. There is no server wrapper anywhere in the ecosystem; this is the same Bun.serve call you already own.

Tuning with createWebsocket#

websocket is createWebsocket() with Bun's defaults. Call createWebsocket(behavior) to set Bun's per-server options; they are passed to Bun verbatim:

TypeScript
import { createWebsocket } from "@rhythmjs/ws";

Bun.serve({
  fetch: toFetchHandler(app),
  websocket: createWebsocket({
    maxPayloadLength: 64 * 1024,
    idleTimeout: 60,
    backpressureLimit: 1024 * 1024,
    closeOnBackpressureLimit: true,
    publishToSelf: false,
  }),
});
maxPayloadLength#
Largest message accepted, in bytes. Oversized messages close the connection. Set it to what your protocol needs, not to Bun's generous default.
idleTimeout#
Seconds of inactivity before Bun closes the socket. Pair it with sendPings or client heartbeats so quiet but healthy connections survive.
backpressureLimit#
Buffered outgoing bytes before send reports backpressure (it returns -1 when queued, 0 when dropped).
closeOnBackpressureLimit#
Close the connection when the limit is exceeded, so one slow reader cannot hold memory forever.
sendPings#
Send automatic pings to keep idle connections open through proxies.
publishToSelf#
Whether peer.publish also delivers to the publisher. Off by default; cursor-style apps want it off, simple echo chats on.
perMessageDeflate#
Compression settings. Trades CPU and memory per connection for bandwidth.

Because one handler serves every instance, these limits are per server, not per route. If two endpoints need different limits (a chat with small messages and an upload channel with large ones), set the limit for the larger and enforce the smaller one in that route's message.

Multiple instances, one server#

Split connection routing the way you split controllers: separate RhythmWs instances, each with its own middleware and its own routes, mounted into one app. Each runs only its own middleware, and one websocket handler serves them all:

TypeScript
const app = new Rhythm()
  .use(mount(http))
  .use(mount(publicWs)) // /ws/status
  .use(mount(memberWs)); // /ws/inbox, behind session and login middleware

An instance has its own origin option, so a public status feed can allow other origins while the member socket stays same-origin only.

Scaling out#

Bun's pub/sub is in-process: peer.publish and server.publish reach sockets connected to the same server instance only. A second replica never sees them. To run replicas, relay publishes through a backplane you own (Redis pub/sub, NATS): publish to the backplane from your handlers and HTTP routes, and in each instance's subscriber call server.publish so every instance fans out to its own sockets.

TypeScript
// backplane: any pub/sub client you own (Redis, NATS, ...)
backplane.subscribe("chat", (message) => server.publish("room:lobby", message));

// in handlers and routes: publish to the backplane, not to Bun directly
backplane.publish("chat", JSON.stringify(event));

Keep memberships in ws.data: they die with the connection, so no cross-instance membership store is needed for fan-out. Sticky routing is only required if you keep other per-connection state outside the process.

Testing#

Handshakes, middleware, upgrade, and handlers all run without sockets under @rhythmjs/testing/ws; upgradeWs exercises the whole upgrade path against a mock Bun server.