Back to Cloudflare

Coordinate State With Durable Objects

November 5, 2026 Updated November 6, 2026 Wasil Zafar 27 min read

Model object identity, transactions, and realtime sessions

Table of Contents

  1. An Object ID Defines a Coordination Boundary
  2. Durable Storage and Concurrent Requests
  3. WebSockets, Hibernation, and Reconnects
  4. State Location, Lifecycle, and Failure Recovery
  5. Design a Small Room or Reservation Coordinator
  6. Exercise Concurrent Requests and a Client Reconnect

An Object ID Defines a Coordination Boundary

At 09:00 two guests open the last king room at a small inn. Their requests land on two Worker isolates. Both read available, both write booked, and the room is sold twice. A retry cannot help; both decisions already happened.

The fix is not a bigger database. A unique constraint in a shared database can stop this one double-booking; what it cannot do is put the check, the expiry timer, and the live socket in the same execution boundary. The fix is one place where those decisions become a sequence: a Durable Object, a globally unique, single-threaded compute instance with private, durable storage attached.

Five terms make the rest precise:

  • A namespace is the deployed binding that creates and routes to objects of one class. It is the factory, not the object.
  • A class is your TypeScript code: methods, schema, handlers.
  • An object is one running instance of that class, identified by a DurableObjectId.
  • A stub is a client handle to one object. Creating it does not start the object; the first method call does.
  • Object storage is a private SQLite database that only that object can read or write.

The analogy is a hotel front desk. One clerk with one ledger can promise a room without double-booking, because every promise passes the same hands. Forty clerks with photocopies cannot, however fast they write. The object is the clerk; storage is the ledger; the ID is which clerk you get.

That is the design decision. The ID is both the routing key and the consistency boundary. Requests that resolve to room:ATL-204 reach the same object, in one location, one event at a time. Requests for room:ATL-205 reach a different object with different storage. There is no shared memory and no cross-object transaction.

Figure 1 shows the path. Two guests targeting the same room converge on one object; a third guest targeting another room diverges. The convergence is the feature.

An Object ID Defines a Coordination Boundary
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["Guest A: hold ATL-204"] --> W["Worker: authenticate, validate, pick key"]
    B["Guest B: hold ATL-204"] --> W
    C["Guest C: hold ATL-205"] --> W
    W -->|"idFromName('room:ATL-204')"| D1["Room object ATL-204
single-threaded + private SQLite"] W -->|"idFromName('room:ATL-205')"| D2["Room object ATL-205
separate SQLite"] D1 --> R1["One serialized decision per hold"] D2 --> R2["Independent decision"] D1 -. "no shared storage or transaction" .-> D2 classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class A,B,C,D1,D2,R1,R2 secondary; class W ok;

Figure 2 redraws the same system as boundaries. Clients cross a public trust boundary into a stateless Worker fleet. The Worker resolves an ID and crosses into one object's private execution boundary. That boundary is where the invariant lives.

Where a Durable Object boundary begins and ends Browser clients cross a public boundary into stateless Worker isolates. The Worker resolves a name to an object ID. That ID selects exactly one single-threaded object with private SQLite storage, its own alarm, and hibernatable sockets. Other IDs have separate storage. Public trust boundary Browser A session cookie Browser B session cookie No object ID yet. No shared memory. Worker boundary Isolate 1: auth, validate, choose key Isolate 2: same code, no shared memory Stateless and replicable. The ID decides the rest. Namespace class Room- Coordinator idFromName( "room:ATL-204") stable ID Same name, same ID. Different name, different object. Object boundary One instance single-threaded one location SQLite storage alarm slot hibernatable sockets Private: no other object can read it. No cross-object transaction. request resolve route

Choosing the atom is the design act. Ask what must never be true: for the inn, that a room is promised twice. Which requests can violate it? Any hold for that room. What key contains all of them? The room.

If the key is too coarse — one object for the inn — unrelated rooms serialize into a queue. If it is too fine — one object per date — a multi-night stay spans objects and no transaction checks the interval. Cloudflare's seat-booking example draws the same line: one object per event, because the invariant is "a seat is sold once."

A subtler case: the inn also promises that one guest cannot hold two overlapping rooms. That invariant spans rooms, so per-room objects cannot enforce it alone. Widen the boundary to the property, or keep per-room objects and add a per-guest index with a compensating check.

Use deterministic names for stable entities. idFromName("room:atl-204") returns the same ID forever, so any Worker routes to the same object. Normalize case and whitespace yourself. newUniqueId() is only for objects whose ID you will store and look up. Cloudflare's chat demo uses one object per room for this reason: the room name is the key everyone already has.

Coordinate, or cache — not both

Keep an object only where requests must agree on an ordering. For data that every request needs but nobody coordinates — catalogs, flags, static configuration — KV or R2 reads are cheaper and do not serialize.

Durable Storage and Concurrent Requests

The two holds now reach one object. What stops them from interleaving?

Three guards keep one object's events in order. A fourth closes the gate unconditionally, including across I/O.

GuardWhat it doesWhy it matters
Input gatesStop new events while synchronous JavaScript runs, and stay closed while a storage operation is in flightA read-modify-write cannot interleave
Output gatesHold outgoing network messages until pending writes are confirmed durableA response never precedes its commit
Write coalescingMerge writes with no intervening await into one atomic commitSeveral calls become one commit
blockConcurrencyWhileClose the gate unconditionally, including across I/OSetup only, never request handling

That makes a read-modify-write safe: read the count, add one, write it back. No request can slip between the two calls, because both hold the input gate. A synchronous SQL SELECT followed by an INSERT behaves the same way.

An await opens the gate

The gate is not a global lock. An await fetch(...) opens it, so other requests run while this object waits. A booking flow that reads a hold, calls a payment provider, then writes "confirmed" has a race window. Move the external call outside the decision, or use a version column and compare-and-set on write.

Use the blocking gate only for setup. It is the wrong tool for request handling and the right one for one-time schema setup. Cloudflare's guidance is blunt: a 5 ms callback caps throughput near 200 requests per second, and a callback that throws resets the object. Use it in the constructor; use storage.transactionSync() for multi-statement SQL while serving traffic.

The layers inside that boundary are not interchangeable:

State layerSurvives eviction?Transaction scopeBilled asUse it for
In-memory field (this.cache)NoNone across eventsWall-clock duration while activeHot caches, socket registries, derived state that can be rebuilt
ctx.storage KV methodsYesEach call atomic; writes without await coalesceRows read and rows writtenSmall documents, flags, per-object indexes
SQLite table via sql.execYesStatement or implicit transaction; transactionSync for severalRows read and written, plus stored GB-monthsReservations, ledgers, message logs, range queries
Alarm (setAlarm)Yes, the scheduled time persistsOne alarm per objectOne row write, plus an invocation requestHold expiry, retries, periodic sweeps
D1, R2, QueuesYes, outside the objectSeparate service; no shared transactionProduct-specificCross-object reporting, blobs, fan-out

Figure 3 shows the hold path, including the commit failure branch. The response leaves only after the write is durable. If the write fails, the output gate discards the response and the caller sees an error, not a false confirmation.

Durable Storage and Concurrent Requests
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
sequenceDiagram
    autonumber
    participant A as Guest A
    participant B as Guest B
    participant W as Worker
    participant D as Room object
    participant S as SQLite storage
    A->>W: POST hold, Idempotency-Key K1
    B->>W: POST hold, Idempotency-Key K2
    W->>D: reserve(K1), reserve(K2)
    Note over D: one event at a time — input gate closed during storage
    D->>S: transactionSync: check overlap
    alt no overlap
        D->>S: INSERT hold + request K1
        S-->>D: committed
        D-->>W: 201 hold
        W-->>A: 201
    else overlap
        D->>S: INSERT request K2 only
        S-->>D: committed
        D-->>W: 409 conflict
        W-->>B: 409
    end
    opt commit fails
        S--xD: write rejected
        Note over D: output gate withholds response
        D-->>W: 5xx, caller retries K1
    end

The middle row is where most production state belongs. SQLite gives range queries, indexes, and transactionSync; the KV methods still work on a hidden table.

The limits are concrete: 10 GB per object on the paid plan, 2 MB for a key and value combined, 2 MB per SQL row, 100 KB per statement, and 100 bound parameters per query. A Free account also has a 5 GB account-wide cap, so "unlimited objects" is not "unlimited bytes."

The product boundary matters. Since July 2026, new Durable Object namespaces must use the SQLite backend. The key-value backend remains only for accounts that already had one, and on the Free plan only SQLite-backed objects exist.

Declare the class with the current exports entry and a SQLite storage setting; legacy projects use new_sqlite_classes. Mixing both forms is rejected.

Storage is not a shared database. You cannot open the file with a SQL client, join across objects, or read another object's rows. Stream changes outward to D1, R2, or analytics instead.

Alarms complete the model. Each object has one alarm slot: setAlarm(t) wakes it at or after t.

Delivery is at least once. alarm() is retried with exponential backoff from two seconds, up to six retries. Store a schedule table, process everything due, then set the next alarm. Make the handler idempotent, and catch external failures so you can reschedule explicitly.

The same shape yields two more primitives. A lock is an object with one holder row and a lease that an alarm expires; a queue is an object with a table of due jobs and one alarm that drains it. Both inherit the single-writer guarantee, and both need idempotent handlers because the alarm can run twice.

The widget implements those rules: schema migration under the concurrency gate, overlap checking and idempotency in one transactionSync, an earliest-expiry alarm, and a confirm that cannot revive an expired hold.

import { DurableObject } from "cloudflare:workers";

export interface Env {
  ROOM: DurableObjectNamespace<RoomCoordinator>;
}

type ReserveResult =
  | { ok: true; holdId: string }
  | { ok: false; reason: "overlap" };

const HOLD_MS = 10 * 60 * 1000;

export class RoomCoordinator extends DurableObject<Env> {
  constructor(ctx: DurableObjectState, env: Env) {
    super(ctx, env);
    // One-time schema setup. Keep this callback short and local.
    ctx.blockConcurrencyWhile(async () => {
      ctx.storage.sql.exec(`
        CREATE TABLE IF NOT EXISTS holds (
          hold_id TEXT PRIMARY KEY,
          guest_id TEXT NOT NULL,
          check_in TEXT NOT NULL,
          check_out TEXT NOT NULL,
          status TEXT NOT NULL,
          expires_at INTEGER NOT NULL
        );
        CREATE INDEX IF NOT EXISTS holds_window
          ON holds (check_in, check_out);
        CREATE TABLE IF NOT EXISTS requests (
          request_id TEXT PRIMARY KEY,
          response TEXT NOT NULL
        );
      `);
    });
  }

  async reserve(
    requestId: string,
    guestId: string,
    checkIn: string,
    checkOut: string,
  ): Promise<ReserveResult> {
    const result = this.ctx.storage.transactionSync((): ReserveResult => {
      const prior = this.ctx.storage.sql
        .exec<{ response: string }>(
          "SELECT response FROM requests WHERE request_id = ?",
          requestId,
        )
        .toArray()[0];
      if (prior) return JSON.parse(prior.response) as ReserveResult;

      const clash = this.ctx.storage.sql
        .exec<{ hold_id: string }>(
          `SELECT hold_id FROM holds
            WHERE status IN ('held', 'confirmed')
              AND check_in < ? AND check_out > ?
            LIMIT 1`,
          checkOut,
          checkIn,
        )
        .toArray()[0];

      const next: ReserveResult = clash
        ? { ok: false, reason: "overlap" }
        : { ok: true, holdId: crypto.randomUUID() };

      if (next.ok) {
        this.ctx.storage.sql.exec(
          `INSERT INTO holds
             (hold_id, guest_id, check_in, check_out, status, expires_at)
           VALUES (?, ?, ?, ?, 'held', ?)`,
          next.holdId,
          guestId,
          checkIn,
          checkOut,
          Date.now() + HOLD_MS,
        );
      }
      this.ctx.storage.sql.exec(
        "INSERT INTO requests (request_id, response) VALUES (?, ?)",
        requestId,
        JSON.stringify(next),
      );
      return next;
    });

    if (result.ok) await this.armExpiry();
    return result;
  }

  confirm(holdId: string): boolean {
    const cursor = this.ctx.storage.sql.exec(
      `UPDATE holds SET status = 'confirmed', expires_at = 0
        WHERE hold_id = ? AND status = 'held' AND expires_at > ?`,
      holdId,
      Date.now(),
    );
    return cursor.rowsWritten > 0;
  }

  async alarm(): Promise<void> {
    this.ctx.storage.sql.exec(
      "DELETE FROM holds WHERE status = 'held' AND expires_at <= ?",
      Date.now(),
    );
    await this.armExpiry();
  }

  private async armExpiry(): Promise<void> {
    const row = this.ctx.storage.sql
      .exec<{ next: number | null }>(
        "SELECT MIN(expires_at) AS next FROM holds WHERE status = 'held'",
      )
      .one();
    const current = await this.ctx.storage.getAlarm();
    if (row.next !== null && (current === null || row.next < current)) {
      await this.ctx.storage.setAlarm(row.next);
    }
  }
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);
    const match = url.pathname.match(/^\/rooms\/([^/]+)\/reserve$/);
    if (!match || request.method !== "POST") {
      return new Response("Not found", { status: 404 });
    }
    const body = await request.json<{
      guestId: string;
      checkIn: string;
      checkOut: string;
    }>();
    const stub = env.ROOM.getByName(match[1]);
    const result = await stub.reserve(
      request.headers.get("Idempotency-Key") ?? crypto.randomUUID(),
      body.guestId,
      body.checkIn,
      body.checkOut,
    );
    return Response.json(result, { status: result.ok ? 201 : 409 });
  },
} satisfies ExportedHandler<Env>;

WebSockets, Hibernation, and Reconnects

The same room object can hold the browser connection that watches availability. That is convenient and easy to get wrong in two ways: authorization and memory.

Authorize before the upgrade, at the Worker. Check the session cookie, verify the room membership claim, and mint a short-lived connect ticket bound to the room, subject, expiry, and a nonce. The object verifies the signature and the room before calling ctx.acceptWebSocket(server).

Identity never travels in a query string. Do not accept ?user=alice: query strings land in logs, and a browser WebSocket cannot set arbitrary headers, so the ticket or cookie is the carrier.

After acceptance, the connection outlives the object's memory. Store per-connection state in the socket attachment; everything else dies with the instance.

// Run on upgrade, after the ticket check.
const pair = new WebSocketPair();
this.ctx.acceptWebSocket(pair[1]);
pair[1].serializeAttachment({ sub, role, exp, lastSeq });
{
  "sub": "guest:ATL-204",
  "role": "viewer",
  "exp": 1793923200,
  "lastSeq": 1841
}
# Inspect attachment and hibernation events in the deployed object.
npx wrangler tail room-coordinator --format json

Attachments survive hibernation, die with the socket, and are capped at 16,384 bytes. In-memory fields, a subscriber map, and a heartbeat timer are gone when the object sleeps.

Hibernation makes this affordable. If an object has no events for about ten seconds, no timers, no unfinished waitUntil, no outbound connection, and no socket accepted with the standard ws.accept() API, the runtime may remove it from memory while clients stay connected. The next message runs the constructor again.

Incoming messages are billed at a 20:1 ratio for requests; outgoing messages and protocol pings are not charged, and duration charges stop while the object hibernates. The standard API keeps the object resident for the connection's life and is the expensive choice for idle rooms.

Reconnects need a resume protocol, not just a retry. Give every room event a monotonic sequence number in SQLite and let the client reconnect with ?since=1841. The object replays rows after that sequence up to a bounded window, then sends a snapshot if the gap is too large. The client backs off exponentially with full jitter — roughly 0.5 s base, 30 s cap — rather than every tab retrying on the same second.

Design for the reconnect storm

A deploy is a reconnect event. A deploy, network blip, or forced update disconnects many sockets at once, and immediate retries look like the hot-object burst described later. Jitter on the client, budget accepts per object in the Worker, answer 429 or 503 with Retry-After, and close slow consumers with 1013 instead of buffering without limit.

Hibernatable sockets survive a code update if they are already hibernated; a forced update disconnects them.

A single object can accept up to 32,768 hibernatable sockets, but CPU and message rate bind first. Batch high-frequency updates into one frame every 50–100 ms, cap messages per socket per second, and authorize on connect rather than on every message.

State Location, Lifecycle, and Failure Recovery

Placement follows the first request. Cloudflare puts a new object near the data center that made the first get() call, and at the time of writing it does not move afterward. The three controls differ in how much choice you actually get.

ControlExampleStrengthConsequence
First requestget() on a stubStickyThe object stays near the first caller's data center
Location hint"weur"Best effortThe runtime picks a nearby data center, not necessarily the hinted one
Jurisdiction"eu"Hard constraintThe same name in another jurisdiction produces a different ID

Placement is a latency tax, not a correctness bug. A room shared by Singapore and Dublin always pays a round trip for one of them. Hint region-specific rooms; for a global room, accept the RTT or split by region and reconcile asynchronously. Pre-creating objects before real traffic usually reflects a batch job's location rather than the users'.

Lifecycle explains most "it forgot" bugs. An object is inactive until a method call on a stub. It becomes active, handles events, then idles. If it meets the hibernation conditions it leaves memory after about ten seconds; otherwise it is evicted after roughly 70–140 seconds. Both paths discard memory. The constructor runs again on the next event, so initialization must be idempotent and migrations safe to re-run.

There are no shutdown hooks. Cloudflare is explicit that hooks would be unreliable, so the contract is "write incrementally." On shutdown, in-flight HTTP and RPC requests that do not touch storage may finish; one that touches storage is stopped to preserve global uniqueness. WebSocket connections are terminated. A deferred code update gives an object time to hibernate; an immediate update resets it. Design every handler as if the process can disappear between two lines.

Figure 4 contrasts the healthy path with a crash between commit and response. The retry is safe only because the request key and its response commit together.

What survives a crash between commit and response The healthy path validates, commits the hold and request key together, then returns 201. In the failure path the instance dies after commit and before the response. The client retries with the same idempotency key, the object restarts, finds the stored response, and returns the same 201 without a second hold. Healthy: respond only after commit POST + key K hold ATL-204 transactionSync check overlap INSERT hold + request K COMMIT 201 Created Failure: crash after commit, before response Retry, same K same dates object restarts constructor runs request table hit for K return stored 201 no second hold instance dies here The same key plus the stored response is what makes the retry safe. Survives eviction: SQLite rows, alarm time, serialized attachment Lost on eviction: in-memory fields, setTimeout, standard-API sockets

Four failure modes recur in production, and each has a recognizable signature.

Hot objects. A single object has a soft ceiling near 1,000 requests per second for simple operations; beyond that it queues, then returns an overloaded error. The signature is rising latency and overloads on one ID, often a global counter or lobby. Use a finer key: shard counters and sum on read, or split a lobby by topic.

Unbounded storage. An object grows until it hits 10 GB, then writes fail with SQLITE_FULL. Reads and deletes keep working, so recovery is possible if you built retention. Timestamp every row, index it, and delete on an alarm. Keep full logs in R2 or D1, with a bounded window in the object.

Missed alarms. The initial attempt plus six retries is the whole budget. If the handler throws through all of them, nothing runs until something calls setAlarm. The signature is a hold that never expires or a nightly job that stops. Catch downstream failures, reschedule explicitly, and alert when retryCount climbs.

Reconnect storms. After a forced update, a room with 10,000 sockets can produce 10,000 upgrades in seconds. Serve 503 with Retry-After, jitter clients, and track upgrade rate per object.

Two recovery tools help. SQLite-backed objects support point-in-time recovery to a bookmark in the past 30 days, and deleteAll() removes data and, on compatibility dates from 2026-02-24, the alarm.

Design a Small Room or Reservation Coordinator

Start from this configuration. The binding name, the export declaration, and the storage backend must agree, or the object never resolves.

// wrangler.jsonc
{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "room-coordinator",
  "main": "src/index.ts",
  "compatibility_date": "2026-11-05",
  "durable_objects": {
    "bindings": [{ "name": "ROOM", "class_name": "RoomCoordinator" }]
  },
  "exports": {
    "RoomCoordinator": { "type": "durable-object", "storage": "sqlite" }
  }
}
# Terminal 1
npx wrangler dev

# Terminal 2: k1 names the logical action, not the HTTP attempt.
curl -X POST http://localhost:8787/rooms/ATL-204/reserve \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: k1" \
  -d '{"guestId":"g1","checkIn":"2026-12-01","checkOut":"2026-12-03"}'
Guided exercise

Design a Small Room or Reservation Coordinator

Execution status: design-only; not executed for this article. Every expected result below is an acceptance criterion, not a measurement. The two code widgets are the fixture; the planning baseline is 2026-11-02 and the docs were re-checked on 2026-11-05.

Prerequisites. A current Node.js LTS release, npm, and a current Wrangler release. wrangler dev needs no Cloudflare account, and a deployed version fits the Workers Free plan because SQLite-backed objects are available there.

You need two terminals and curl.

Minimal setup. Create a Worker project, paste the coordinator widget into src/index.ts, and apply the configuration above. Legacy projects use a migration with new_sqlite_classes; never use both.

  1. Run npx wrangler dev. Expected: the binding resolves locally without a deployment.
  2. Reserve ATL-204 for 2026-12-01 to 2026-12-03 with Idempotency-Key: k1. Expected: 201 and a holdId.
  3. Repeat the identical request with k1. Expected: 201, the same holdId, and one row in holds.
  4. Send different keys (k2, k3) for overlapping dates from two terminals at once. Expected: exactly one 201 and one 409 with overlap.
  5. Reserve ATL-205 for the same dates with k4. Expected: 201, because a different room is a different object.
  6. Call confirm(holdId) through a temporary route or Vitest. Expected: true once, then false.
  7. Set HOLD_MS to 5000, create a hold, and wait six seconds. Expected: the alarm deletes it and a later confirm returns false.
  8. Add a socket route, send three sequenced messages, drop the connection, and reconnect with since=2. Expected: only message 3 replays.
  9. Optional: with @cloudflare/vitest-plugin, call evictDurableObject(stub). Expected: an in-memory counter resets while the SQLite hold count survives.
Failure checkWhat you seeWhere to look
Check and insert not transactionalTwo 201s for overlapping datestransactionSync scope, or an awaited non-storage call between them
Request row not committed with the holdA different holdId on the same keyThe requests insert inside the same transaction
Alarm never armedA hold that never expiressetAlarm, overwritten alarm, exhausted retries
Cursor not persistedEvery message replaysThe sequence row written before the send

Cost dimensions. Local development is USD 0. The Free plan includes 100,000 requests per day, 13,000 GB-s per day, and 5 GB of storage at the time of writing; the paid plan meters requests, duration at 128 MB, and rows read and written. Socket residency, not storage, is the cost driver here.

Cleanup. Stop wrangler dev, remove .wrangler/state, and delete the test route.

If you deployed, call ctx.storage.deleteAll() in each test object, then delete the namespace through an exports tombstone or the dashboard.

Deleting the script alone can leave billable data, so remove the binding and any test namespace too.

Exercise Concurrent Requests and a Client Reconnect

Planned exercise: execution not yet performed. The planning baseline is 2026-11-02; product pages were re-checked on 2026-11-05. No deployed object, socket, or alarm was exercised, so this section states pass criteria, not measured results.

Pass evidence. A successful run produces all of the following:

  • Two overlapping reservations with different keys yield one 201 and one 409; an in-object count shows one hold.
  • Replaying the same key after a crash returns the original holdId without a new row.
  • A five-second hold is gone after its alarm; confirm then returns false.
  • Reconnecting with since=2 replays only later events; a cursor beyond retention returns a snapshot marker.
  • evictDurableObject clears an in-memory field while the SQLite count survives.
  • An upgrade with a missing, expired, or wrong-room ticket is rejected before acceptance.

Fail evidence. A second hold after a retry; a 500 instead of 409; an alarm that leaves the hold because it deleted by the wrong status; an empty subscriber map after hibernation; overload errors from a reconnect burst; a socket accepted with another room's ticket.

Self-check.

Why is one object per room safer than one object per inn? The invariant "this room is promised once" only needs that room's requests serialized. Per-inn serializes unrelated rooms into a hot object; per-date splits a multi-night stay until no transaction can check the interval.

Hibernation is on, yet the object never sleeps. What do you check first? A setInterval, a pending waitUntil, an outbound fetch or WebSocket, or a socket accepted with the standard API instead of ctx.acceptWebSocket(). Each disqualifies hibernation and keeps duration billing running.

A retry after a timeout creates a second hold. Where is the bug? The idempotency record and the hold are not in one transaction, or the retry uses a new key. The key must be generated per logical action and stored with the response.

Unresolved limitations. No hosted run was performed, so no throughput, latency, alarm timing, or reconnect behavior was measured. No Wrangler, workerd, or Vitest version is pinned because nothing was executed; the code targets the cloudflare:workers API documented in October 2026. The 1,000 requests-per-second figure is a documented soft ceiling, not a benchmark. The limits page and its FAQ differ on the Free plan's per-object storage figure; the account-wide 5 GB cap is the safe constraint. Pricing, allowances, location hints, and the exports shape are dated October–November 2026 observations. The 32,768-socket figure is a platform maximum, not a capacity plan.

References (verified 2026-11-05):

  • Durable Objects overview: https://developers.cloudflare.com/durable-objects/
  • What are Durable Objects: https://developers.cloudflare.com/durable-objects/concepts/what-are-durable-objects/
  • Lifecycle of a Durable Object: https://developers.cloudflare.com/durable-objects/concepts/durable-object-lifecycle/
  • Limits: https://developers.cloudflare.com/durable-objects/platform/limits/
  • Pricing: https://developers.cloudflare.com/durable-objects/platform/pricing/
  • Alarms API: https://developers.cloudflare.com/durable-objects/api/alarms/
  • SQLite-backed storage API: https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/
  • Durable Object State API: https://developers.cloudflare.com/durable-objects/api/state/
  • WebSockets and hibernation: https://developers.cloudflare.com/durable-objects/best-practices/websockets/
  • Rules of Durable Objects: https://developers.cloudflare.com/durable-objects/best-practices/rules-of-durable-objects/
  • Data location: https://developers.cloudflare.com/durable-objects/reference/data-location/
  • Durable Object class exports: https://developers.cloudflare.com/durable-objects/reference/durable-objects-migrations/
  • SQLite-only namespace change (July 2026): https://developers.cloudflare.com/changelog/post/2026-07-09-restrict-new-kv-backed-namespaces/
  • Testing Durable Objects: https://developers.cloudflare.com/durable-objects/examples/testing-with-durable-objects/
  • Vitest test APIs: https://developers.cloudflare.com/workers/testing/vitest-integration/test-apis/
  • Workers limits: https://developers.cloudflare.com/workers/platform/limits/
  • Cloudflare chat demo (one object per room): https://github.com/cloudflare/workers-chat-demo

Next in the Series

In Run Durable Workflows and Scheduled Jobs, we'll explore Make retries, state transitions, and recovery explicit.