Port Authority

Port patterns / Hot-swapping, wiretapping and liveness

Transparent IPC wiretap & flight recorder

Whoever creates or introduces a MessageChannel controls the topology. Instead of wiring Client straight to a Worker, splice a proxy in the middle (Client ↔ Tap ↔ Worker) without changing a single line in either endpoint. Every message crosses with timestamps onto a flight recorder tape; flip on chaos mode to drop a message and verify the client's timeout path, then replay the exact recorded tape into a brand-new Worker to reproduce state deterministically — like strace or mitmproxy for browser IPC.

When you'd use this

You're debugging a subtle race between a checkout UI and a pricing worker, or writing end-to-end tests to prove your client survives dropped IPC calls. Because the host page hands out the initial MessageChannel, you can flip a flag to splice a wiretap between them without modifying either side. The tap logs every request and reply with timestamps, lets your test harness drop or delay a specific message to verify timeout recovery, and exports a clean tape you can replay into a fresh worker to reproduce the exact state in isolation.

Code

function wiretap(toClient, toService) {
  const tape = [];
  let dropNext = false;
  toClient.onmessage = ({ data }) => {
    const entry = { at: performance.now(), req: data, dropped: dropNext };
    tape.push(entry);
    if (dropNext) { dropNext = false; return; }    // chaos: swallow this message
    toService.postMessage(data);
  };
  toService.onmessage = ({ data }) => toClient.postMessage(data);
  return { tape, dropNextMessage: () => (dropNext = true) };
}

In practice

// Drop-in wrapper around any MessageChannel introduction in dev or CI
function connectWithWiretap(clientFrame, worker, { enableTap = false } = {}) {
  if (!enableTap) {
    const ch = new MessageChannel();
    clientFrame.postMessage({ cmd: "port" }, origin, [ch.port1]);
    worker.postMessage({ cmd: "port" }, [ch.port2]);
    return null;
  }
  const toClient = new MessageChannel(), toWorker = new MessageChannel();
  const tap = wiretap(toClient.port1, toWorker.port1);
  clientFrame.postMessage({ cmd: "port" }, origin, [toClient.port2]);
  worker.postMessage({ cmd: "port" }, [toWorker.port2]);
  return tap;                                  // inspect tap.tape or call tap.dropNextMessage()
}

How it works

Because a MessagePort is an unforgeable capability handed out at setup time, whoever wires two endpoints together controls the entire communication path. Normally you create one MessageChannel and hand port1 to the client and port2 to the service. To insert a wiretap, you create two channels instead, hand one end of each to Client and Worker, and forward messages between the two inner ends.

Neither endpoint changes a line of code. Client still posts requests into one plain port and runs its normal timeout logic; Worker still reads from one plain port and replies. Everything crossing the boundary passes through the Tap, which stamps each message with performance.now() and appends it to an in-memory flight recorder tape.

Once the Tap sits on the wire, you get two powerful debugging tools for free. First, fault injection: drop a single request, add 400 ms of latency or reorder replies to test whether your client's timeouts and retries actually hold up. Second, deterministic replay: spin up a brand-new Worker and feed it the recorded sequence of non-dropped requests from the tape to reproduce a bug without re-running the UI.

Step by step

What each press of Next does in the demo above.

  1. Splice Wiretap. Two MessageChannels are wired through the Tap. Client and Worker each receive one plain port and never know a proxy sits between them.
  2. Send normal traffic. Client sends add(10) and mul(3). Both round-trip cleanly to Worker v1 (total = 30) while the Tap records each request and reply with timestamps.
  3. Enable Chaos. Tap arms dropNext = true and swallows add(5) in red. Worker v1 never sees it, and Client's 400ms timeout triggers cleanly.
  4. Replay recorded tape. A brand-new Worker boots and receives only the recorded non-dropped messages (#1 add(10), #2 mul(3)), reproducing total = 30 deterministically.

What you can build with it

Other ideas

  • DevTools-style IPC inspectors that record every message between a page, its workers and embedded iframes with latency histograms and payload diffs.
  • Automated chaos testing in CI: wrap worker or iframe channels in a fault-injecting proxy that drops messages, injects jitter or closes ports mid-flight to verify timeout handling.
  • Bug reproduction bundles: attach the last 200 recorded IPC messages to a crash report and replay them against a fresh worker locally.

Things to try

  • Compare the logs in Client and Worker v1 after Step 1: both only ever see a single plain port, with zero wiretap code in either context.
  • In Step 3, watch the red DROPPED pill stop at the Tap: Worker v1's total stays at 30 while Client's 400 ms timeout triggers cleanly.
  • In Step 4, watch the yellow replay #1 and replay #2 pills drive a completely fresh Worker to total = 30 — reproduced!.

Gotchas

  • Every message forwarded through a wiretap crosses an extra structured-clone hop. That's negligible for control RPCs, but if a channel moves large ArrayBuffers or streams, make sure the proxy forwards transferables (and avoids cloning huge payloads into its log) or you'll tank throughput.
  • Replaying a tape only reproduces bugs deterministically if the worker is pure with respect to its port inputs. If the worker reads Date.now(), Math.random(), network responses or shared OPFS files, you'll also need to record or stub those inputs.
  • Don't leave a flight recorder unbounded in production: keep a fixed-size ring buffer (for example the last 100 messages) and strip sensitive tokens or user data before exporting a trace.
  • If an endpoint passes reply ports inside messages (the reply-port pattern), a naïve proxy that only forwards event.data will lose event.ports — you have to forward event.ports too, or recursively wrap them if you want to record replies.

References

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

MessageChannel
Makes a new pair of joined ports, port1 and port2. 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
<iframe>
An element that shows another page inside this one. The inner page can be on a different origin, and the two can only talk by posting messages. MDNHTML Standard
ArrayBuffer
A block of raw bytes. It can be moved to another thread without copying. MDNECMAScript
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
Origin private file system
Origin-scoped file storage hidden from the user's normal filesystem. A worker can open a file in it for fast, exclusive synchronous access. MDNFile System Standard
MessageEvent.ports
The ports that arrived with a message, as an array on the event. MDNHTML Standard

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