A Durable Object chat room using ctx.acceptWebSocket() keeps each client's name in a class-field Map, and after quiet spells messages show "unknown"; why, and what fixes it?
answer
- sockets outlive the instance
- the constructor runs again
- a small copy travels with each socket
- 16 KiB, structured clone
- bigger data goes to storage
basics
~20 sHibernation evicted the object: the sockets stayed connected, but class fields were discarded and the constructor ran again on the next message. Store per-socket data with ws.serializeAttachment() at accept time and read it back with ws.deserializeAttachment().
solid answer
~40 sWith the Hibernation API an idle object is evicted from memory while its clients stay connected. When the next message arrives, the runtime builds a new instance, runs the constructor and calls `webSocketMessage()`; the `Map` the old instance filled is gone, so the lookup misses and the code falls back to "unknown". The fix is to keep per-connection data with the socket: call `server.serializeAttachment({ name })` right after `this.ctx.acceptWebSocket(server)` and read it with `ws.deserializeAttachment()` in each handler. The value is a structured-clone copy of at most 16,384 bytes, so call `serializeAttachment()` again after every change, and keep larger or longer-lived data in the object's storage with only its key in the attachment. If an in-memory index is still useful, rebuild it in the constructor from `this.ctx.getWebSockets()` and their attachments.
code
javascript · 40 linesimport { DurableObject } from "cloudflare:workers";
export class ChatRoom extends DurableObject {
async fetch(request) {
const name = new URL(request.url).searchParams.get("name") ?? "guest";
const [client, server] = Object.values(new WebSocketPair());
this.ctx.acceptWebSocket(server);
server.serializeAttachment({ name, joinedAt: Date.now() });
return new Response(null, { status: 101, webSocket: client });
}
async webSocketMessage(ws, message) {
const session = ws.deserializeAttachment();
if (typeof message === "string" && message.startsWith("/nick ")) {
ws.serializeAttachment({ ...session, name: message.slice(6) });
return;
}
for (const peer of this.ctx.getWebSockets()) {
try {
peer.send(`${session.name}: ${message}`);
} catch {
// the peer is already closing
}
}
}
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 that hibernation keeps the sockets open but throws away the object's memory, and that serializeAttachment() keeps data with each socket.
Explain the wake sequence of new instance, constructor, then handler, and why a class-field Map is empty at that point.
Diagnose from the symptom, fine while busy and wrong after quiet spells, then fix with attachments, re-serializing after each change and moving large data to storage.
Set the rule that a hibernating object treats memory as a cache only, and make an idle-gap test part of review for every WebSocket object.
## What hibernation keeps and what it drops Under the Hibernation API, an idle Durable Object is evicted from memory while its clients stay connected. The runtime keeps what it owns; whatever only your instance held is gone. | Kept by the runtime | Discarded with the instance | |---|---| | the WebSocket connections | class fields, such as a `Map` of names | | each socket's tags | caches and indexes built in memory | | each socket's attachment | values set up in the constructor, until it runs again | | the object's storage | | The next message rebuilds the instance: 1. The runtime creates a new instance of the class and runs the `constructor`. 2. It calls `webSocketMessage(ws, message)` on that new instance. 3. Code such as `this.names.get(ws) ?? "unknown"` finds an empty `Map`, and the fallback is what the room sees. ## Why the bug hides - **Busy rooms never idle.** The runtime currently hibernates an eligible object after about 10 seconds without events, so a test with steady traffic never triggers it. - **It looks intermittent.** The symptom appears only after quiet spells, so it shows up first in small rooms, at night, or in production. A test that drives the object without an idle gap passes for the same reason. - **Local development hibernates too.** `wrangler dev` evicts hibernatable objects as well, so a test that leaves a socket idle for more than 10 seconds and then sends a message reproduces it on a laptop. - **Deploys look similar but are different.** A deploy restarts every object and disconnects every socket, so clients reconnect and the room starts over. Hibernation drops memory while the sockets stay connected, which is exactly why stale assumptions break. ## The fix: attachments 1. Right after `this.ctx.acceptWebSocket(server)`, call `server.serializeAttachment({ name, joinedAt })`. 2. In every handler, read it with `ws.deserializeAttachment()`. 3. When the data changes, for example on a `/nick` command, build the new value and call `ws.serializeAttachment()` again. 4. If the room needs an in-memory index, rebuild it in the constructor by walking `this.ctx.getWebSockets()` and reading each attachment, or build it lazily inside the handler. A constructor that rebuilds the index looks like this: ```js constructor(ctx, env) { super(ctx, env); this.names = new Map(); for (const ws of this.ctx.getWebSockets()) { const session = ws.deserializeAttachment(); if (session) this.names.set(ws, session.name); } } ``` The `Map` is now only a cache of the attachments, rebuilt on every wake, so it can never disagree with them for long. ## Attachment rules - The value can be anything the structured clone algorithm supports: plain objects, arrays, dates, maps. - The runtime stores a **copy**. Changing the original object afterwards changes nothing until you call `serializeAttachment()` again. - The serialized size is capped at 16,384 bytes; a larger value throws `A WebSocket 'attachment' cannot be larger than 16384 bytes.` - `deserializeAttachment()` returns `null` when nothing was attached. - Attachments persist through hibernation for as long as the connection is healthy, and they are lost when either side closes it. ## When an attachment is not enough Some data does not fit the attachment model: a chat history, a large profile, or anything that must outlive the connection. Keep that in the object's storage and put only its key in the attachment, so a handler reads storage by key when it needs the rest. An attachment is the right home for what identifies the connection and is needed on almost every message: the user id, the display name, a role. A useful split for a chat room is that the attachment holds `userId`, `name` and `role`, while storage holds the message history and per-user settings keyed by `userId`. Each handler then reads the attachment first and touches storage only when the message needs it. Keep the constructor short as well. On a hibernating object it runs on every wake, so a constructor that loads a large dataset or recomputes an index from scratch turns every message after a quiet spell into a slow one. The safest rule for a hibernating object is that memory is only a cache: anything the room cannot afford to lose lives in an attachment or in storage, and the code always works when the cache is empty.
- Why not reload the names from storage on every message instead?You can, but it adds a storage read to every message for data that belongs to one socket and ends with it. `deserializeAttachment()` is synchronous and needs no storage call. Storage is the right place for data that must outlive the connection or exceed 16,384 bytes, with its key kept in the attachment.
- Does an attachment survive a deploy of new code?No. Deploying a new version restarts every Durable Object and disconnects all of its WebSockets, and attachments are lost when the connection closes. Clients reconnect and the object writes fresh attachments, so anything that must survive a deploy belongs in storage.
A night-shift hotel clerk: when one clerk goes home, the guests stay in their rooms, and the next clerk arrives knowing only what is written on each room's key tag. Whatever the first clerk kept on a personal notepad is gone. Class fields are the notepad, attachments are the key tags, and the constructor is the new clerk arriving.
- Assumes class fields persist while clients stay connected to a hibernated object.
- Mutates the value returned by deserializeAttachment() and expects the change to persist.
- Stores a whole chat history in the attachment, ignoring the 16 KiB limit.
- Does heavy setup in the constructor, which now runs on every wake.
- Believes wrangler dev never hibernates objects, so the bug must be production-only.