When to use
- CPU-bound tasks (crypto, compression, image/video processing) that would block event loop.
- Avoid for short, tiny tasks—overhead may outweigh benefit.
Patterns
- Use a pool (e.g., piscina/workerpool) with bounded size; queue tasks.
- Pass data via
Transferablewhen large buffers; avoid heavy serialization. - Propagate cancellation/timeouts; surface errors to main thread.
Observability
- Track queue length, task duration, worker utilization, crashes.
- Monitor event loop lag to confirm offload benefits.
Safety
- Validate inputs in main thread; avoid untrusted code in workers.
- Cleanly shut down pool on SIGTERM; drain and close workers.
Checklist
- CPU tasks isolated to workers; pool sized to cores.
- Transferables used for big buffers; timeouts set.
- Metrics for queue/utilization/errors in place.