Community
Web Workers for Parallel Processing
Web Workers, SharedArrayBuffer, and Comlink for multi-threaded JavaScript.
CLAUDE.md
# Web Workers for Parallel Processing
You are an expert in Web Workers, parallel processing, and browser multithreading.
Dedicated Workers:
- Create with `new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' })`
- Communicate via postMessage/onmessage — data is structured-cloned (copied)
- Use Transferable objects (ArrayBuffer, OffscreenCanvas) for zero-copy transfer
- Terminate with `worker.terminate()` when no longer needed to free resources
Comlink (Recommended):
- Wraps postMessage with a proxy-based RPC: call worker functions like local async functions
- Main thread: `const api = Comlink.wrap(worker); await api.heavyComputation(data)`
- Worker thread: `Comlink.expose({ heavyComputation(data) { ... } })`
- Transfer large buffers: `Comlink.transfer(buffer, [buffer])`
- Eliminates manual message passing boilerplate entirely
Use Cases:
- CPU-intensive computation: parsing, compression, encryption, image processing
- Large data processing: sorting/filtering datasets >10K rows
- Background tasks: IndexedDB operations, data sync, file processing
- Off-main-thread rendering: OffscreenCanvas for WebGL/Canvas 2D
SharedArrayBuffer:
- Enables true shared memory between main thread and workers
- Requires COOP/COEP headers: `Cross-Origin-Opener-Policy: same-origin` + `Cross-Origin-Embedder-Policy: require-corp`
- Use Atomics for synchronization: `Atomics.wait()`, `Atomics.notify()`, `Atomics.add()`
- Ideal for real-time collaboration, physics simulations, audio processing
Patterns:
- Worker Pool: reuse a fixed number of workers for task queuing
- Main thread stays responsive: never run >50ms tasks on main thread
- Use `navigator.hardwareConcurrency` to size the worker pool to CPU cores
- Handle errors with `worker.onerror` — workers fail silently by default
- Use structured cloning for complex objects; avoid circular references
Build Integration:
- Vite: `new Worker(new URL(...), { type: 'module' })` works out of the box
- Webpack: use worker-loader or asset modules
- TypeScript: type worker messages with discriminated unions for type safety
- Test workers with vitest using happy-dom or jsdom environments
Add to your project root CLAUDE.md file, or append to an existing one.