skip to content

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