skip to content

Durable Objects

A Durable Object is one addressable instance with its own storage, so a single place serializes a room, counter or session. Interviewers ask when it is the right unit of coordination.

on this pageshow

explore

questions

17

How does a Cloudflare Worker call a method on a Durable Object, and what are the namespace binding, the stub and an RPC method?

level: juniorimportance: must knowfreq 62%

answer

  1. binding in the Wrangler file
  2. env.DOCUMENT is a namespace
  3. stub returned without waiting
  4. public methods become RPC
  5. await, and recreate after errors

basics

~20 s

A durable_objects binding puts a namespace on env; getByName() or get(id) returns a stub immediately, and awaiting stub.someMethod() sends an RPC to the one object, which runs that public method of its class extending DurableObject.

solid answer

~40 s

The Wrangler file declares `durable_objects.bindings` with a `name` (say `DOCUMENT`) and the exported `class_name`. At runtime `env.DOCUMENT` is a `DurableObjectNamespace`. `env.DOCUMENT.getByName(docId)`, or `get(id)` with an ID, returns a **stub** at once, before any connection exists. When the class extends `DurableObject` from `cloudflare:workers` and the Worker's compatibility date is `2024-04-03` or later, every public method on the class is callable through the stub: `await stub.applyEdit(userId, text)` sends an RPC, the object runs the method, and the return value comes back structured-cloned. Private `#` members and arrow-function properties are not exposed. Calls on one stub arrive in the order made. Errors thrown in the object reach the caller with `.remote` set, and because many exceptions break a stub, create a new one before retrying.

code

json · 8 lines
json
{
  "name": "doc-editor",
  "main": "src/index.js",
  "compatibility_date": "2026-10-01",
  "durable_objects": {
    "bindings": [{ "name": "DOCUMENT", "class_name": "DocumentRoom" }]
  }
}

go deeper

for a junior

Recall the chain: a durable_objects binding gives env.DOCUMENT, getByName() gives a stub, and await stub.method() runs that method on the object.

for a middle

Explain which members are exposed over RPC, what must be serialisable, and why stub.fetch() needs an absolute URL when you use it.

for a senior

Show the failure habits: await every call, read .remote, .retryable and .overloaded, and build a fresh stub per retry because stubs can break.

for a principal

Argue for a narrow, versioned RPC surface on each class, since every public method is an entry point other code will come to depend on.

## Three pieces between a Worker and an object Calling a **Durable Object** involves three things, and interviewers like to hear them named precisely. 1. **The namespace binding.** In the Wrangler file, `durable_objects.bindings` lists objects of `{ "name": "DOCUMENT", "class_name": "DocumentRoom" }`. `name` is the property that appears on `env`; `class_name` is the class exported from the Worker's module. An optional `script_name` binds to a class exported by a *different* Worker. The class also has to be declared to the platform (through the Wrangler file's migrations or its newer `exports` field), which belongs with object storage. 2. **The namespace.** At runtime `env.DOCUMENT` is a `DurableObjectNamespace`: one per class, holding any number of objects. It makes IDs (`idFromName()`, `newUniqueId()`, `idFromString()`) and stubs (`get(id)`, `getByName(name)`). 3. **The stub.** A `DurableObjectStub` is a client-side proxy for exactly one object. `get()` and `getByName()` return it immediately, often before any connection exists, so the first call can be sent without an extra round trip. Creating a stub does not wake or create the object; the first call through it does. ## Calling methods over RPC With a class that `extends DurableObject` (imported from `cloudflare:workers`) and a compatibility date of `2024-04-03` or later (or the `rpc` compatibility flag), **public methods become RPC methods**: ```javascript const stub = env.DOCUMENT.getByName(docId); const result = await stub.applyEdit(userId, text); ``` What happens: - The call is **always asynchronous**, even if the method is synchronous in the class; the stub returns a promise-like value. - Arguments and return values must be **serialisable**: nearly anything structured-clonable (objects, arrays, strings, numbers), plus streams, `Request` and `Response`. Instances of your own classes cannot cross unless they extend `RpcTarget`. - Only methods declared on the class are reachable. **Private `#` members** and **arrow functions assigned as instance properties** are not exposed, which keeps internal helpers internal. - Inside the object, the base class gives you `this.ctx` (the `DurableObjectState`, with `ctx.id` and `ctx.storage`) and `this.env`. ### The older `fetch()` path Before RPC, a Worker sent an HTTP `Request` to `stub.fetch()` and the class's `fetch()` handler parsed the URL to decide what to do. That still works and is the right tool when you genuinely need a `Request`/`Response` (proxying a request, for instance), but the URL must be absolute; it does not need to resolve anywhere. For application calls, RPC removes the hand-written routing and gives typed method calls when the binding is typed as `DurableObjectNamespace<DocumentRoom>`. ## Ordering, awaiting and errors | Behaviour | What to know | |---|---| | Order on one stub | Calls made on the same stub are delivered in the order you made them (E-order) | | Order across stubs | No ordering guarantee between two different stubs, even to the same object | | Unawaited call | Its result and any error are lost; always `await` stub calls | | Error thrown in the class | Propagates to the caller; `.remote` is `true` | | Infrastructure error | May carry `.retryable` (safe to retry if idempotent) or `.overloaded` (do not retry) | | Stub after an exception | Many exceptions leave it broken, failing every later call; create a new stub | Two habits follow: - **Await every call.** A fire-and-forget `stub.applyEdit(...)` without `await` swallows failures, and the Worker may finish before the call completes. - **Recreate the stub on failure.** Stubs are cheap. Retry logic should build a fresh stub per attempt rather than reusing one that may be stuck on the original exception. ## Putting it together for a document editor In a collaborative editor, the Worker authenticates the user, takes the document ID from the URL, calls `env.DOCUMENT.getByName(docId)` and awaits `stub.applyEdit(...)`. The object for that document applies the edit against its own storage and returns the new revision. The Worker stays stateless; the object is the one place where that document's edits meet. Calling a *separate Worker* over RPC through a service binding uses the same RPC machinery and is covered with service bindings.

  • When would you still call stub.fetch() on a Durable Object instead of an RPC method?
    When the interaction really is HTTP: passing a client's Request through unchanged, returning a streamed Response, or on a Worker pinned to a compatibility date before 2024-04-03 without the rpc flag. The URL must be absolute but need not resolve. For ordinary application calls, RPC methods are simpler and typed.
  • Two different stubs to the same Durable Object each send a call. Which arrives first?
    There is no guarantee. Delivery order is promised only for calls made on the same stub. If two operations must apply in order, send both through one stub, or make the object tolerate either order.

  • getByName() waits until the Durable Object has been constructed
  • Every method on the class, including #private ones, is callable over RPC
  • A stub call can be left unawaited because the object will finish anyway
  • A stub that threw once can always be reused for the next call
  • Durable Objects can only be called through their fetch() handler
open as a page

In a Cloudflare Durable Object, how do you persist state through ctx.storage, and why is a class field not enough?

level: juniorimportance: must knowfreq 60%

basics

~20 s

A Durable Object persists state by writing to its private ctx.storage, with put() and get() for key-value pairs or ctx.storage.sql.exec() for tables. Class fields live only in memory and are lost when the object is evicted, reset or redeployed.

open as a page

In Cloudflare Durable Objects, what is the difference between idFromName() and newUniqueId(), and when would you choose each?

level: middleimportance: must knowfreq 70%

basics

~10 s

idFromName() hashes a string into the same Durable Object ID everywhere, so one name always reaches one object worldwide; newUniqueId() mints a random ID you must store (as toString()) and rebuild later with idFromString().

open as a page

In a Cloudflare Durable Object, what does ctx.blockConcurrencyWhile() guard, and why call it in the constructor rather than around every request?

level: middleimportance: must knowfreq 50%

basics

~20 s

ctx.blockConcurrencyWhile(callback) stops every other event reaching the object until the async callback settles, even across awaits. That suits one-time setup in the constructor, such as creating tables; wrapping each request serialises all traffic and caps throughput.

open as a page

For a Durable Object chat room holding 5,000 mostly idle clients, what changes in memory and billing between ws.accept() and ctx.acceptWebSocket()?

level: middleimportance: must knowfreq 32%

basics

~20 s

With ws.accept() the object must stay in memory, billed for duration, as long as any socket is open. With ctx.acceptWebSocket() the runtime holds the sockets, so an idle object hibernates and accrues no duration charges until a message wakes it.

open as a page

A Durable Object releases 15-minute ticket holds from its alarm() handler, yet some holds were released twice and others never; how do setAlarm() and alarm retries explain it?

level: seniorimportance: must knowfreq 45%

basics

~20 s

Each Durable Object has a single alarm, so a setAlarm() per hold overwrites earlier wake-ups. alarm() runs at least once and retries a throw only 6 times with backoff, so the handler must be idempotent and reschedule itself.

open as a page

With Cloudflare Durable Objects, how does a chat-room object accept a client WebSocket through the Hibernation API and receive its messages?

level: juniorimportance: should knowfreq 30%

basics

~20 s

The Worker forwards the upgrade request to the object's stub; the object creates a WebSocketPair, passes the server end to this.ctx.acceptWebSocket(), and returns a 101 response carrying the client end. Messages then arrive at its webSocketMessage() method.

open as a page

In Cloudflare Durable Objects, how do a locationHint and a jurisdiction differ in controlling where an object runs and stores its data?

level: middleimportance: should knowfreq 32%

basics

~20 s

A locationHint passed to get() or getByName() is a best-effort latency hint honoured only when the object is first created; a jurisdiction such as jurisdiction("eu") is a guarantee that the object runs and stores data only in that region.

open as a page

With a SQLite-backed Durable Object, how do you run a parameterised query through ctx.storage.sql.exec(), and what does its cursor give you?

level: middleimportance: should knowfreq 50%

basics

~10 s

ctx.storage.sql.exec(query, ...bindings) runs SQL synchronously, fills each ? placeholder from the extra arguments, and returns a SqlStorageCursor you iterate or read with toArray(), one() or raw(), plus rowsRead and rowsWritten counts.

open as a page

In Wrangler 4, how do you declare a new SQLite-backed Durable Object class, and why can't an existing class change its storage backend?

level: middleimportance: should knowfreq 35%

basics

~20 s

Bind the class under durable_objects.bindings and declare it in the exports map with "type": "durable-object" and "storage": "sqlite"; older Workers use a migrations entry with new_sqlite_classes. The backend is fixed when the namespace is first created.

open as a page

In a Durable Object using WebSocket Hibernation, how do you broadcast to every client, or to one channel, without your own socket list?

level: middleimportance: should knowfreq 20%

basics

~10 s

Call this.ctx.getWebSockets() for every socket the object accepted, or getWebSockets(tag) for one group, where tags were passed to ctx.acceptWebSocket(ws, tags). The runtime keeps that set through hibernation, so no in-memory list is needed.

open as a page

A Cloudflare Durable Object reached via idFromName("global") counts every document's views and now throws 'Durable Object is overloaded'; why, and how do you fix it?

level: seniorimportance: should knowfreq 52%

basics

~20 s

One name maps to one single-threaded object, with a soft limit of about 1,000 requests per second; past that its queue fills and calls fail as overloaded. Shard the counter over many named objects, or per document, and sum on read.

open as a page

A Cloudflare Durable Object handles one event at a time, yet two document edits that each await a call to another service overwrite each other; why?

level: seniorimportance: should knowfreq 48%

basics

~20 s

A Durable Object runs one piece of JavaScript at a time, but awaiting non-storage I/O such as fetch() or another object's stub lets other requests run; input gates only hold events back during the object's own storage calls.

open as a page

A ticket-reservation Durable Object oversold seats after an await was added between its availability check and its insert; why, and how do implicit transactions and transactionSync() fix it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

The await let other bookings run their own availability checks before any insert landed, so all saw free seats. Keep check and insert synchronous, ideally in ctx.storage.transactionSync(); the output gate holds the reply until the write is durable.

open as a page

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?

level: seniorimportance: should knowfreq 26%

basics

~20 s

Hibernation 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().

open as a page

A Durable Object chat room accepts every socket with ctx.acceptWebSocket(), yet its duration charges show it awake around the clock; what keeps it from hibernating?

level: seniorimportance: should knowfreq 18%

basics

~20 s

Something else pins it in memory: a pending setTimeout() or setInterval(), unfinished I/O or ctx.waitUntil() promises, an open outbound connection such as an upstream WebSocket, any socket accepted with ws.accept(), or an event that never finishes.

open as a page

With Durable Object WebSocket Hibernation, how do you answer clients' application-level "ping" heartbeats without waking the object?

level: middleimportance: nice to knowfreq 14%

basics

~10 s

Call this.ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair("ping", "pong")). The runtime then answers any text message exactly equal to "ping" with "pong" on every hibernation-accepted socket, without waking the object or adding duration charges.

open as a page