Node.js is single-threaded by default, making CPU-intensive tasks a performance bottleneck. NestJS leverages worker threads to solve this—offloading heavy operations without blocking the main event loop.
You’ll quickly find that your app freezes, blocks requests, or slows down. That’s because Node.js is single-threaded by default.
So the challenge is:
How do we handle CPU-heavy workloads without blocking the main thread?
Let’s dive deep into how to implement true parallelism in Node.js using multi-threading techniques and learn which is best for your use case.
Why Worker Threads?
- Problem: Synchronous CPU-heavy tasks (calculations, image processing) block the main thread.
- Solution: Worker threads run parallel to the main thread, freeing the event loop.
- Key Use Cases:
- Mathematical computations (e.g., Fibonacci)
- Image/video processing
- Large dataset parsing
Setup & Dependencies
First, install Node.js (≥ v12) and create a NestJS project:
npm i -g @nestjs/clinest new worker-demo
Install sharp for image processing (our example):
npm install sharp
Offload image resizing using sharp.
Worker Setup
src/workers/image.worker.ts
Service & Controller
src/image/image.service.ts
src/image/image.controller.ts
Result: Uploaded images are resized in parallel threads, keeping your API responsive.
Node.js Execution Model: The Basics
- Node.js uses a single-threaded event loop for asynchronous I/O (like reading files, querying DBs, etc.).
- It’s fast for I/O-bound tasks, but CPU-bound operations can block the loop and freeze the app.
To fix that, Node.js provides:
- worker_threads – true multi-threading
- cluster – process-level parallelism
- child_process – isolated subprocess execution
When to Use What in NestJS
Hope you find it helpful!!