Node.js Event Loop & Architecture

Difficulty: Intermediate

Question

How does the Node.js event loop work, what are its phases, and how is it different from the browser event loop?

Answer

The Node.js event loop is a loop run by libuv on the main thread that repeatedly picks up completed I/O and timer events and runs their JavaScript callbacks, one at a time. Your JavaScript runs on a single thread, but the actual I/O (sockets, files, DNS, crypto) is done by the operating system or by libuv's thread pool, so one Node process can juggle thousands of concurrent connections without blocking.

The six phases of one loop iteration

Each pass through the loop (a "tick") visits these phases in order, and each phase has its own FIFO queue of callbacks:

  1. Timers: runs callbacks from setTimeout and setInterval whose threshold has passed.
  2. Pending callbacks: some system-level I/O callbacks deferred from the previous iteration (for example certain TCP errors).
  3. Idle / prepare: internal to libuv.
  4. Poll: fetches new I/O events and runs their callbacks (a socket received data, a file read finished). If nothing else is scheduled, the loop waits here for I/O.
  5. Check: runs setImmediate callbacks, right after poll.
  6. Close callbacks: runs things like socket.on('close').

Between every individual callback, Node drains the microtask queues: first the process.nextTick queue, then the Promise queue (.then, await continuations, queueMicrotask). That is why a resolved Promise always runs before the next timer, and why a recursive process.nextTick can starve the loop completely.

Since Node 20 (libuv 1.45), timers are checked only after the poll phase rather than both before and after it. This rarely changes application code, but it is why old blog posts sometimes describe slightly different ordering.

What actually runs off the main thread

Node vs browser event loop

AspectNode.jsBrowser
Implemented bylibuvThe browser (per HTML spec)
Macrotask structureSix named phasesTask queues chosen by the browser
Extra queuesprocess.nextTick, setImmediaterequestAnimationFrame, rendering steps
RenderingNonePaint can happen between tasks
MicrotasksDrained between each callbackDrained after each task

The big practical difference: browsers interleave rendering with tasks, so a long task causes visible jank. Node has no rendering, so a long task instead causes latency spikes and timeouts for every concurrent request.

Common gotchas

One iteration of the Node.js event loop. Microtasks (nextTick, then Promises) are drained between every callback in every phase.
  1. Timers: Expired setTimeout and setInterval callbacks run.
  2. Pending callbacks: Deferred system I/O callbacks from the last tick.
  3. Idle / prepare: Internal libuv housekeeping.
  4. Poll: Collect new I/O events and run their callbacks; wait here if idle.
  5. Check: setImmediate callbacks run.
  6. Close callbacks: Handlers such as socket.on('close') run.

Code examples

Predicting the event loop order

// order.cjs  (run with: node order.cjs)
const fs = require('node:fs');

console.log('1: sync');
setTimeout(() => console.log('timeout (main)'), 0);
setImmediate(() => console.log('immediate (main)'));
process.nextTick(() => console.log('2: nextTick'));
Promise.resolve().then(() => console.log('3: promise'));
console.log('1b: sync');

// Inside an I/O callback the order IS deterministic
fs.readFile(__filename, () => {
  setTimeout(() => console.log('5: timeout (in I/O)'), 0);
  setImmediate(() => console.log('4: immediate (in I/O)'));
});

Synchronous code runs first, then the nextTick queue, then Promise microtasks. Inside an I/O callback the check phase comes before the next timers phase, so setImmediate reliably beats setTimeout there.

Blocking the Event Loop (Anti-Pattern)

const express = require('express');
const app = express();

// BAD: blocks the event loop for ALL users
app.get('/hash', (req, res) => {
  const crypto = require('crypto');
  // This takes ~500ms and blocks everything
  const hash = crypto.pbkdf2Sync(
    'password', 'salt', 100000, 64, 'sha512'
  );
  res.json({ hash: hash.toString('hex') });
});

// GOOD: non-blocking with async version
app.get('/hash-async', async (req, res) => {
  const crypto = require('crypto');
  const hash = await new Promise((resolve, reject) => {
    crypto.pbkdf2(
      'password', 'salt', 100000, 64, 'sha512',
      (err, key) => err ? reject(err) : resolve(key)
    );
  });
  res.json({ hash: hash.toString('hex') });
});

A synchronous pbkdf2 with 100,000 iterations blocks the loop, so every other request waits. The async version runs on libuv's thread pool and the main thread keeps serving traffic.

Worker Threads for CPU-Intensive Work

// main.js
const { Worker } = require('worker_threads');

function runWorker(data) {
  return new Promise((resolve, reject) => {
    const worker = new Worker('./worker.js', {
      workerData: data,
    });
    worker.on('message', resolve);
    worker.on('error', reject);
  });
}

// worker.js
const { workerData, parentPort } = require('worker_threads');

// CPU-heavy computation runs in separate thread
function fibonacci(n) {
  if (n <= 1) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
}

const result = fibonacci(workerData);
parentPort.postMessage(result);

Worker threads run JavaScript on separate V8 isolates, so CPU-heavy work like this does not block the main event loop. Shown as two files; in practice reuse workers through a pool instead of creating one per request.

Key points

Common follow-up questions

Interview tips

Concepts covered

Event Loop, libuv, Microtask Queue, process.nextTick, setImmediate, Thread Pool

More Node.js Interview questions