Polski

Tutorial · Node.js internals · Node.js

Node.js under the hood – the event loop, microtasks, streams, worker threads and memory leaks

How Node.js 24 really works: V8, libuv and the thread pool, the event loop phases, process.nextTick vs Promise (and why the order differs in ESM), blocking the loop and how to measure it, streams with backpressure, worker threads vs cluster, and finding memory leaks and profiling – with real run outputs.

By · · 18 min read

"Node.js is single-threaded" is only half true. Your JavaScript runs on one thread, but underneath there is the libuv thread pool, the operating system's asynchronous I/O and the V8 garbage collector. Once you understand how these parts cooperate, you stop being surprised that a single JSON.parse of a big file stalls every HTTP request, or that a CSV export eats 700 MB of memory. In this tutorial you will verify every claim with working code – the outputs in the "Output" blocks come from real runs on Node.js 24.

Prerequisites: Node.js 24 LTS or newer (26 LTS works too), a good grasp of async/await and Promises, TypeScript basics. The Express or NestJS tutorial helps.

765 → 1.5 ms
loop delay (p99) – report on the main thread vs in workers
402 → 99 MB
peak RSS – `readFile` vs a stream for a 79 MB CSV
4
libuv pool threads – by default (`UV_THREADPOOL_SIZE`)
6
event loop phases – timers, pending, idle/prepare, poll, check, close

What Node.js is made of

Diagram: JavaScript code, V8, libuv and the operating system

Networking does not use the thread pool – the operating system handles sockets and libuv gets notified when data is ready. The pool (4 threads, UV_THREADPOOL_SIZE) handles operations without a good asynchronous OS API: most of fs, dns.lookup, asynchronous crypto (e.g. scrypt) and zlib. If a server hashes dozens of passwords while reading files, those operations queue up for the same four threads.

The event loop phases

Diagram: One iteration of the libuv event loop; after every callback: nextTick, then microtasks

In each phase the loop runs the callbacks queued for that phase. Since Node 11 the nextTick and microtask queues are drained after every single callback (just like in browsers), not only after the whole phase. Let's check it in code.

Step 1. The project

package.json and tsconfig.json

package.json
{
  "name": "pierogi-node-runtime",
  "private": true,
  "version": "1.0.0",
  "type": "module",
  "engines": { "node": ">=24" },
  "scripts": {
    "order": "node src/01-order.ts && node src/01-order.cjs",
    "blocking": "node src/02-blocking.ts",
    "data": "node src/make-orders-csv.ts",
    "streams": "node src/03-streams.ts naive && node src/03-streams.ts stream",
    "backpressure": "node src/04-backpressure.ts ignore && node src/04-backpressure.ts respect",
    "cluster": "node src/05-cluster.ts",
    "leak": "node --expose-gc src/06-leak.ts leak && node --expose-gc src/06-leak.ts fixed",
    "typecheck": "tsc --noEmit"
  },
  "devDependencies": {
    "@types/node": "^24.19.4",
    "typescript": "~7.0.2"
  }
}
tsconfig.json
{
  "compilerOptions": {
    "target": "es2024",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "types": ["node"],
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "erasableSyntaxOnly": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*.ts"]
}

erasableSyntaxOnly makes sure you only use TypeScript syntax that Node can simply strip (no enum, no constructor parameter properties). That is why node src/file.ts works without a build step, and tsc --noEmit only checks types.

Step 2. Execution order: nextTick, Promise, setTimeout, setImmediate

Start in the browser. The example prints the order of synchronous code, microtasks and macrotasks. The second button blocks the main thread for 500 ms – see when setTimeout(…, 0) actually runs.

Microtasks vs macrotasks in the browser – Order: synchronous code, Promise and queueMicrotask, MessageChannel and setTimeout, requestAnimationFrame; blocking the thread for 500 ms delays the timer

/index.js
import "./styles.css";

const app = document.getElementById("app");
app.innerHTML = `
  <div class="bar">
    <button id="run">Run again</button>
    <button id="block">Block the main thread for 500 ms</button>
  </div>
  <ol id="log"></ol>`;
const list = document.getElementById("log");

function log(label, kind) {
  console.log(`[${kind}] ${label}`);
  const li = document.createElement("li");
  li.innerHTML = `<span class="tag ${kind}">${kind}</span> ${label}`;
  list.append(li);
}

function runOrderDemo() {
  list.innerHTML = "";
  log("script start", "sync");

  setTimeout(() => log("setTimeout(…, 0)", "macrotask"), 0);

  const channel = new MessageChannel();
  channel.port1.onmessage = () => log("MessageChannel message", "macrotask");
  channel.port2.postMessage(null);

  Promise.resolve().then(() => {
    log("promise.then #1", "microtask");
    // A microtask queued by a microtask still runs before any macrotask.
    Promise.resolve().then(() => log("promise.then queued inside a microtask", "microtask"));
  });

  queueMicrotask(() => log("queueMicrotask", "microtask"));

  (async () => {
    log("async function: code before the first await", "sync");
    await null;
    log("async function: code after await", "microtask");
  })();

  requestAnimationFrame(() => log("requestAnimationFrame (before the next paint)", "render"));

  log("script end", "sync");
}

document.getElementById("run").onclick = runOrderDemo;

document.getElementById("block").onclick = () => {
  list.innerHTML = "";
  const scheduledAt = performance.now();
  setTimeout(() => log(`setTimeout(…, 0) ran after ${Math.round(performance.now() - scheduledAt)} ms`, "macrotask"), 0);
  const end = performance.now() + 500;
  while (performance.now() < end) {
    // busy loop: no clicks, no painting, no timers until it finishes
  }
  log("500 ms of synchronous work finished", "sync");
};

runOrderDemo();
/styles.css
body { font-family: system-ui, sans-serif; margin: 0; padding: 12px; color: #1f2328; }
.bar { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 8px; }
button { padding: 6px 12px; cursor: pointer; }
ol { padding-left: 24px; margin: 0; }
li { padding: 3px 0; }
.tag { display: inline-block; min-width: 76px; font: 12px ui-monospace, monospace; padding: 1px 6px; border-radius: 4px; margin-right: 6px; text-align: center; }
.sync { background: #e7f5ff; }
.microtask { background: #d3f9d8; }
.macrotask { background: #fff3bf; }
.render { background: #f3d9fa; }

Microtasks always run before the next macrotask – including those queued by another microtask. The order of macrotasks among themselves (MessageChannel, setTimeout) and relative to requestAnimationFrame depends on the browser. Now the same in Node, with two queues the browser does not have: process.nextTick and setImmediate.

Callback order in ESM and CommonJS

src/01-order.ts
import { readFile } from "node:fs";

// Run: node src/01-order.ts   (and compare with the CommonJS variant 01-order.cjs)
const log = (msg: string) => console.log(msg);

log("1  sync: start");
setTimeout(() => log("   timers: setTimeout 0"), 0);
setImmediate(() => log("   check: setImmediate"));
Promise.resolve().then(() => log("   microtask: promise.then"));
queueMicrotask(() => log("   microtask: queueMicrotask"));
process.nextTick(() => log("   nextTick: process.nextTick"));
log("2  sync: end of script");

// Inside an I/O callback (poll phase) the order is deterministic:
// the check phase (setImmediate) comes right after poll, timers only in the next loop turn.
readFile(import.meta.filename, () => {
  setTimeout(() => log("   [I/O] timers: setTimeout 0"), 0);
  setImmediate(() => log("   [I/O] check: setImmediate"));
  process.nextTick(() => log("   [I/O] nextTick"));
});
src/01-order.cjs
// The same queues in a CommonJS module: run with `node src/01-order.cjs`.
const log = (msg) => console.log(msg);
log("1  sync: start");
setTimeout(() => log("   timers: setTimeout 0"), 0);
setImmediate(() => log("   check: setImmediate"));
Promise.resolve().then(() => log("   microtask: promise.then"));
queueMicrotask(() => log("   microtask: queueMicrotask"));
process.nextTick(() => log("   nextTick: process.nextTick"));
log("2  sync: end of script");
node src/01-order.ts, then node src/01-order.cjs
$ node src/01-order.ts
1  sync: start
2  sync: end of script
   microtask: promise.then
   microtask: queueMicrotask
   nextTick: process.nextTick
   check: setImmediate
   timers: setTimeout 0
   [I/O] nextTick
   [I/O] check: setImmediate
   [I/O] timers: setTimeout 0

$ node src/01-order.cjs
1  sync: start
2  sync: end of script
   nextTick: process.nextTick
   microtask: promise.then
   microtask: queueMicrotask
   check: setImmediate
   timers: setTimeout 0

Three observations interviewers like to ask about:

  1. In CommonJS nextTick beats Promise; in ESM it is the other way round. An ES module is evaluated asynchronously, inside a job that is itself handled as a microtask. So the microtask queue is drained before the nextTick queue. Don't write code that depends on this order.
  2. setTimeout(0) vs setImmediate in the main module is non-deterministic. In five ESM runs, setImmediate won four times and setTimeout once. It depends on how much time passed before the first loop iteration.
  3. Inside an I/O callback the order is guaranteed: after the poll phase comes check (setImmediate), and timers wait for the next iteration.

Step 3. Blocking the loop and worker threads

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Step 4. Streams and backpressure
  • Step 5. Memory leaks and profiling
  • Common mistakes
  • Check yourself
  • What next

Create a free account · Sign in