FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Offloading Browser Inference to Web Workers

Run inference in a dedicated Worker to keep model compute off the UI event loop, with explicit buffer ownership, bounded requests, and visible startup failures.

Freshness: current•12 min read•Deep Learning and Specialized AI
Full Technical Reference Document

Mental model

A dedicated Web Worker gives browser inference a separate JavaScript agent and event loop, so model loading and execution do not monopolize the UI thread. The main thread still owns rendering and interaction, while messages cross an explicit boundary with either copied or transferred data. This can protect responsiveness, but it does not guarantee faster inference or make cancellation automatic.

Learning outcomes

  • Distinguish main-thread responsiveness from model inference latency and throughput.
  • Choose between structured cloning and transferring an ArrayBuffer, accounting for detached sender buffers.
  • Bound work sent to a Worker and expose initialization, inference, timeout, and failure states.
  • Identify when ONNX Runtime's WASM proxy, thread settings, or WebGPU provider change the deployment constraints.

Theory

A Worker runs JavaScript outside the document's main event loop and cannot directly manipulate the DOM. The page sends a message with postMessage; the browser structured-clones supported values unless a transferable is supplied. For a transferable ArrayBuffer, ownership moves to the receiving context. The sender's buffer becomes detached, so retaining a copy for UI work requires an explicit copy before transfer.

Moving an inference call changes where the work blocks. It does not remove the arithmetic, shrink the model, or reserve a physical CPU core. A Worker can still compete with scrolling, audio, and other tabs for CPU time; on constrained devices it may even increase battery or thermal pressure. Measure two separate outcomes: main-thread long tasks and input delay, plus model cold-start and warm-run latency. If inference time is unchanged while long tasks fall, the Worker has improved responsiveness without accelerating the model.

For a batch-one FP32 image model with shape [1,3,224,224][1,3,224,224], the input tensor size is:

Binput=N×C×H×W×bB_{input}=N \times C \times H \times W \times b

Here BinputB_{input} is bytes, NN is batch size, CC is channel count, HH and WW are pixel dimensions, and bb is bytes per scalar. With N=1N=1, C=3C=3, H=W=224H=W=224, and b=4b=4, the tensor contains 602,112 bytes, about 0.574 MiB. A 1,000-class FP32 output is only 4,000 bytes. Transferring the input buffer avoids cloning that 0.574 MiB, but detaches it from the sender; copying first preserves the page's original data at the cost of another allocation and copy.

The message protocol is an API boundary, not a function call. Include a request ID, validate the expected tensor shape and type, and return a typed result or an explicit error. Keep one in-flight request per model session unless measurements justify a queue or a worker pool. An unbounded message queue can grow memory use and make old predictions arrive after the user has moved on. The page should ignore results whose request IDs are stale.

Validate model request and tensor shape
Transfer owned input buffer to dedicated worker
Create or reuse the ONNX inference session
Run inference under a bounded execution provider
Return scores or a typed failure with request ID
Conceptual teaching model synthesized from:whatwg-web-workers-spec,onnx-runtime-web-env-flags

Trade-offs

DesignUseful whenCost to make explicit
Run inference on the page threadThe model is tiny and results are needed immediatelyA long synchronous or WASM task can delay paint and input handling
Own a dedicated Worker and sessionThe app needs request IDs, lifecycle states, and a predictable message boundaryModel assets must resolve from the worker bundle; transferred buffers detach
Enable ONNX Runtime's WASM proxy WorkerThe existing app uses the WASM provider and wants to move heavy work with a runtime optionThe proxy uses a Blob Worker, which can be blocked by strict CSP, and it does not support the WebGPU execution provider

ONNX Runtime Web uses its own WASM thread setting. Its documented default is selected from available hardware concurrency, capped at four, and numThreads: 1 disables WASM multithreading. Multithreaded WASM requires browser support and crossOriginIsolated; that deployment mode depends on cross-origin isolation headers. A dedicated page Worker and the runtime's proxy Worker are different designs. Avoid nesting them without profiling, since the extra boundary can duplicate scheduling and confuse resource ownership.

The proxy is convenient for the WASM provider, but it is not a general Worker compatibility switch. ONNX Runtime documents that the proxy Worker cannot use the WebGPU provider because its GPU buffer is not transferable, and that its Blob-based Worker can fail under CSP restrictions. If the chosen provider needs a Worker-specific setup, bundle and test that setup directly in supported browsers. Always test the exact production model, runtime bundle, content policy, and headers; a development server's permissive configuration can hide a deployment failure.

Failure modes and misconceptions

  • The UI still freezes during model setup. Session creation, weight fetches, and preprocessing can be as expensive as the first inference. Send loading and ready states to the page, measure cold start separately, and do not report a usable model before the session resolves.
  • A transferred input becomes empty on the page. That is the ownership change, not data corruption. Transfer a scratch copy or hand off a buffer the page no longer needs.
  • Timed-out work keeps consuming resources. Removing a promise from the page only ignores its eventual reply; it does not interrupt a non-yielding WASM kernel. Cooperative cancellation works only at checkpoints. worker.terminate() is a hard stop, but destroys the session and forces a restart.
  • More Workers reduce latency. Inference sessions can allocate large arenas and compete for memory bandwidth. Start with one bounded session, then compare p50/p95 latency, main-thread long tasks, peak memory, and device power before adding workers.
  • The Worker silently fails in production. A bad model URL, missing WASM binary, CSP rejection, unsupported provider, or isolation-header mismatch can prevent initialization. Surface a failed state, record the runtime/provider and model version, and offer a deliberate fallback instead of spinning forever.
  • An old result overwrites a newer user choice. A completed Worker message may arrive after the selected image or prompt changed. Tag every request and apply a result only if its ID still matches the UI's active request.

Decision scenario

A product team moves a 224-by-224 classifier into a dedicated Worker. On a mid-range laptop, inference p95 remains 180 ms, but main-thread long tasks above 50 ms fall from six per interaction to zero. The page also sends a new request on every slider movement, and the worker's memory grows when a user drags continuously. Keep the Worker boundary because it protects input and paint, then debounce or replace obsolete queued inputs and allow only one active inference. Report the 180 ms model latency honestly; do not call the worker an acceleration. If the first model load takes 4 seconds, expose that cold-start state and cache versioned assets before claiming the feature is ready offline.

Implementation pattern

The page below makes one request at a time, copies the input so the caller retains ownership, and transfers the copy. The worker initializes one ONNX session, declares its model's input contract, and transfers scores back. A timeout stops waiting but does not cancel a running kernel; the failure policy must distinguish those outcomes.

js
// classifier-client.js
export const worker = new Worker(new URL("./classifier.worker.js", import.meta.url), { type: "module" });
const pending = new Map();
let nextId = 0;
export let modelState = "loading";
​
function fail(error) {
modelState = "failed";
for (const job of pending.values()) {
clearTimeout(job.timer);
job.reject(error);
}
pending.clear();
}
​
worker.addEventListener("message", ({ data }) => {
if (data.kind === "ready") { modelState = "ready"; return; }
if (data.kind === "fatal") return fail(new Error(data.message));
const job = pending.get(data.id);
if (!job) return;
pending.delete(data.id);
clearTimeout(job.timer);
if (data.kind === "result") job.resolve(data.scores);
else job.reject(new Error(data.message));
});
​
worker.addEventListener("error", ({ error }) => fail(error ?? new Error("Inference worker failed")));
​
export function classify(pixels) {
if (modelState !== "ready") return Promise.reject(new Error(`Model is ${modelState}`));
if (!(pixels instanceof Float32Array) || pixels.length !== 150_528) {
return Promise.reject(new TypeError("Expected 1 x 3 x 224 x 224 FP32 input"));
}
if (pending.size !== 0) return Promise.reject(new Error("Inference worker is busy"));
const id = ++nextId, ownedPixels = new Float32Array(pixels);
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (pending.delete(id)) reject(new Error("Inference timed out"));
}, 10_000);
pending.set(id, { resolve, reject, timer });
try {
worker.postMessage({ id, pixels: ownedPixels }, [ownedPixels.buffer]);
} catch (error) {
clearTimeout(timer);
pending.delete(id);
reject(error);
}
});
}
js
// classifier.worker.js; the ONNX artifact accepts FP32 NCHW input and returns `logits`.
import * as ort from "onnxruntime-web";
​
ort.env.wasm.numThreads = 1;
const sessionReady = ort.InferenceSession.create("/models/mobile-classifier-224.onnx", {
executionProviders: ["wasm"],
});
sessionReady.then(
() => self.postMessage({ kind: "ready" }),
(error) => self.postMessage({ kind: "fatal", message: String(error) }),
);
​
self.addEventListener("message", async ({ data }) => {
try {
const session = await sessionReady;
const input = new ort.Tensor("float32", data.pixels, [1, 3, 224, 224]);
const outputs = await session.run({ images: input });
const scores = Float32Array.from(outputs.logits.data);
self.postMessage({ kind: "result", id: data.id, scores }, [scores.buffer]);
} catch (error) {
self.postMessage({ kind: "error", id: data.id, message: String(error) });
}
});

Adapt images, logits, and the tensor shape to the exported ONNX model contract. In a product, replace the fixed “busy” response with an explicit bounded queue or latest-request-wins policy; do not queue unlimited full-size tensors. Report model download, session initialization, ready, inference, timeout, and failure separately so a UI spinner cannot mistake a slow startup for an active prediction.

Decision checklist

Before rolling out the Worker, compare the same model and input on the main thread and in a Worker. Capture cold-start and warm p50/p95, input delay, main-thread long tasks, bytes copied or transferred, peak memory, and error rate on low-memory mobile devices as well as desktop hardware. Confirm the production CSP, worker asset paths, and any cross-origin isolation headers. Keep the Worker when the responsiveness gain is worth its memory and lifecycle costs, and retain a server or simpler local fallback for devices that cannot initialize the chosen runtime.

Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next