Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Frontend System Design Roadmap
  1. 1.HTTP/1.1 vs HTTP/2 vs HTTP/3 (QUIC)
  2. 2.TCP and TLS Handshakes: Connection Setup Costs
  3. 3.Browser Network Stack and Connection Pooling
  4. 4.GET vs POST and Idempotency in HTTP
  5. 5.The Critical Rendering Path (CRP)
  6. 6.DOM, CSSOM and the Render Tree
  7. 7.Layout, Paint and Compositing
  8. 8.Reflows and Repaints Explained
  9. 9.Event Loop: Call Stack, Task and Microtask Queues
  10. 10.Async JavaScript: Promises and async/await
  11. 11.Web Workers: Multi-threading in the Browser
  12. 12.Browser Storage: Cookies, Web Storage, IndexedDB
  13. 13.Client-Side Storage: Limits and Security Risks
  14. 14.Choosing the Right Client-Side Storage
  15. 15.HTTP Caching: Cache-Control, ETag, Last-Modified
  16. 16.Browser-Level Caching Mechanisms
  17. 17.Cache Invalidation for Frontend Apps
  18. 18.Structuring a Large Single-Page App
  19. 19.Component-Based Architecture Principles
  20. 20.Props, State and Component Lifecycle
  21. 21.Module Bundling Basics
  22. 22.Core Web Vitals: LCP, INP and CLS
  23. 23.FCP and Time to Interactive (TTI) Explained
  24. 24.Measuring Performance: Lighthouse and WebPageTest
  25. 25.Asset Compression and Minification Basics
  26. 26.What Is a CDN and How Does It Work?
  27. 27.CDN Benefits: Latency, Availability, Offload
  28. 28.CDN Cache Behavior and Invalidation
  29. 29.Global State vs Local Component State
  30. 30.State Patterns: Redux, Zustand and Context
  31. 31.Data Fetching: React Query and SWR
  32. 32.Immutable Data in Frontend State
  33. 33.SSR vs CSR: Rendering Trade-offs
  34. 34.Hydration and Time to First Byte (TTFB)
  35. 35.Static Site Generation (SSG) for Speed and SEO
  36. 36.Incremental Static Regeneration (ISR)
  37. 37.Micro-Frontends: Core Principles
  38. 38.Micro-Frontend Integration Strategies
  39. 39.Communication Between Micro-Frontends
  40. 40.Micro-Frontends: Pros and Cons for Large Teams
  41. 41.Real-Time: Polling, SSE and WebSockets
  42. 42.Real-Time Use Cases: Chat, Alerts, Live Data
  43. 43.Designing a Real-Time Data Flow
  44. 44.Scaling WebSocket Connections
  45. 45.Responsive Images: srcset, sizes and picture
  46. 46.Modern Image Formats: WebP, AVIF, JPEG XL
  47. 47.Lazy Loading Images and Videos
  48. 48.Video Streaming: HLS, DASH, Adaptive Bitrate
  49. 49.REST and GraphQL for Frontend Engineers
  50. 50.Batching, Throttling and Debouncing API Calls
  51. 51.Handling API Errors in the Frontend
  52. 52.Authentication Flows: OAuth and JWT
  53. 53.Global Error Boundaries in React
  54. 54.Error Reporting: Sentry and LogRocket
  55. 55.Graceful Degradation and Fallback UIs
  56. 56.Real User Monitoring (RUM)
  57. 57.CORS: Cross-Origin Resource Sharing
  58. 58.Preventing XSS (Cross-Site Scripting)
  59. 59.CSRF Protection for Frontend Apps
  60. 60.Content Security Policy (CSP)
  61. 61.Storing Auth Tokens: Cookies vs localStorage
  62. 62.PWA Manifest and Installability
  63. 63.Service Workers: Lifecycle and Caching Strategies
  64. 64.Offline Support and Background Sync
  65. 65.Push Notifications for Web Apps
  66. 66.Webpack vs Vite vs Parcel
  67. 67.Code Splitting, Tree Shaking, Asset Optimization
  68. 68.Module Resolution and Hot Module Replacement
  69. 69.Monorepo Tooling: Nx and Lerna
  70. 70.Atomic Design for Component Libraries
  71. 71.Theming and Customization in Design Systems
  72. 72.Accessibility in Component Libraries
  73. 73.Component Library Docs, Testing and Versioning
  74. 74.Publishing and Consuming a Component Library
  75. 75.Full-Text Search: Levenshtein and Fuzzy Matching
  76. 76.Indexing Large Datasets in the Browser
  77. 77.Search Performance: Debouncing and Web Workers
  78. 78.Integrating Backend Search Services
  79. 79.Choosing a Chart Library: D3, Chart.js, Recharts
  80. 80.Rendering Large Datasets: Canvas vs SVG
  81. 81.Interactive, Responsive Data Visualizations
  82. 82.Data Fetching and Aggregation for Dashboards
  83. 83.A/B Test Design and Rollout Strategies
  84. 84.Client-Side vs Server-Side A/B Testing
  85. 85.Feature Flags and Remote Configuration
  86. 86.Experiment Data Collection and Analytics
Frontend System Design Roadmap
11

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:

  1. The Problem: You know what "blocking the main thread" means and when it happens.
  2. The Solution: You correctly identify Web Workers as the tool for CPU-bound tasks.
  3. The Mechanism: You understand communication happens via postMessage.
  4. The Limitation: You know workers are isolated and can't touch the DOM.
  5. 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.

Try a free mock interviewPractice system design problems
Previous

Async JavaScript: Promises and async/await

Next

Browser Storage: Cookies, Web Storage, IndexedDB