skip to content

In Cloudflare Workers RPC over a service binding, what can a method accept and return, and what happens to functions, class instances, streams and errors?

level: middleimportance: should knowfreq 25%

answer

  1. structured clone, with exceptions
  2. functions become stubs
  3. extend RpcTarget or fail
  4. byte streams, ownership moves
  5. errors keep name and fields

basics

~20 s

Structured-clonable values are copied. Functions and RpcTarget instances become stubs that call back to their origin, other classes fail to serialize, byte streams, Request and Response stream with flow control, and errors arrive by name and fields, not class.

solid answer

~50 s

Workers RPC copies nearly everything the structured clone algorithm supports: objects, arrays, strings, numbers and similar values, up to a 32 MiB serialized message. It also passes things structured clone cannot. A **function** is replaced by a stub, and calling it makes an RPC back to where it was defined. An instance of a class that extends `RpcTarget` is also replaced by a stub, so its methods run where the object lives. An instance of any other application class is rejected with a `DataCloneError`. Byte-oriented `ReadableStream` and `WritableStream`, `Request` and `Response` are streamed with flow control and their ownership moves to the recipient, which is how payloads larger than 32 MiB travel. A thrown error reaches the caller as a new error object: for compatibility dates from 2026-04-21, `name`, `message` and serializable own properties such as `code` survive, but `instanceof` against the custom class does not.

code

javascript · 42 lines
javascript
import { 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);
  }
}

class Receipt {
  constructor(total) {
    this.total = total;
  }
}

export class BillingApi extends WorkerEntrypoint {
  openInvoice() {
    return new Invoice(); // the caller receives a stub, not a copy
  }
  receipt() {
    return new Receipt(100); // not an RpcTarget: fails to serialize
  }
  quote(plan, onQuote) {
    return onQuote(plan === "pro" ? 2000 : 500); // onQuote is a stub that calls back into the caller
  }
  charge() {
    const err = new Error("card declined");
    err.name = "PaymentError";
    err.code = "DECLINED";
    throw err;
  }
}

export default class extends WorkerEntrypoint {
  async fetch() {
    return new Response("Not found", { status: 404 });
  }
}

go deeper

for a junior

Recall that ordinary values such as objects, arrays, strings and numbers are copied across an RPC call, and that a method's result must be awaited.

for a middle

Explain the additions: functions and RpcTarget instances become stubs, other classes throw DataCloneError, and streams, Request and Response stream with ownership transfer.

for a senior

Show the production edges: the 32 MiB message limit and streaming around it, errors keyed on name and code rather than instanceof, and the 2026-04-21 compatibility date for enhanced error serialization.

for a principal

Set a team rule for internal RPC contracts: plain data for results, RpcTarget for handles, streams for bulk, and stable error codes treated as part of the API.

## Values copied by value Workers RPC is designed to feel like calling a local JavaScript function, so arguments and return values are mostly ordinary values. **Nearly every type the structured clone algorithm supports** can cross a service binding: plain objects, arrays, strings, numbers, booleans and similar built-in types. They are **copied**; the callee gets its own object and changes to it do not reach the caller. One serialized RPC message may be at most **32 MiB**. A plain object containing functions is also allowed. Its non-function properties are copied at the moment the object is sent, and each function inside it becomes its own stub. ## What Workers RPC adds beyond structured clone | Value | What the other side receives | |---|---| | Function | a **stub**; calling it makes an RPC back to the Worker that sent the function | | Instance of a class extending `RpcTarget` | a **stub**; method calls and awaited getters run on the original object | | Instance of any other application class | nothing: the send fails with `DataCloneError` | | Byte-oriented `ReadableStream` or `WritableStream` | the stream, with bytes streamed under flow control | | `Request` or `Response` | the message, with its body streamed | | An RPC stub, even one from a third Worker | a stub that proxies through the Worker that passed it | Some consequences: - **Callbacks work both ways.** A callee can receive a function and call it, which calls back into the caller. That is why "caller" and "callee" describe a single call better than "client" and "server". - **Plain classes are refused on purpose.** Structured clone would silently drop the prototype and deliver a bare object; Workers RPC instead throws `Could not serialize object of type "Receipt". This type does not support serialization.` so nobody mistakes a copy for the real thing. Extend `RpcTarget` to pass an object by reference, or return a plain object to pass data. - **One stub beats many.** Returning an `RpcTarget` with five methods sends one stub; returning an object with five function properties sends five. - **Streams move, they are not shared.** After sending a stream the sender can no longer read or write it. Keeping a copy needs `tee()` or `clone()`, which may force buffering and lose flow control. Only streams with a `type: "bytes"` source are supported. ## Large payloads The 32 MiB limit applies to the serialized message, not to stream bodies. A method that must hand back a large export returns a `ReadableStream` or a `Response` and lets the runtime stream it. Building a huge `Uint8Array` in memory and wrapping it in a stream technically passes, but puts pressure on the isolate's memory; streaming from the original source is the better design. ## Errors across the boundary An exception thrown by an RPC method, or a rejected promise, reaches the caller as a **new error object**: 1. With **enhanced error serialization**, the `enhanced_error_serialization` compatibility flag, the error keeps its effective `name`, `message` and **serializable own properties**, including non-enumerable ones such as `cause`. The flag is on by default for compatibility dates on or after **2026-04-21**. 2. For earlier dates, both the provider and the consumer must add the flag; `legacy_error_serialization` opts out and drops custom properties. 3. In either mode the caller does **not** get the provider's class, prototype methods, `instanceof` results or original stack. So a `PaymentError` with `code: "DECLINED"` arrives with `err.name === "PaymentError"` and `err.code === "DECLINED"`, yet `err instanceof PaymentError` is false on the caller. The contract between Workers is the error's **serializable fields**: check `name` and a documented `code`, and keep those properties small and serializable, because a non-serializable property can stop the enhanced details from arriving. ## A checklist for designing an RPC method - Return **plain data** for results the caller only reads. - Return an **`RpcTarget`** when the caller should keep acting on a server-side object. - Accept a **function** when the callee must report back progress or results. - Use a **stream** for anything that could approach 32 MiB. - Throw errors with a stable **`name` and `code`**, never relying on the class surviving.

  • How should a billing Worker return a 200 MiB statement export over RPC?
    Return a `ReadableStream` with a byte source, or a `Response` wrapping one, instead of a buffer or array. Stream bodies are not bound by the 32 MiB serialized-message limit; bytes flow with backpressure and ownership passes to the caller. Stream from the original source, such as an R2 object body, rather than building the whole file in the isolate's memory first.
  • A caller catches an RPC error and checks `err instanceof PaymentError`. Why does it never match?
    The error crosses the boundary as a new object rebuilt by the runtime, and the provider's class, prototype and constructor are not preserved. With enhanced error serialization, on by default from compatibility date 2026-04-21, `name`, `message` and serializable own fields such as `code` do arrive. Branch on `err.name` or `err.code` and treat those fields as the contract.
  • Why is returning an `RpcTarget` usually better than returning an object full of functions?
    An object with five function properties creates five stubs and copies its other properties once, at send time. An `RpcTarget` instance with five methods is one stub, its getters are fetched on demand when awaited, and its `#private` state stays on the server. It is cheaper and keeps the interface explicit.

Working with a colleague in another office: you can send a photocopy of a form (a copied value) or a direct line that rings your own desk (a stub), but the post office refuses to ship your actual desk and pretend it is still yours (a plain class instance).

  • Any class instance crosses RPC like structuredClone does, just losing its prototype.
  • A returned RpcTarget is copied to the caller, so its methods run in the caller's isolate.
  • Custom error classes survive RPC, so instanceof checks on the caller still work.
  • RPC messages have no size limit because the call never leaves Cloudflare.
  • Passing a function over RPC ships its source code to run in the other Worker.
  • After sending a ReadableStream over RPC the sender can keep reading it too.

Assumes a compatibility date on or after 2026-04-21, when enhanced_error_serialization became the default and RPC errors began carrying their own serializable properties; earlier dates must add the flag on both Workers.