Port Authority

Port patterns / Off the main thread: Actors, Remote DOM and media

A worker that plays music while this page is frozen

Sound is made on a thread of its own, and that thread accepts a port. This page starts an audio processor and a worker, gives each one end of a channel, and steps away. The worker writes the tune and sends each note straight to the audio thread, which plays it and says so. Freeze this page for three seconds: the buttons stop working and its counter stops, but the music keeps time because none of it passes through here. The audio thread has no DOM, no timers and no network. A port is the only way to reach it, and anything that holds the other end can.

When you'd use this

You're building a browser DAW, step sequencer, or audio synthesiser where opening a heavy UI dialog or rendering waveforms on the main thread must never make playback stutter. Wire your sequencer Worker straight to your AudioWorkletProcessor over a MessageChannel.

Code

const node = new AudioWorkletNode(audio, "bell");
const { port1, port2 } = new MessageChannel();
composerWorker.postMessage({}, [port1]);
node.port.postMessage({}, [port2]);        // the audio thread now holds a port

// the worker, every beat. The page is not involved.
port.postMessage({ freq: 440 });

In practice

// AudioWorkletProcessor accepting a direct port from a sequencer Worker
class Bell extends AudioWorkletProcessor {
  constructor() {
    super();
    this.port.onmessage = ({ ports: [notes] }) => {
      notes.onmessage = ({ data }) => { this.freq = data.freq; notes.postMessage({ played: true }); };
    };
  }
  process(inputs, outputs) { /* synthesise audio into outputs[0] */ return true; }
}
registerProcessor("bell", Bell);

// composer worker sends notes straight to the audio thread
onmessage = ({ ports: [port] }) => {
  setInterval(() => port.postMessage({ freq: pattern[step++ % pattern.length] }), 125);
};

How it works

An AudioWorkletProcessor runs on the browser's high-priority real-time audio thread — no DOM, no setTimeout, no network — and exposes a MessagePort that can accept further transferred ports.

This page creates a MessageChannel, hands one end to a Composer Web Worker and the other to the AudioWorklet, and steps out of the way. Freezing the main thread for 3 seconds locks up the entire UI while the music keeps playing without missing a beat.

What you can build with it

Built and running below.

A decoder worker that hands sound straight to the speakers

Streaming decoded audio from a worker straight into the audio thread.

A worker produces sound a tenth of a second at a time, as a decoder would, and moves each block of samples down a port to the audio thread. The audio thread plays them and reports how far it has got, and the worker uses that to stay about half a second ahead. This page introduced the two and holds nothing. Freeze it for three seconds and the sound carries on without a gap, because no sample ever passes through here.

Code

// the worker: stay half a second ahead of what has been played
port.onmessage = ({ data }) => {
  while (sent - data.played < sampleRate / 2) {
    const block = decodeNext();                       // a Float32Array
    port.postMessage({ block }, [block.buffer]);      // moved to the audio thread
    sent += block.length;
  }
};

Step by step

What each press of Next does in this demo.

  1. Start the decoder. The worker and the audio thread are introduced. Blocks of sound start to flow between them.
  2. Freeze this page for 3 seconds. The page stops. The worker keeps decoding and the audio thread keeps playing.
  3. Stop the sound. The audio is closed.

A level meter drawn by a worker, fed from the audio thread

Sending real-time level meters or FFT data from the audio thread to an OffscreenCanvas worker.

A tone swells and fades. A processor on the audio thread measures how loud it is, twenty times a second, and posts each reading down a port. The other end is held by a worker, which draws the meter into a canvas it was handed. The readings go from the audio thread to the worker to the screen. Freeze this page and the meter keeps moving, in time with what you hear.

Code

// on the audio thread: pass audio through and send RMS twenty times a second
process([input], [output]) {
  const ch = input[0]; if (!ch) return true;
  for (let c = 0; c < output.length; c++) output[c].set(ch);
  for (let i = 0; i < ch.length; i++) this.sum += ch[i] * ch[i];
  if ((this.n += ch.length) >= sampleRate / 20) {
    meterPort.postMessage({ level: Math.sqrt(this.sum / this.n) });
    this.sum = this.n = 0;
  }
  return true;
}

Step by step

What each press of Next does in this demo.

  1. Start the tone and the meter. The audio thread and the meter's worker are given one end each of a channel.
  2. Freeze this page for 3 seconds. The page stops. The meter does not.
  3. Stop the sound. The audio is closed.

Already running elsewhere

Things to try

  • Start the music, freeze this page for 3 seconds, and listen — the beat never stutters.
  • Check the note count after the freeze: roughly 13 notes played while the main thread ticked 0 times.

Gotchas

  • Browsers require a real user gesture before unlocking AudioContext.
  • Never allocate heavily or post messages on every 128-sample render quantum inside process() — batch telemetry, and use a SharedArrayBuffer ring buffer on cross-origin isolated pages for jitter-free high-rate PCM streaming.
  • The audio thread only accepts a tiny subset of transferables (ports, buffers, and streams).

Measured

Chromium 157: 13 notes played cleanly during a 3-second main-thread freeze. Other browsers are being filled in from the lab's results.

References

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

AudioWorklet
Code that processes audio on the browser's audio thread. Each node has a port for talking to the page, and newer browsers are adding a shared audioWorklet.port on the scope itself. MDNWeb Audio API
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
Web Workers
Scripts that run on their own thread, away from the page. MDNHTML Standard
OffscreenCanvas
A canvas that is not attached to the page, so a worker can draw to it. MDNHTML Standard
SharedArrayBuffer
A block of raw bytes that several threads can read and write at the same time. Posting it shares it instead of copying it. MDNECMAScript
Cross-origin isolation
A state a page enters by sending two headers. It keeps other origins out of the page's process, and the browser then allows shared memory. MDNHTML Standard
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

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