Port Authority

Port patterns / Hot-swapping, wiretapping and liveness

Zero-downtime live worker hot-swap (live port migration)

Like Erlang/OTP hot upgrades or Nginx worker handoffs, you can replace a running Dedicated Worker without disconnecting whoever talks to it. Upstream Feed sends numbered events down a single MessagePort into Worker v1, which tracks running state (count and sum). When Worker v2 deploys, v1 transfers its live feed port plus state snapshot straight to v2 and terminates. Because a newly transferred MessagePort buffers incoming messages until the receiver starts listening, event #4 arriving mid-swap waits safely in the queue. Worker v2 attaches onmessage, immediately drains the buffered #4, and handles #5 and #6 with zero drops. Upstream Feed never notices the swap.

When you'd use this

A collaborative editor runs a CRDT sync worker that holds live MessagePorts from open UI panels and a WebRTC peer bridge. When a new version of the worker script ships — or when the worker's WASM heap needs a clean restart — you don't want to tear down every channel and force panels to re-sync. Boot Worker v2 in the background, ask v1 to transfer its live ports plus a compact state snapshot straight into v2, and terminate v1. Any edits posted during the swap sit safely in the transferred port's queue and arrive in order as soon as v2 starts listening.

Code

// Inside Worker v1: transfer the live port + state atomically to Worker v2
// Any messages arriving during handover wait in the transferred port's queue
migrationPort.postMessage({ state: { count, sum, lastSeq } }, [feedPort]);

// Inside Worker v2: restore state and start draining buffered messages
migrationPort.onmessage = ({ data, ports: [liveFeed] }) => {
  ({ count, sum, lastSeq } = data.state);
  liveFeed.onmessage = (e) => handleEvent(e.data); // delivers buffered #4 first
};

In practice

// Upgrading a live CRDT or indexing worker after a background bundle update
async function hotSwap(oldWorker, nextScriptUrl) {
  const nextWorker = new Worker(nextScriptUrl, { type: "module" });
  await once(nextWorker, "ready");

  const mig = new MessageChannel();
  nextWorker.postMessage({ cmd: "accept-migration" }, [mig.port2]);
  oldWorker.postMessage({ cmd: "handoff" }, [mig.port1]);

  await once(nextWorker, "migrated");          // live ports + state now belong to nextWorker
  oldWorker.terminate();                       // upstream feeds never saw a disconnect
  return nextWorker;
}

How it works

A MessagePort isn't bound to the worker that originally received it. It's a movable capability whose queue lives inside the browser's messaging layer. As long as one end stays open in the upstream producer, the other end can move from Worker v1 to Worker v2 without closing the channel.

The handover works atomically in two turns. First, Worker v1 keeps processing messages right up until the synchronous turn where it packages its in-memory state snapshot (here { count, sum, lastSeq }) and posts it to Worker v2 with [feedPort] in the transfer list. The instant postMessage transfers feedPort, v1's handle is neutered and the newly transferred port on v2's side starts in a disabled (buffering) state, so anything Upstream Feed sends mid-swap queues safely inside the browser. Second, Worker v2 restores the state and assigns feedPort.onmessage, which enables the queue and immediately drains every buffered event before continuing with live traffic.

Once the transfer completes, you can call v1.terminate() straight away. Upstream Feed never sees an error, never reconnects, and doesn't need any protocol versioning or reconnect logic.

Step by step

What each press of Next does in the demo above.

  1. Connect Upstream Feed to Worker v1. A feed port is transferred to Worker v1 and events #1, #2 and #3 flow straight across (sum = 6).
  2. Deploy Worker v2. Worker v2 boots and v1 transfers its live port + state straight across. Event #4 fires mid-swap into the paused port queue, v1 terminates, and v2 drains the buffered #4 immediately.
  3. Send events #5 & #6. Upstream Feed posts #5 and #6 into the exact same MessagePort it has held from the start. Worker v2 processes both (sum = 21, 0 dropped).

What you can build with it

Other ideas

  • Hot-swapping a compute, parser or CRDT worker (Yjs, Automerge) after downloading a newer script bundle without dropping active tab or WebRTC ports.
  • Recycling a long-lived worker whose WASM linear memory has fragmented or grown large, migrating its active client ports and compact state to a fresh worker.
  • Splitting or rebalancing load across a worker pool by handing busy client ports from an overloaded worker to a quiet one.

Things to try

  • Watch Step 2 closely: Upstream Feed emits #4 right after v1 transfers the port and before Worker v2 starts listening, yet Worker v2 still prints [v2] #4 (buffered!) with zero gaps.
  • Notice Upstream Feed's log in Step 3: it posts #5 and #6 into the exact same port it was handed in Step 1, with no knowledge that Worker v1 was terminated.

Gotchas

  • Don't set port.onmessage = null and then wait asynchronously before transferring the port. Once a MessagePort has been started (which assigning onmessage does implicitly), clearing onmessage doesn't re-pause its queue — messages delivered in the gap dispatch to zero listeners and vanish. Keep handling messages right up until the synchronous postMessage(..., [port]) call that transfers it, because the browser automatically starts the transferred port paused on the receiving end.
  • Only serialisable state (or transferable objects like ArrayBuffers and other ports) can cross in the handover message. Non-transferable handles such as open WebSockets, live WebGPU devices or closures have to be rebuilt in Worker v2.
  • If Worker v1 is in the middle of an async operation (say an IndexedDB transaction or an awaited fetch) when you ask it to hand off, wait for in-flight work to finish before transferring the port so you don't duplicate side effects or lose uncommitted state.
  • Never call port.close() on a port you're about to transfer: close() permanently disentangles the channel, whereas transferring moves the live end intact.
  • If the producer fires messages at high frequency while Worker v2 is slow to boot (for example compiling a large WASM module), boot and warm up Worker v2 first, and only trigger the handoff once v2 reports ready.

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
WebRTC
The browser's APIs for direct connections between two browsers, carrying audio, video or data. MDNWebRTC
Transferable objects
Objects that can be moved to another page or worker instead of copied. After the move the sender can no longer use them. The transfer list is the argument to postMessage that names them. MDNHTML Standard
MessagePort.postMessage()
Sends a message through a port. A second argument lists the objects to move instead of copy. MDNHTML Standard
ArrayBuffer
A block of raw bytes. It can be moved to another thread without copying. MDNECMAScript
WebSocket
A two-way connection between a page and a server that stays open. MDNWebSockets Standard
IndexedDB
A database in the browser that belongs to one origin. It can store most things that can be posted, including a CryptoKey. MDNIndexed Database API

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