The Node.js Event Loop, Explained Properly

One thread, thousands of connections

Node.js runs your JavaScript on a single thread, yet handles thousands of concurrent connections. The event loop is how. Understanding it explains most Node performance problems.

The Big Idea

Node doesn't wait for slow operations (network, disk). It starts them, registers a callback, and moves on. When the operation finishes, the callback is queued and the event loop runs it.

Phases of the Loop

  1. Timers — setTimeout, setInterval callbacks
  2. Pending callbacks — some system-level callbacks
  3. Poll — wait for and process I/O events
  4. Check — setImmediate callbacks
  5. Close callbacks — e.g. socket close events

Microtasks Run Between Everything

After each callback, Node drains microtask queues:

  • process.nextTick queue first
  • Then promise callbacks (.then, await continuations)
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
Promise.resolve().then(() => console.log('promise'));
process.nextTick(() => console.log('nextTick'));
console.log('sync');
// sync, nextTick, promise, then timeout/immediate (order of these two can vary in the main module)

The libuv Thread Pool

Some operations (file system, DNS lookup, crypto, zlib) use a background thread pool (default 4 threads). Heavy use can queue up — adjust UV_THREADPOOL_SIZE if needed.

Blocking the Loop

CPU-heavy synchronous code blocks every request:

  • Large JSON.parse / JSON.stringify
  • Complex regex on user input
  • Synchronous crypto or compression
  • Big loops over arrays

Solutions: worker threads, streaming, chunking work, or moving it to another service.

Measuring

import { monitorEventLoopDelay } from 'node:perf_hooks';
const h = monitorEventLoopDelay();
h.enable();
setInterval(() => console.log('p99 lag ms', h.percentile(99) / 1e6), 5000);

Keep the event loop free, and Node.js scales beautifully. Block it, and everything waits.

Arivanandhan Chitheshwaran