Port patterns / Hot-swapping, wiretapping and liveness
Restart a hung worker and replay its pending work
Give a worker a work port and a health port. If it locks up in an infinite loop or calls close(), three missed pings trigger a clean recovery: terminate the dead worker, spawn a fresh one, transfer new ports, and replay every unanswered request. Callers just get their answer slightly later.
When you'd use this
You run a third-party OCR, PDF, or Wasm library in a Web Worker that occasionally deadlocks on weird inputs. Tracking pending idempotent calls alongside a health port lets you automatically kill hung workers, boot a clean replacement, and replay in-flight work transparently.
Code
function start() {
const worker = new Worker("/patterns/alive-worker.js", { type: "module" });
const work = new MessageChannel(), health = new MessageChannel();
worker.postMessage({ ports: true }, [work.port2, health.port2]);
current = work.port1; // route work to the newest worker
work.port1.onmessage = ({ data }) => {
const job = pending.get(data.id); if (!job) return;
pending.delete(data.id); job.resolve(data.count);
};
const watcher = watch(health.port1, { every: 500, misses: 3, onState(state) {
if (state !== "silent") return;
watcher.stop(); health.port1.close(); work.port1.close(); worker.terminate();
start(); // boot replacement worker
for (const [id, ask] of pending) {
if (++ask.tries > 2) { pending.delete(id); ask.reject(new Error("worker keeps hanging")); }
else current.postMessage({ id, n: ask.n }); // replay unanswered work
}
} });
}
In practice
// document scanner running third-party OCR in a worker that occasionally hangs
const pending = new Map();
let current, next = 0;
start();
const wordsOnPage = (n) => new Promise((resolve, reject) => {
const id = ++next;
pending.set(id, { n, resolve, reject, tries: 0 });
current.postMessage({ id, n });
});
// worker hangs mid-page: 3 missed pings terminate it, boot worker #2, and replay
wordCount.textContent = await wordsOnPage(12);
How it works
Track every in-flight request in a pending map and run health pings on a dedicated second port. After three missed pings, call worker.terminate() (which kills even an infinite synchronous loop), spawn a replacement worker with fresh work and health ports, and replay every unanswered request.
Callers never see the crash or restart — their promise just takes a couple of seconds longer to resolve.
Only replay work that's idempotent (like counting primes or parsing). For requests with side effects, deduplicate with an idempotency key on the server or in IndexedDB because the new worker starts with blank memory.
Step by step
What each press of Next does in the demo above.
- Start the worker. Starts worker #1 and transfers a work port and a health port to it.
- Ask: primes below 5 million. Sends a job on the work port and gets the prime count back.
- Make the worker hang. Puts worker #1 into an infinite loop so it stops answering both work and health pings.
- Ask: primes below 5 million. This request queues in pending. After three missed pings, the page terminates worker #1, spawns worker #2, and replays the job.
- Make the worker close itself. The worker calls close() silently — three missed pings catch it and boot worker #3.
What you can build with it
Already running elsewhere
- Resilient worker pools that automatically replace hung third-party libraries or Wasm modules without failing caller promises. See the demo at the top of this page.
Things to try
- Trigger Make the worker hang, then ask for primes — after three missed pings, worker #2 boots and delivers the answer.
- Trigger Make the worker close itself to see silent self-termination caught the same way.
Gotchas
- Don't auto-replay non-idempotent requests without external deduplication.
- Long synchronous loops block health pings too — yield periodically in legitimately slow workers, and don't detach transferable buffers you'd need to resend on retry.
- Cap retry attempts so a worker that crashes on startup doesn't spin in an infinite restart loop.
Measured
Chromium 153: an infinite-loop worker is terminated and replaced 1.5–2 s after pings stop, and the queued job completes on worker #2. 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.
- Web Workers
- Scripts that run on their own thread, away from the page. MDNHTML 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.