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.
%%{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.
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.
| Guard | What it does | Why it matters |
|---|---|---|
| Input gates | Stop new events while synchronous JavaScript runs, and stay closed while a storage operation is in flight | A read-modify-write cannot interleave |
| Output gates | Hold outgoing network messages until pending writes are confirmed durable | A response never precedes its commit |
| Write coalescing | Merge writes with no intervening await into one atomic commit | Several calls become one commit |
blockConcurrencyWhile | Close the gate unconditionally, including across I/O | Setup 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 layer | Survives eviction? | Transaction scope | Billed as | Use it for |
|---|---|---|---|---|
In-memory field (this.cache) | No | None across events | Wall-clock duration while active | Hot caches, socket registries, derived state that can be rebuilt |
ctx.storage KV methods | Yes | Each call atomic; writes without await coalesce | Rows read and rows written | Small documents, flags, per-object indexes |
SQLite table via sql.exec | Yes | Statement or implicit transaction; transactionSync for several | Rows read and written, plus stored GB-months | Reservations, ledgers, message logs, range queries |
Alarm (setAlarm) | Yes, the scheduled time persists | One alarm per object | One row write, plus an invocation request | Hold expiry, retries, periodic sweeps |
| D1, R2, Queues | Yes, outside the object | Separate service; no shared transaction | Product-specific | Cross-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.
%%{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.
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.
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.
Hibernation preserves the connection, not the conversation
In-memory fields, timers, and anything you forgot to write to storage or an attachment are lost when the object sleeps, even though the client's socket never closed.
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.
| Control | Example | Strength | Consequence |
|---|---|---|---|
| First request | get() on a stub | Sticky | The object stays near the first caller's data center |
| Location hint | "weur" | Best effort | The runtime picks a nearby data center, not necessarily the hinted one |
| Jurisdiction | "eu" | Hard constraint | The same name in another jurisdiction produces a different ID |
One routing rule per entity
Two routes to the same name are two objects. Mixing the global namespace with a jurisdiction binding for the same idFromName("room:1") addresses two objects. Pick one rule per entity and keep it everywhere; inside the object, read the jurisdiction from ctx.id if the code must branch.
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.
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.
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.
- Run
npx wrangler dev. Expected: the binding resolves locally without a deployment. - Reserve
ATL-204for2026-12-01to2026-12-03withIdempotency-Key: k1. Expected: 201 and aholdId. - Repeat the identical request with
k1. Expected: 201, the sameholdId, and one row inholds. - Send different keys (
k2,k3) for overlapping dates from two terminals at once. Expected: exactly one 201 and one 409 withoverlap. - Reserve
ATL-205for the same dates withk4. Expected: 201, because a different room is a different object. - Call
confirm(holdId)through a temporary route or Vitest. Expected:trueonce, thenfalse. - Set
HOLD_MSto5000, create a hold, and wait six seconds. Expected: the alarm deletes it and a later confirm returnsfalse. - Add a socket route, send three sequenced messages, drop the connection, and reconnect with
since=2. Expected: only message 3 replays. - Optional: with
@cloudflare/vitest-plugin, callevictDurableObject(stub). Expected: an in-memory counter resets while the SQLite hold count survives.
| Failure check | What you see | Where to look |
|---|---|---|
| Check and insert not transactional | Two 201s for overlapping dates | transactionSync scope, or an awaited non-storage call between them |
| Request row not committed with the hold | A different holdId on the same key | The requests insert inside the same transaction |
| Alarm never armed | A hold that never expires | setAlarm, overwritten alarm, exhausted retries |
| Cursor not persisted | Every message replays | The 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
holdIdwithout a new row. - A five-second hold is gone after its alarm;
confirmthen returnsfalse. - Reconnecting with
since=2replays only later events; a cursor beyond retention returns a snapshot marker. evictDurableObjectclears 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.