Node.js Event Loop, Streams & Backpressure: Performance in Depth
By: Md Tarek · 17 Oct 2026
Executive Summary & Key Takeaways
- Node is single-threaded for your JavaScript, but I/O is not. The event loop offloads file, network, and DNS work to a thread pool and the OS, then resumes your callbacks when results are ready.
- Blocking the loop blocks everything. A synchronous CPU-heavy task (JSON.parse on a huge payload, a tight loop) stalls every other request on that process.
- Streams let you process data in chunks instead of buffering it all in memory — essential for large files and high-throughput pipes.
- Backpressure is the contract that prevents memory blowup. A writable that signals
falsefromwrite()is asking you to pause the producer untildrainfires. - Use `pipe` / `pipeline`, not manual `data` events.
pipelinehandles error propagation and cleanup correctly where hand-rolled code leaks.
1. The Event Loop Phases
The loop cycles through timers, pending callbacks, idle/prepare, poll (I/O), check (setImmediate), and close callbacks. Understanding the poll phase explains the classic setTimeout(fn, 0) vs setImmediate(fn) ordering question — the answer depends on whether you are inside an I/O callback.
2. Streams and Backpressure
The write() method returns a boolean that tells you whether the internal buffer is below its high-water mark. Ignoring it is how you turn a 10 GB file into a 10 GB memory spike:
import { pipeline } from 'node:stream/promises';
await pipeline(
sourceStream,
transformStream,
destinationStream,
);pipeline wires up backpressure, error handling, and cleanup for you.
3. Common Performance Pitfalls
| Pitfall | Symptom | Fix | |---|---|---| | sync JSON.parse on huge body | loop blocked, latency spikes | stream parser or worker | | unbounded buffers | OOM | backpressure / streams | | too many awaits in a row | latency | Promise.all where independent | | CPU work on main thread | event loop lag | worker_threads |
4. Measuring Loop Lag
Track event-loop lag in production — a moving average of setTimeout delay is a cheap proxy. When lag climbs, you are CPU-bound on the main thread and should move work to workers or offload to a queue.
FAQ
When should I use worker_threads? For CPU-bound work like image processing, compression, or heavy computation. For I/O-bound work, async and the thread pool already scale without extra workers.
