# WebSocket hibernation for a real-time inbox

URL: https://eoxlabs.dev/engineering/websocket-hibernation-realtime-inbox
Last updated: 2026-11-26
Published: 2026-11-26
Publisher: EOXLABS (https://eoxlabs.dev)

Section: [Engineering notes](https://eoxlabs.dev/engineering)

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](https://developers.cloudflare.com/durable-objects/api/state/) and [DurableObject base class reference](https://developers.cloudflare.com/durable-objects/api/base/).

| Call | What it does | Documented limit |
|---|---|---|
| `ctx.acceptWebSocket(ws, tags?)` | Accepts the server end so the runtime can hibernate the object | 32,768 connections per object; at most 10 tags of 256 characters each |
| `webSocketMessage(ws, message)` | Handler for text (`string`) or binary (`ArrayBuffer`) frames | Received messages up to [32 MiB](https://developers.cloudflare.com/durable-objects/platform/limits/) |
| `webSocketClose(ws, code, reason, wasClean)` | Handler when a client closes | On compatibility dates before 2026-04-07 the handler must call `ws.close()` |
| `webSocketError(ws, error)` | Handler for errors other than disconnection | None stated |
| `ws.serializeAttachment(value)` | Per-connection state that survives hibernation | [16,384 bytes serialized](https://developers.cloudflare.com/durable-objects/best-practices/websockets/) |
| `ctx.setWebSocketAutoResponse(pair)` | Answers a fixed request string without waking the object | 2,048 characters each for request and response |
| `ctx.getWebSockets(tag?)` | Lists connected sockets, optionally by tag | May include sockets in the `CLOSING` state |

The auto-response exists because browsers can't send protocol pings. The [browser WebSocket interface](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) 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?

```ts
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](https://developers.cloudflare.com/durable-objects/concepts/durable-object-lifecycle/) 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](https://developers.cloudflare.com/durable-objects/platform/pricing/) 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.

| State | Survives hibernation? | Where we keep it |
|---|---|---|
| The client's connection | Yes | The runtime |
| User and device identity | Yes | The socket's attachment |
| Class fields | No | SQLite, or rebuilt in the constructor |
| `setTimeout` timers | No, and a pending one blocks hibernation | An alarm |
| Message history | Yes | SQLite |

## 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](https://eoxlabs.dev/engineering/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](https://eoxlabs.dev/engineering/edge-native-vs-edge-deployed). The platform details are on our [Durable Objects stack page](https://eoxlabs.dev/stack/durable-objects), the delivery side under [product engineering](https://eoxlabs.dev/capabilities/product-engineering), and related notes in our [engineering notes](https://eoxlabs.dev/engineering).

— DL

## Related

- [Durable Objects](https://eoxlabs.dev/stack/durable-objects): Durable Objects give EOXLABS one single-threaded, authoritative home for each piece of shared state, with clear guarantees, hard limits and cases where another store is better.
- [Product Engineering](https://eoxlabs.dev/capabilities/product-engineering): Prepare A Launch: EOXLABS designs, builds and deploys a new product from zero, with the architecture, code, pipelines and runbooks a production system needs.
- [Durable Object alarms instead of background jobs](https://eoxlabs.dev/engineering/durable-object-alarms): Replacing process-model background jobs with Durable Object alarms, with verified semantics, a TypeScript scheduler that runs many jobs on one alarm, idempotency rules and a decision list.
- [Edge-native vs edge-deployed](https://eoxlabs.dev/engineering/edge-native-vs-edge-deployed): What separates an edge-native system from one that only runs its handlers at the edge, with a comparison table and the architecture smells that give an edge-deployed system away.
- [WebSocket Hibernation](https://eoxlabs.dev/glossary/websocket-hibernation): WebSocket hibernation lets a Durable Object be evicted from memory while its WebSocket clients stay connected, so idle real-time connections stop costing compute time.

## More engineering notes

- [Envelope encryption for OAuth tokens on Workers](https://eoxlabs.dev/engineering/envelope-encryption-oauth-tokens)
- [Why sub-50 ms is a defensible edge claim and sub-2 ms is not](https://eoxlabs.dev/engineering/sub-50ms-edge-latency)
- [Designing backups that survive ransomware](https://eoxlabs.dev/engineering/ransomware-resilient-backups)
