Node.js · JavaScript · Backend · Performance

The Node.js Event Loop Explained with Examples

The phases of the Node.js event loop, microtasks versus macrotasks, process.nextTick and setImmediate, and how to find code that blocks the loop.

Sander Yazıcıoğlu Published: 2 min read Türkçe oku

The Node.js Event Loop Explained with Examples

Node.js runs JavaScript on a single thread yet handles thousands of concurrent connections. The secret is the event loop. Beyond being a classic interview question, understanding it is also the answer to "why did the server suddenly slow down?" in production.

The core idea

Node.js hands slow work such as file reads, network requests and timers to the operating system or libuv's thread pool. When that work finishes, its callback goes into a queue. The event loop drains these queues in order and runs your JavaScript. While your JavaScript runs, no other callback can run.

The phases

Each turn of the loop goes through these phases:

PhaseWhat runs
timersExpired setTimeout and setInterval callbacks
pending callbacksDeferred callbacks for some system errors
pollI/O events (network, files); waits here if nothing is pending
checksetImmediate callbacks
close callbacksClose events such as socket.on('close')

Between phases, and after every callback, the microtask queues are drained.

Microtasks and macrotasks

setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
Promise.resolve().then(() => console.log('promise'));
process.nextTick(() => console.log('nextTick'));
console.log('sync');

Output:

sync
nextTick
promise
timeout
immediate
  • Synchronous code finishes first.
  • The process.nextTick queue drains even before the promise queue.
  • Then promise callbacks (microtasks) run.
  • The order of setTimeout(0) and setImmediate isn't guaranteed in the main module, but inside an I/O callback setImmediate always runs first.

Blocking the loop

If a request runs a synchronous loop that takes 200 ms, every user on the server waits those 200 ms. Usual suspects:

  • JSON.parse / JSON.stringify on large payloads.
  • Synchronous APIs such as fs.readFileSync.
  • Complex regular expressions (especially patterns with catastrophic backtracking).
  • CPU-heavy work: hashing, compression, image processing.

Detecting it

Node.js ships a built-in tool for measuring loop delay:

import { monitorEventLoopDelay } from 'node:perf_hooks';

const histogram = monitorEventLoopDelay({ resolution: 20 });
histogram.enable();

setInterval(() => {
  console.log('p99 loop delay (ms):', histogram.percentile(99) / 1e6);
  histogram.reset();
}, 10000);

If p99 delay regularly exceeds tens of milliseconds, something is blocking. Profile with node --cpu-prof to see which function burns the time.

Fixes

  • Use async APIs: fs.promises, streams.
  • Chunk big work: split the loop and yield with setImmediate between chunks.
  • Move CPU-heavy work out: worker threads or a separate service or queue.
  • Stream large data: process a file or HTTP body piece by piece instead of loading it all into memory.

Why it matters for realtime systems

In WebSocket servers loop delay hits users directly: messages go out late, heartbeats are missed and connections drop. Add loop delay to the metrics described in realtime systems with Node.js and WebSocket.

Conclusion

Understanding the event loop is the foundation of fast Node.js code: keep synchronous work short, know the microtask order, measure the delay, and move CPU-heavy work off the main thread.

All articles →