Frontend System Design · Lesson 11 of 86 · 4 min
Web Workers: Multi-threading in the Browser
This topic shows you understand the browser's single-threaded nature and its primary escape hatch for heavy computation.
In an interview, you use Web Workers to answer the question: "How do you run a CPU-intensive task without freezing the page?" They let you execute a script on a background thread, separate from the main thread that handles UI rendering and user interactions.
This is true parallelism. Don't confuse it with the concurrency model of async/await, which juggles tasks on the same main thread. A worker is for when you have a single, long-running, synchronous block of code that would otherwise halt everything.
When to use a Worker (and when not to)
The browser's main thread does everything: it runs your JavaScript, performs layout, paints pixels, and responds to user input. To maintain a smooth 60 frames per second, it has about 16ms to do all of this for each frame. A synchronous script that takes 100ms to run will block rendering for several frames, making the UI feel frozen.
Use a Worker for tasks that are CPU-bound and take a noticeable amount of time (think >50-100ms).
Good candidates for a Worker:
- Parsing a large file (CSV, JSON) on the client side.
- Complex calculations like image filtering, audio processing, or cryptographic operations.
- Diffing large objects or running intensive search algorithms on a large dataset.
The trap: Don't use a Worker for I/O-bound tasks like fetch. Network requests are already non-blocking and handled efficiently by the browser. Creating a worker just to make a fetch call adds unnecessary overhead. The same goes for trivial computations; the cost of creating the worker and passing messages will be higher than the work itself.
How Workers communicate with the main thread
A Worker runs in a completely isolated environment. It has no access to the window object, the DOM, or your main script's variables. The only way to communicate is by passing messages.
The main thread creates a worker, sends it data with worker.postMessage(), and listens for results with worker.onmessage. The worker listens with self.onmessage and sends data back with self.postMessage().
By default, data sent via postMessage is cloned using the structured clone algorithm. This is fine for small objects, but for large data (like a 10MB ArrayBuffer), the copying process itself can be slow and memory-intensive.
The code: A basic calculation worker
Here’s the most common pattern. The main script creates the worker and delegates a heavy calculation. The worker does the math and sends the result back.
First, the worker script. It listens for a message, runs a blocking calculation, and posts the result.
// worker.js
self.onmessage = function(e) {
const upperLimit = e.data;
// This is a deliberately slow, blocking operation.
let sum = 0;
for (let i = 0; i < upperLimit; i++) {
sum += i;
}
// Send the result back to the main thread.
self.postMessage(sum);
};
Next, the main script that uses this worker.
// main.js
// Check for browser support first.
if (window.Worker) {
const myWorker = new Worker('worker.js');
// Send data to the worker to start the calculation.
console.log('Main: Posting message to worker.');
myWorker.postMessage(1_000_000_000);
// Listen for the result.
myWorker.onmessage = function(e) {
console.log('Main: Message received from worker:', e.data);
// You would update the UI here.
};
// Listen for errors.
myWorker.onerror = function(error) {
console.error('Main: Worker error:', error.message);
};
// The main thread is not blocked.
console.log('Main: Worker is running, but I am not blocked!');
} else {
console.log('Your browser doesn\'t support Web Workers.');
}
While the worker is busy counting to a billion, the main thread is free to log its final message and handle any user interactions.
Avoiding performance traps
The trap: Sending large amounts of data to and from a worker can be a bottleneck due to the structured cloning overhead. If you're processing a large file or image, the time spent just copying the data can defeat the purpose of using a worker.
The solution is to use Transferable Objects. When you transfer an object like an ArrayBuffer, its ownership is moved to the worker, not copied. This is nearly instantaneous. The original object in the main thread becomes unusable.
To transfer an object, you pass it as the second argument to postMessage:
// main.js
const largeBuffer = new ArrayBuffer(1024 * 1024 * 10); // 10MB buffer
// The second argument is a list of objects to transfer.
myWorker.postMessage(largeBuffer, [largeBuffer]);
// At this point, `largeBuffer` is neutered in the main thread.
// console.log(largeBuffer.byteLength); // Throws an error.
The worker receives the buffer and can transfer it back the same way after processing.
Also, remember that workers are not free. They consume memory and CPU. If a worker is no longer needed, terminate it explicitly with worker.terminate() to release its resources. This is crucial in single-page applications where components that create workers might be unmounted.
What interviewers are listening for
When you discuss Web Workers, they want to see if you understand the core trade-offs.
"I would use a Web Worker for a CPU-intensive, synchronous task that blocks the main thread, like client-side parsing of a large file. I'd be mindful of the data transfer cost between the main thread and the worker. For large data, I'd use Transferable Objects like an ArrayBuffer to avoid the overhead of structured cloning. The worker can't access the DOM, so once it's done, it posts a message back, and the main thread updates the UI with the result."
This answer demonstrates:
- The Problem: You know what "blocking the main thread" means and when it happens.
- The Solution: You correctly identify Web Workers as the tool for CPU-bound tasks.
- The Mechanism: You understand communication happens via
postMessage. - The Limitation: You know workers are isolated and can't touch the DOM.
- The Performance Nuance: You can speak to the cost of data transfer and know the optimization (
Transferable Objects).
Try it
Take the prime number calculation code from the original lesson. Implement it yourself. Open your browser's performance monitor, run the calculation without a worker, and observe how the UI freezes. Then, run it with the worker and confirm that the main thread remains responsive. This will make the concept stick.
Next: We'll cover Browser Storage: Cookies, Web Storage, IndexedDB, and when to use each.
Lock it in — apply this lesson under interview conditions.