In a Durable Object using WebSocket Hibernation, how do you broadcast to every client, or to one channel, without your own socket list?
answer
- the runtime already knows the sockets
- labels given at accept time
- filter by one label
- closing sockets can still appear
basics
~10 sCall this.ctx.getWebSockets() for every socket the object accepted, or getWebSockets(tag) for one group, where tags were passed to ctx.acceptWebSocket(ws, tags). The runtime keeps that set through hibernation, so no in-memory list is needed.
solid answer
~40 sWith the Hibernation API the runtime, not your class, holds the set of accepted sockets, so a class-field array would be empty after every wake. `this.ctx.getWebSockets()` returns all of them and `this.ctx.getWebSockets(tag)` only those accepted with that tag. Tags are strings you pass at accept time, as in `this.ctx.acceptWebSocket(server, ["user:ana", "channel:general"])`: at most 10 per socket, each up to 256 characters, and `this.ctx.getTags(ws)` reads them back. Nothing in the API changes a socket's tags later, so put stable facts in tags and anything that changes in the socket's attachment or in storage. Loop over the result, skip the sender if needed, and wrap each `send()` in `try`/`catch`, because the list can include sockets already in the `CLOSING` state, and sending on one throws.
code
javascript · 38 linesimport { DurableObject } from "cloudflare:workers";
export class ChatRoom extends DurableObject {
async fetch(request) {
const url = new URL(request.url);
const user = url.searchParams.get("user") ?? "guest";
const channel = url.searchParams.get("channel") ?? "general";
const [client, server] = Object.values(new WebSocketPair());
this.ctx.acceptWebSocket(server, [`user:${user}`, `channel:${channel}`]);
return new Response(null, { status: 101, webSocket: client });
}
async webSocketMessage(ws, message) {
const channelTag = this.ctx.getTags(ws).find((t) => t.startsWith("channel:"));
for (const peer of this.ctx.getWebSockets(channelTag)) {
if (peer === ws) continue;
try {
peer.send(message);
} catch {
// the peer is already closing; webSocketClose cleans it up
}
}
}
async webSocketClose(ws, code, reason) {
ws.close(code, reason);
}
}
export default {
async fetch(request, env) {
if (request.headers.get("Upgrade") !== "websocket") {
return new Response("Expected Upgrade: websocket", { status: 426 });
}
const room = new URL(request.url).searchParams.get("room") ?? "lobby";
return env.CHAT_ROOM.getByName(room).fetch(request);
},
};go deeper
Recall getWebSockets() for everyone, getWebSockets(tag) for a group, and that tags are given as the second argument of acceptWebSocket().
Explain why a class-field list breaks under hibernation while the runtime-held set does not, and quote the 10-tag and 256-character limits.
Show the defensive loop: try/catch around send() for CLOSING sockets, skipping the sender, and keeping changing membership data out of tags.
Discuss the fan-out ceiling of an object that handles one event at a time, and when a room's audience should be split across several objects.
## Why an in-memory socket list fails With the standard API, a chat room usually keeps its own `Set` of sockets and loops over it to broadcast. Under the Hibernation API that pattern breaks. When the object hibernates, its instance is discarded; the next message runs the constructor on a fresh instance, and the `Set` starts empty while thousands of clients are still connected. The runtime, however, never forgets the sockets. It holds them while the object sleeps and exposes them through `DurableObjectState`: - `this.ctx.getWebSockets()` returns an array of every socket accepted with `this.ctx.acceptWebSocket()`. - `this.ctx.getWebSockets(tag)` returns only the sockets accepted with that tag. - `this.ctx.getTags(ws)` returns one socket's tags, and throws for a socket that was not accepted through `acceptWebSocket()`. - Sockets accepted with the standard `ws.accept()` never appear in these results. ## Tags: labels fixed at accept time Tags are plain strings passed as the second argument of `acceptWebSocket()`: ```js this.ctx.acceptWebSocket(server, ["user:ana", "channel:general"]); ``` - Each socket may carry at most **10** distinct tags; an eleventh throws `a Hibernatable WebSocket cannot have more than 10 tags`. - Each tag may be at most **256** characters long. - Duplicate tags in the array are ignored. - `DurableObjectState` has no method that changes a socket's tags after `acceptWebSocket()`. That last rule shapes the design. Put stable facts in tags: the user, the tenant, the channel the connection was opened for. Anything that changes during the connection, such as a nickname or a typing status, belongs in the socket's attachment or in the object's storage. If a user switches channel and the channel is a tag, the client reconnects with the new one. Tag values are free-form strings. A `kind:value` convention such as `user:` and `channel:` keeps them readable and stops a user called `general` from colliding with a channel of the same name. When in doubt, ask whether the value could change before the client disconnects: if it could, it is not a tag. ## Broadcasting with getWebSockets() 1. Decide the audience: no tag for the whole room, `channel:general` for one channel, `user:ana` for every tab one user has open. 2. Call `this.ctx.getWebSockets(tag)`. It is synchronous and returns an array. 3. Skip the sender when the message should not echo back. The `ws` passed to `webSocketMessage()` is the same object as its entry in that array, so `peer === ws` identifies it. 4. Call `peer.send(message)` for each socket, inside `try`/`catch`. A room that wants every client, the sender included, to see the canonical copy of a message, for example with a server timestamp added, simply skips step 3. ## Edge cases in the loop - **Closing sockets are still listed.** A socket in the `CLOSING` state, for example one the server has closed while the client's reply is still outstanding, can appear in `getWebSockets()`. Calling `send()` on it throws `TypeError: Can't call WebSocket send() after close().`, and one bad peer must not abort the broadcast for everyone else. - **Disconnected sockets are not listed.** Once the runtime has detected a disconnect, the socket leaves the set, and `webSocketClose()` is where per-client cleanup runs. - **Fan-out costs CPU in one place.** A Durable Object handles one event at a time, so a loop over 5,000 sockets runs inside a single handler while other messages wait. Each incoming message resets the object's CPU allowance to 30 seconds, but the loop still delays everything queued behind it. - **Many small frames are expensive.** Every WebSocket message carries fixed processing overhead, so batching several logical messages into one frame raises throughput. - **There is a ceiling.** One object may hold at most 32,768 hibernatable sockets, and CPU and memory usually set a lower practical limit. ## Tags, attachments or storage? | Need | Use | Why | |---|---|---| | Find a group of sockets | tags | `getWebSockets(tag)` filters on them directly | | Per-connection data that changes | attachment | `serializeAttachment()` can be called again at any time | | Data over 16 KiB, or needed after the connection ends | storage | attachments are capped and die with the connection | A broadcast therefore needs no bookkeeping of its own. The runtime holds the membership, tags give it shape, and the handler only decides who should hear the message and survives the peers that are on their way out.
- How would you send a direct message to one user who may have several tabs open?Tag each socket with its user at accept time, such as `user:ana`, then send to every socket in `this.ctx.getWebSockets("user:ana")`. Several tabs are simply several sockets carrying the same tag, and the runtime keeps those tags through hibernation, so no lookup table is needed.
- Why can a broadcast to thousands of sockets in one object become a bottleneck?A Durable Object runs one event at a time, so the fan-out loop spends its CPU inside a single handler while every other message waits. Batching several logical messages into one frame cuts the per-message overhead; beyond that, the audience has to be split across several objects.
- Keeps sockets in a class-field array and broadcasts from it after hibernation.
- Assumes getWebSockets() returns only sockets that are fully open.
- Plans to retag a socket when its user switches channel, as if tags could change.
- Thinks getWebSockets() also returns sockets accepted with ws.accept().