Node.js Event Loop Blocking in NestJS: How We Measure Lag and Offload CPU Work to worker_threads with Piscina
Table of Contents
About the Author

Ahmed Mahmoud
Author & Developer
Software engineer passionate about web development and user experience design.
Founder of Devya · eng-ahmed.com ↗Headline: A Node.js process runs all of its JavaScript on one event-loop thread, so one synchronous CPU-heavy call, such as a PDF render, a large JSON.parse, or crypto.pbkdf2Sync, stalls every concurrent request on that process. At Devya we measure the stall with monitorEventLoopDelay() and performance.eventLoopUtilization(), switch to the async core API when one exists, and move the remaining CPU-bound JavaScript into a bounded Piscina worker pool with a queue limit and an AbortSignal.
The bug reports our team receives never say "event loop". They say the health check timed out, or that an endpoint that reads one row from Postgres took seconds at the exact moment someone exported a report. The cause is usually one function doing a lot of synchronous work on the main thread. These are our field notes on finding that function, deciding where its work should run, and wiring a worker pool into a NestJS service without creating a new failure mode.
Key takeaways
One thread is shared by every request: while synchronous JavaScript runs on the Node.js main thread, no other request on that process gets a callback, a timer, or a socket read.
Measure before moving code: monitorEventLoopDelay() from node:perf_hooks records event loop delay as a histogram in nanoseconds, and performance.eventLoopUtilization() reports the share of time the loop was busy.
Try the cheapest fix first: crypto.scrypt, crypto.pbkdf2, and zlib.gzip already run on the libuv thread pool; only their Sync variants block the event loop.
Use Piscina for your own CPU-bound JavaScript: Piscina is a worker_threads pool, and we set maxThreads, idleTimeout, and maxQueue explicitly and close the pool in onModuleDestroy.
A worker pool is not a job queue: a Piscina task lives in process memory and is lost on a crash or deploy, so work that takes minutes or must be retried belongs in a durable queue.
What actually blocks the Node.js event loop?
Synchronous JavaScript that runs for more than a few milliseconds blocks the Node.js event loop. The event loop is the single thread that runs callbacks for timers, sockets, and resolved promises, and it cannot start the next callback until the current one returns. Awaiting a database query does not block it, because the query waits in the driver and the kernel. Parsing a multi-megabyte result of that query does block it.
The usual suspects we find in NestJS services: report and document generation done in JavaScript (PDF layout, spreadsheets, templating); JSON.parse and JSON.stringify on multi-megabyte payloads; Sync core APIs in request handlers such as crypto.pbkdf2Sync, crypto.scryptSync, zlib.gzipSync, and fs.readFileSync; regular expressions with catastrophic backtracking on user input; and tight loops over large arrays that belong in SQL.
The symptom is collateral damage. Unrelated endpoints slow down at the same moment, the load balancer marks the instance unhealthy because the health check cannot answer, and libraries miss their own timers. BullMQ renews job locks from the same event loop, so a blocked loop can make a healthy job look stalled.
How do we measure event loop lag in production?
monitorEventLoopDelay() from node:perf_hooks is the measurement we trust: it schedules a timer at a fixed resolution, records how late each tick fires, and stores the delays in a histogram measured in nanoseconds. We pair it with performance.eventLoopUtilization(), which returns idle, active, and utilization values between two readings. Utilization near 1 while request volume is modest is the clearest sign that the main thread is doing CPU work instead of waiting on I/O.
In NestJS we wrap both in a small injectable monitor. On module init it enables the histogram at a 20 ms resolution and starts an unref'd 10-second interval, so reporting never keeps the process alive. Each tick logs p50, p99, and max delay in milliseconds plus the utilization delta since the previous tick, then resets the histogram. On module destroy it clears the interval and disables the histogram.
When we tested the monitor with a deliberate 200 ms busy-loop, the histogram's max reported roughly that 200 ms: the metric measures the stall itself, not a proxy. We alert on sustained p99 delay rather than on max, because one startup tick or a long garbage-collection pause produces a large max with no user impact.
To find which function blocks, we reproduce the slow path locally with node --cpu-prof. That flag writes a .cpuprofile file when the process exits, Chrome DevTools opens it as a flame chart, and the widest synchronous frame under a request handler is the culprit.
Is the libuv thread pool the same as worker_threads?
No. The libuv thread pool is a fixed set of native threads (4 by default, changed with the UV_THREADPOOL_SIZE environment variable) that Node.js core uses for file system calls, dns.lookup, and the async variants of crypto and zlib; it never runs your JavaScript. The worker_threads module starts additional threads that each get their own V8 isolate and event loop, so they can run your JavaScript in parallel with the main thread.
Async core API (crypto.scrypt, zlib.gzip): native code on the libuv pool. We use it whenever a core async variant exists. Cost: it shares four threads with file system calls and dns.lookup.
worker_threads via Piscina: your JavaScript in a separate V8 isolate. We use it for CPU-bound JavaScript whose result goes into the HTTP response. Cost: memory per thread and message copying.
Child process or separate service: a separate OS process. We use it for crash isolation or a different runtime. Cost: process startup plus IPC or HTTP.
Durable job queue (BullMQ): a separate worker process. We use it for minutes of work, retries, and surviving deploys. Cost: infrastructure and an asynchronous user experience.
The first fix is often not a worker at all. Replacing crypto.scryptSync with a promisified crypto.scrypt moves password hashing off the main thread in one line.
How do we run CPU-bound work in a Piscina pool inside NestJS?
Piscina is a worker thread pool for Node.js: it keeps a set of worker threads alive, queues tasks, and resolves each pool.run() call with the return value of the function the worker file exports. We wrap one pool per kind of work in a NestJS provider, so the pool's lifecycle follows the module's.
The worker file exports one async function that builds the PDF bytes with a pure function and returns them wrapped in Piscina's move() helper, so the bytes are transferred back instead of copied. The provider creates the pool with filename pointing at the compiled worker in dist, minThreads 1, maxThreads from an environment variable, idleTimeout of 60 seconds, maxQueue set to 'auto', and resourceLimits capping the worker heap. Its render method calls pool.run() with an AbortSignal and turns the "Task queue is at limit" rejection into a 503, and onModuleDestroy awaits pool.close(), which waits for started tasks before stopping the threads.
Explicit thread counts matter: the Piscina 4.9 README documents minThreads as os.availableParallelism(), maxThreads as 1.5 times that, and an idleTimeout that shuts idle threads down immediately. Those defaults assume the process owns the machine, so in containers with CPU limits we set maxThreads to match the allotment.
The worker file stays out of Nest: every worker thread evaluates its own imports, so a worker file that imports AppModule opens a database pool per thread. Our worker files import pure functions only.
What does it cost to send data to a worker thread?
Every argument passed to pool.run() is copied into the worker with the structured clone algorithm, and the serialization half of that copy runs on the main thread. Sending a huge object to a worker still blocks the event loop for the time it takes to clone it.
We send the minimal input the computation needs, as plain objects rather than ORM entities, because structured clone drops class prototypes and their methods. Binary data moves instead of copying: an ArrayBuffer in the transferList option of run() hands ownership to the worker, and Piscina's move() does the same for return values.
What happens when the worker pool is saturated?
A worker pool without a queue limit turns a CPU problem into a memory problem. Piscina's maxQueue option caps the tasks waiting for a thread, the value 'auto' sets it to maxThreads squared, and once the queue is full run() rejects with "Task queue is at limit". We map that rejection to HTTP 503 so clients retry later.
Cancellation uses the signal option of run(). A queued task is cancelled; a running task has its worker thread stopped and replaced. Our controllers abort when the response closes before writableFinished is true, combined with AbortSignal.timeout() through AbortSignal.any(), so a pathological input cannot hold a thread forever.
Piscina also exposes waitTime, runTime, and utilization on the pool. We log queue wait next to event loop delay: rising wait time with flat loop delay means the pool is too small, not that the main thread is blocked.
When should we use a job queue instead of worker threads?
We use worker threads when the result belongs in the HTTP response and the work finishes well inside the request timeout. We use a durable job queue when the work takes minutes, needs retries, or must survive a deploy, because a Piscina task lives in process memory and a crash or rolling deploy drops it.
Worker threads do not add CPU cores. On a container limited to one vCPU, the pool shares that core with the main thread: the scheduler keeps the event loop responsive, but the CPU work does not finish faster. When the pool is saturated on every core, the answer is more instances or a queue.
FAQ
Q: How much event loop delay is too much in a Node.js API?
A: No universal number exists, because event loop delay adds directly to the latency of every request in flight on that process. We alert on sustained p99 delay from monitorEventLoopDelay() relative to the API's latency target, not on the max value.
Q: Does async/await prevent event loop blocking?
A: No. An async function only yields to the event loop at an await; synchronous code between two awaits runs on the main thread without interruption.
Q: Should we use Piscina or the raw worker_threads module?
A: The raw worker_threads module is enough for one long-lived worker with a custom message protocol. For request-driven tasks we use Piscina, because it already handles the pool, the bounded queue, AbortSignal cancellation, and mapping each task to its result.
Q: Does raising UV_THREADPOOL_SIZE fix a blocked event loop?
A: No. UV_THREADPOOL_SIZE only sizes the libuv pool that runs async file system, DNS, crypto, and zlib work; synchronous JavaScript on the main thread is unaffected by it.
Further Reading
Backend Engineering
Postgres LISTEN/NOTIFY in Node.js and NestJS: How We Invalidate Caches Across Replicas Without Losing Notifications on Reconnect
PostgreSQL LISTEN/NOTIFY gives Node.js apps a transactional, zero-infrastructure signal that fires only when a write commits. Here is how we use it to invalidate in-memory caches across NestJS replicas: a trigger that calls pg_notify, a dedicated listener connection that survives reconnects, and the limits that tell us when to switch to Redis or CDC.
Backend Engineering
Postgres Transaction Isolation Levels from Node.js: Write Skew, SERIALIZABLE, and Retrying 40001
PostgreSQL defaults to READ COMMITTED, which lets two concurrent requests each pass a check and together break an invariant. This is how our team chooses between a constraint, an atomic UPDATE, a parent-row lock, and SERIALIZABLE, and how we retry SQLSTATE 40001 safely from Node.js.