A Cloudflare billing Worker keeps an RPC stub received as a parameter and uses it later in ctx.waitUntil(), getting 'RPC stub used after being disposed'; why, and how should stub lifetimes be managed?
answer
- two isolates, two garbage collectors
- disposal is an explicit signal
- parameters die when the call returns
- the caller's context still matters
- skip the first await
basics
~20 sA parameter stub is disposed when the RPC method returns, and it calls back through the caller, so it cannot outlive the caller's request. Read the values later work needs before returning, and use dup() only inside that window.
solid answer
~50 sA stub pins an object in another isolate, and that isolate's garbage collector cannot see the holder's references, so the runtime relies on explicit **disposal**. It disposes automatically when an event's execution context ends, when an RPC call that received stubs as parameters returns, and when a returned object that contains stubs is disposed. The billing Worker's stub was a parameter, so it was dead once `audit()` returned. `invoice.dup()` keeps a second handle past the return, but calls through it still route back through the gateway, so once the gateway has sent its response they fail with `The execution context which hosts this callback is no longer running.` The robust fix is to `await` the values the background job needs inside the method and hand plain data to `ctx.waitUntil()`. On the caller's side, `using` declarations dispose stubs at the end of scope, and skipping the first `await` pipelines chained calls into one round trip.
code
javascript · 37 linesimport { WorkerEntrypoint, RpcTarget } from "cloudflare:workers";
class Invoice extends RpcTarget {
#lines = [];
addLine(cents) {
this.#lines.push(cents);
return this.#lines.length;
}
get total() {
return this.#lines.reduce((sum, cents) => sum + cents, 0);
}
}
export class BillingApi extends WorkerEntrypoint {
openInvoice() {
return new Invoice();
}
async audit(invoice) {
// `invoice` is disposed when audit() returns, and its calls route back through the caller,
// so read what the background work needs while this call is still live.
const total = await invoice.total;
this.ctx.waitUntil(this.#record(total));
return "queued";
}
async #record(total) {
await new Promise((resolve) => setTimeout(resolve, 50)); // later work, after the caller has responded
console.log("audited total", total);
}
}
export default class extends WorkerEntrypoint {
async fetch() {
return new Response("Not found", { status: 404 });
}
}go deeper
Recall that a returned object can be a stub pointing into another Worker, and that a using declaration disposes it at the end of the block.
Explain the three automatic disposal cases and why a parameter stub dies when the method returns; know what dup() and Symbol.dispose do.
Diagnose 'RPC stub used after being disposed' and 'no longer running' errors, read values before returning instead of holding stubs, and use pipelining to cut round trips.
Weigh what held stubs cost a shared internal Worker in memory and context lifetime when deciding whether its API returns handles or plain data.
## Why stubs need disposing When a Worker calls another Worker over a service binding and gets back an `RpcTarget` or a function, it holds a **stub**: a handle to an object that lives in **another** isolate. As long as the stub exists, that object cannot be garbage-collected. Each isolate has **its own garbage collector**, and none can see into another, so the side that owns the object cannot tell on its own that the holder has finished. The holder must send an explicit signal, called **disposing** the stub. Outstanding stubs also hold execution contexts open: when stubs are passed in the parameters or results of a call to a `WorkerEntrypoint`, that callee's context is **implicitly extended** until they are all disposed and every call made through them has returned. A caller that disconnects, including another Worker whose own context has ended, cancels the callee's context regardless. ## When the runtime disposes for you 1. **End of the execution context.** When a `fetch()` handler sends its final response, or the client disconnects, every stub created during that event is disposed. Work passed to `ctx.waitUntil()` extends the context. 2. **Parameters, when the call returns.** A stub that arrives as an argument of an RPC method is disposed as soon as that method returns. This is the billing Worker's bug: its background job ran after `audit()` returned and got `RPC stub used after being disposed.` 3. **Returned objects.** Any object returned by an RPC gets a system disposer that disposes every stub inside it, such as an array of four stubs. Primitive results have no disposer because they cannot contain stubs. ## Why dup() alone does not fix the billing Worker `dup()` creates a second handle to the same target that must be disposed independently, like duplicating a file descriptor. It survives the automatic disposal of the parameter, which is exactly what it is for: keeping a stub while passing the original to a function that disposes it, or keeping a returned stub beyond its `using` scope. But a stub the gateway passed in calls back **through the gateway**, either to an object the gateway owns or through the gateway's proxy to the object's real home. The gateway's `fetch()` context ends when it sends its response. After that, calls through the duplicate fail with `The execution context which hosts this callback is no longer running.` So for work that must run after the caller is gone: - `await` the values the work needs, such as `await invoice.total`, **inside** the method; - pass those plain values to `ctx.waitUntil()`; - reserve `dup()` for keeping a handle within the window in which the caller is still running. ## Disposing explicitly The automatic cases are a safety net; for best performance, dispose stubs as soon as code is done with them. - **`using` declarations** (Explicit Resource Management) call `[Symbol.dispose]()` when the variable leaves scope, even if an exception is thrown. As of Wrangler 4 the syntax works natively. - **`using result = stub.foo()`** is a good default for any object result, so that stubs added to the result later are covered too. - **An `RpcTarget` can implement `[Symbol.dispose]()`**, which runs after its last stub (and every duplicate of that stub) is disposed. The holder does not wait for it, its exceptions are reported as uncaught exceptions rather than propagated, and `Symbol.asyncDispose` is not supported. | Situation | What to do | |---|---| | Result used only inside one block | `using x = await env.SVC.method()` | | Parameter handed to a helper that disposes it | `const keep = param.dup()` first, dispose `keep` later | | Background work after the caller responds | read plain values before returning, pass those to `ctx.waitUntil()` | | Stub wanted by a later request | not possible: a stub never outlives its execution contexts | Saving a stub in a module-scope variable for the next request fails too, with `Cannot perform I/O on behalf of a different request.`, the same rule that governs streams and other I/O objects. ## Promise pipelining An RPC call returns a **custom thenable**, not a real `Promise` (`instanceof Promise` is false), and that thenable also acts as a stub for the eventual result. So: - `using inv = await env.BILLING.openInvoice(); await inv.addLine(1500);` takes **two round trips**. - `using inv = env.BILLING.openInvoice(); await inv.addLine(1500);` takes **one**: the second call is sent speculatively on the promised result, without waiting for the first. - If the first call throws, every pipelined call fails with the **same exception**. Pipelining matters most when the callee is far away, as with a Durable Object; it keeps an API shaped like local code without inventing a combined `openInvoiceAndAddLine()` method.
- Can the gateway cache a stub from the auth Worker in a module-scope variable to save a call on the next request?No. A stub is tied to the execution contexts that created it, and using it from another request's handler fails with `Cannot perform I/O on behalf of a different request.` Cache the plain data a call returned, if that is safe to share between requests, and make a fresh call when you need the remote object again.
- When does an `RpcTarget`'s own `[Symbol.dispose]()` run, and can the holder await it?It runs where the object lives, after the last stub pointing at it, including every `dup()` of that stub, has been disposed. The holder's dispose call does not wait for it, and an exception it throws is reported as an uncaught exception instead of reaching the holder. Only `Symbol.dispose` is supported; `Symbol.asyncDispose` is not.
- What happens to the pipelined `addLine()` call if `openInvoice()` throws?It fails with the same exception. A pipelined call is sent speculatively on the promised result, so when that result turns out to be an error, every call chained on it rejects with that error. Handle the failure once, where the chain is awaited, rather than expecting the second call to run on its own.
- Stubs are garbage-collected across isolates, so explicit disposal is unnecessary.
- A stub received as a parameter stays valid while the callee holds a reference.
- dup() makes a stub safe to use after the calling Worker has sent its response.
- An RpcTarget can implement Symbol.asyncDispose so holders await its cleanup.
- Keeping an RPC stub in a global lets the next request reuse it.
- If the first pipelined call fails, the chained calls still run on their own.
Assumes Wrangler 4, which supports the using declaration natively; with earlier Wrangler versions, stubs had to be disposed by hand, for example by calling Symbol.dispose in a finally block.