// Engineering notes

WebSocket hibernation for a real-time inbox

Published · ·Last updated ·

EOXLABS designs real-time inboxes as one Durable Object per inbox, holding every connected device's WebSocket through the Hibernation API. Between messages the object sleeps and stops accruing duration charges while clients stay connected. Each message is written to the object's SQLite storage before fan-out, so a reconnecting device replays exactly what it missed.

An inbox here means any ordered stream one person or team watches live: support conversations, alerts, approvals, chat. The pattern is the same.

What does the architecture look like?

A request takes three hops, and each has one job.

  1. The Worker verifies the session token at the edge, resolves the inbox ID, and builds a fresh request carrying the verified user and device IDs. It never forwards client-supplied identity headers.
  2. The Worker gets the inbox's stub with env.INBOX.getByName(inboxId) and forwards the upgrade with stub.fetch(request).
  3. The inbox object accepts the socket, stores messages, and fans them out.

Because a Durable Object is single-threaded, the inbox has a total order without locks. The object assigns each message a sequence number, and that number does the rest of the work in this design.

Which Hibernation API calls does an inbox need?

Every name below is checked against Cloudflare's DurableObjectState reference and DurableObject base class reference.

CallWhat it doesDocumented limit
ctx.acceptWebSocket(ws, tags?)Accepts the server end so the runtime can hibernate the object32,768 connections per object; at most 10 tags of 256 characters each
webSocketMessage(ws, message)Handler for text (string) or binary (ArrayBuffer) framesReceived messages up to 32 MiB
webSocketClose(ws, code, reason, wasClean)Handler when a client closesOn compatibility dates before 2026-04-07 the handler must call ws.close()
webSocketError(ws, error)Handler for errors other than disconnectionNone stated
ws.serializeAttachment(value)Per-connection state that survives hibernation16,384 bytes serialized
ctx.setWebSocketAutoResponse(pair)Answers a fixed request string without waking the object2,048 characters each for request and response
ctx.getWebSockets(tag?)Lists connected sockets, optionally by tagMay include sockets in the CLOSING state

The auto-response exists because browsers can't send protocol pings. The browser WebSocket interface exposes only send() and close(), so a web client's heartbeat is an application message. setWebSocketAutoResponse answers it in the runtime, and the object stays asleep. Protocol-level pings from other clients are answered automatically too.

What does the inbox object look like in code?

import { DurableObject } from "cloudflare:workers";

export class Inbox extends DurableObject<Env> {
  constructor(ctx: DurableObjectState, env: Env) {
    super(ctx, env);
    ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS messages (
      seq INTEGER PRIMARY KEY AUTOINCREMENT, body TEXT NOT NULL, at INTEGER NOT NULL)`);
    ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair("ping", "pong"));
  }

  async fetch(request: Request): Promise<Response> {
    const userId = request.headers.get("x-verified-user") ?? "";
    const deviceId = request.headers.get("x-verified-device") ?? "";
    const [client, server] = Object.values(new WebSocketPair());
    this.ctx.acceptWebSocket(server, [`user:${userId}`]);
    server.serializeAttachment({ userId, deviceId });
    return new Response(null, { status: 101, webSocket: client });
  }

  // Called by the Worker over RPC when a message arrives for this inbox.
  async deliver(body: unknown): Promise<number> {
    const { seq } = this.ctx.storage.sql
      .exec<{ seq: number }>(`INSERT INTO messages (body, at) VALUES (?, ?) RETURNING seq`,
        JSON.stringify(body), Date.now())
      .one();
    const frame = JSON.stringify({ type: "msg", seq, body });
    for (const ws of this.ctx.getWebSockets()) {
      try { ws.send(frame); } catch { /* closing socket: it will replay on reconnect */ }
    }
    return seq;
  }

  async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer) {
    if (typeof message !== "string") return;
    const req = JSON.parse(message);
    if (req.type !== "resume") return;
    const after = Number(req.after) || 0;
    const { oldest } = this.ctx.storage.sql
      .exec<{ oldest: number | null }>(`SELECT MIN(seq) AS oldest FROM messages`).one();
    if (oldest !== null && after < oldest - 1) {
      ws.send(JSON.stringify({ type: "resync" })); // gap is older than retention
      return;
    }
    const rows = this.ctx.storage.sql
      .exec<{ seq: number; body: string }>(
        `SELECT seq, body FROM messages WHERE seq > ? ORDER BY seq LIMIT 500`, after)
      .toArray();
    for (const r of rows) ws.send(JSON.stringify({ type: "msg", seq: r.seq, body: JSON.parse(r.body) }));
  }
}

The sample assumes a compatibility date of 2026-04-07 or later, where the runtime replies to a client's close frame itself, so the class omits webSocketClose. AUTOINCREMENT is deliberate: SQLite then never reuses a sequence number, even after old rows are pruned.

What does hibernation cost, and what is lost when the object sleeps?

Cloudflare's lifecycle reference says an object hibernates after 10 seconds with no incoming request or event, provided no setTimeout or setInterval callback is scheduled, no I/O is pending, and every socket uses the Hibernation API. In-memory state is discarded, and the constructor runs again on the next event. That is why the constructor above does two cheap things and nothing else.

The pricing page sets the cost model:

  • Idle objects eligible for hibernation are not billed for duration.
  • Duration, when it accrues, is charged on the 128 MB the object is allocated, regardless of actual use.
  • Incoming WebSocket messages count as requests at a 20:1 ratio, so 100 incoming messages bill as 5 requests.
  • Outgoing messages and incoming protocol pings are not charged, and auto-responses add no duration.

So the inbox costs money when messages arrive, from clients or from deliver() calls, not while clients sit and listen. Chatty client features, typing indicators above all, belong behind client-side throttling.

StateSurvives hibernation?Where we keep it
The client's connectionYesThe runtime
User and device identityYesThe socket's attachment
Class fieldsNoSQLite, or rebuilt in the constructor
setTimeout timersNo, and a pending one blocks hibernationAn alarm
Message historyYesSQLite

How does fan-out stay bounded?

One object per inbox keeps fan-out proportional to the devices watching that inbox, not to the user base. getWebSockets("user:" + id) narrows a send to one person's devices for read receipts or personal notices. An organization-wide broadcast does not go through one object: each object has a soft limit of 1,000 requests per second, so a Worker or a queue fans the broadcast out across inbox objects instead. Our internal fan-out measurements, with the socket counts and method behind them, are available on request at contact@eoxlabs.dev.

How do reconnection and missed-message replay work?

The client stores the highest contiguous sequence number it has applied. After every reconnect it sends {"type":"resume","after":n}. The object replays rows after n in order, 500 at a time (the client resumes again from the last one it received), or answers resync when the gap is older than retention, and the client refetches over HTTP.

Correctness comes from the single thread. deliver() inserts and sends with no await in between, and the replay reads and sends the same way, so a message is either in the replay or sent live afterward. It can be both: a message delivered between the socket opening and the resume arrives twice. The client treats the sequence number as an idempotency key and sorts by it, so duplicates are harmless.

What would we do differently?

We'd put a protocol version in the first client message from day one. Changing a wire protocol with mobile clients in the field is slow, and a version field makes it possible.

We'd prune history with a scheduled job inside the same object, using Durable Object alarms, not on the write path.

And we'd plan for token expiry on long-lived sockets. A socket authenticated at upgrade can outlive its token, so we store the expiry in the attachment and close the socket once it passes, on the next message or from an alarm, whichever comes first.

This inbox is one instance of the placement argument in edge-native vs edge-deployed. The platform details are on our Durable Objects stack page, the delivery side under product engineering, and related notes in our engineering notes.

— DL

→

Related

+

More engineering notes

Have a system that can’t go dark?

Start a project →