Port Authority

Port patterns / The four primitives

Send a reply port with each request

Instead of matching replies to requests with correlation IDs, mint a fresh channel for each request and transfer one end along with it. The reply comes back on a port that only this request ever held, so overlapping answers can't get mixed up even when they return out of order.

When you'd use this

A writing app runs spell-check in a Web Worker while the user edits, firing off multiple paragraphs concurrently. Because each request carries a dedicated reply port, results for a long chapter can't collide with a short intro no matter what order they finish in — and the worker stays completely stateless.

Code

function ask(service, question) {
  const { port1, port2 } = new MessageChannel();
  service.postMessage(question, [port2]);
  return new Promise((resolve) => (port1.onmessage = (e) => { resolve(e.data); port1.close(); }));
}

In practice

// a writing app spell-checking paragraphs concurrently in a worker
const service = new Worker("/spelling.js");

// two paragraphs go out at once
const [intro, chapter] = await Promise.all([
  ask(service, { text: introText }),
  ask(service, { text: chapterText }),
]);
underline(introBox, intro);
underline(chapterBox, chapter);

// in spelling.js: reply on the port attached to this request
onmessage = async (e) => {
  const reply = e.ports[0];
  reply.postMessage(await mistakesIn(e.data.text));
  reply.close();
};

// Even if the short paragraph finishes first, every reply lands on the right
// promise. Add a timeout in production so an unanswered port doesn't leak.

How it works

Every request carries a brand-new MessagePort minted just for that call. The service answers on that port and closes it. Replies can't collide even when requests finish out of order because no other call ever held that port.

That eliminates the request-ID map most postMessage wrappers maintain, and a reply port can't be guessed or forged.

It also decouples who asked from who receives the answer: a client can hand its reply port to another worker or frame, and the response lands directly there.

Step by step

What each press of Next does in the demo above.

  1. Connect Client one. Transfers a request port between Client one and the Service.
  2. Connect Client two. Transfers a separate request port between Client two and the Service.
  3. Client one asks. Client one sends a question along with a fresh reply port. The answer returns on that reply port, then closes.
  4. Client two asks. Client two sends a question with its own reply port. Overlapping replies stay on separate ports so they never collide.

What you can build with it

Built and running below.

A long job that reports progress, and can be cancelled

Streaming progress updates on the reply port until the final answer arrives, or cancelling work in flight. Delegating the reply to a third context by transferring the reply end.

The reply port does not have to carry one answer. This page asks a slow service for a job and keeps the reply port open. Progress arrives on it, ten per cent at a time. To cancel, this page says so on the same port and closes it. The service stops work, because nobody is waiting for the result any more.

Code

const { port1, port2 } = new MessageChannel();
service.postMessage({ job: "render" }, [port2]);
port1.onmessage = ({ data }) => data.done ? finish(data) : showProgress(data.percent);

// changed your mind
port1.postMessage({ cancel: true });
port1.close();

Step by step

What each press of Next does in this demo.

  1. Start a long job. The question goes out with a fresh reply port. Progress comes back on that port.
  2. Start a long job. The first job finished. Start a second one.
  3. Cancel it. This page tells the service to stop, on the reply port, and closes it. The service stops part-way.

Call a function on another origin and await the answer

Request/response RPC over ports — this is what Comlink and Hawser do underneath.

Twelve lines turn the reply pattern into await call("add", 2, 3). Each call makes a channel, sends one end with the question, and returns a promise that settles when the other end speaks. Errors come back as rejections. Three calls made at once come back to the right callers, even when the slow one finishes last, because each has its own channel.

Code

const call = (method, ...args) => new Promise((resolve, reject) => {
  const { port1, port2 } = new MessageChannel();
  port1.onmessage = ({ data }) => { "error" in data ? reject(new Error(data.error)) : resolve(data.result); port1.close(); };
  service.postMessage({ method, args }, [port2]);
});

await call("add", 2, 3);       // 5, computed on another origin

Step by step

What each press of Next does in this demo.

  1. await call("add", 2, 3). A question goes out with a reply port. The promise resolves with the answer.
  2. await call("divide", 1, 0). The service refuses. The promise rejects with its message.
  3. Three calls at once. Three questions, three wires. The slow one comes back last and still reaches the right caller.

Things to try

  • Make both clients ask at once and watch each yellow reply port ride into the service before spawning its own temporary reply cable.
  • Fire several questions rapidly from Client one to watch overlapping reply cables resolve independently.

Gotchas

  • An unanswered reply port leaks until the page closes — always attach a timeout.
  • Minting a channel per call is cheap, but for tens of thousands of tiny messages a second, batch them or reuse a multiplexed channel.

References

The web platform features this page mentions, with what each one is, its documentation on MDN and the specification that defines it.

Web Workers
Scripts that run on their own thread, away from the page. MDNHTML Standard
MessagePort
One end of a message channel. Whatever is posted into it comes out of the other end, and it can be sent to another page, frame or worker. MDNHTML Standard
MessagePort.postMessage()
Sends a message through a port. A second argument lists the objects to move instead of copy. MDNHTML Standard

Projects and documents this page draws on.

  • Comlink, by Surma and the Chrome Labs team.

For more, see Further reading: articles, talks, papers, libraries and the specifications, collected in one place.