Skip to the content

Lesson 189 of 296

Single thread, the event loop and libuv

What you will learn

  • What Node.js is (a short reminder)
  • What "single-threaded" means
  • How Node.js handles thousands of connections with one thread
  • libuv and the thread pool
  • The phases of the event loop
  • Microtasks, process.nextTick, setImmediate and setTimeout ordering
On this page

Node.js in one paragraph

Node.js is a runtime that runs JavaScript outside the browser, on servers and your computer (Lesson 26). It uses Google's V8 engine to execute JavaScript and adds APIs the browser does not have: files (fs), networking (http, net), processes, streams and more.

Single-threaded

A thread is one sequence of instructions the CPU executes. Your JavaScript in Node.js runs on one main thread: only one piece of your JavaScript runs at any moment.

So how can one thread serve thousands of users at the same time? Because most server work is waiting: for the database, for a file, for another API. Node.js does not sit and wait. It starts the operation, moves on to other work, and runs your callback when the result is ready. This is non-blocking I/O (I/O means input/output: network, disk).

A traditional thread-per-request server (classic Java or PHP setups) gives each request its own thread, which mostly waits. Threads cost memory, so Node.js's model handles many idle connections cheaply. The trade-off: one slow CPU-heavy task blocks everyone (Lesson 190).

libuv

libuv is a C library inside Node.js that provides the event loop and asynchronous I/O:

  • Network I/O uses the operating system's own non-blocking mechanisms (epoll on Linux, kqueue on macOS, IOCP on Windows). No extra threads are needed.
  • Operations the OS cannot do asynchronously go to libuv's thread pool (4 threads by default, changed with the UV_THREADPOOL_SIZE environment variable): file system operations, DNS lookups with dns.lookup, some crypto functions (such as pbkdf2 and scrypt) and zlib compression.

So "Node.js is single-threaded" means your JavaScript runs on one thread. Node.js itself uses several threads behind the scenes.

The event loop

The event loop (Lesson 76 covered the browser version) is the loop that keeps checking: "is any work ready? run its callback". In Node.js it goes through phases, each with its own queue:

PhaseRuns
timersCallbacks from setTimeout and setInterval whose time has passed
pending callbacksSome system-level callbacks deferred from the previous loop (for example certain TCP errors)
idle, prepareInternal use only
pollRetrieves new I/O events and runs their callbacks (incoming requests, data read); waits here if nothing else is scheduled
checkCallbacks from setImmediate
close callbacksclose events, such as socket.on("close")

Between every callback, Node.js empties two special queues first:

  1. The process.nextTick queue.
  2. The microtask queue: Promise callbacks (.then, code after await) and queueMicrotask.

A classic ordering question

Save this as order.cjs (a CommonJS file, the classic Node.js module format, Lesson 73) and run node order.cjs:

const { readFile } = require("node:fs");

const order = [];

console.log("1 sync start");
setTimeout(() => console.log("5 or 6: timeout"), 0);
setImmediate(() => console.log("5 or 6: immediate"));
Promise.resolve().then(() => console.log("4 promise"));
process.nextTick(() => console.log("3 nextTick"));
console.log("2 sync end");

readFile(__filename, () => {
  setTimeout(() => order.push("timeout"), 0);
  setImmediate(() => order.push("immediate"));
  setTimeout(() => console.log("inside I/O callback:", order.join(" then ")), 20);
});

Output (checked by running it several times):

1 sync start
2 sync end
3 nextTick
4 promise
5 or 6: timeout        (these two lines can swap
5 or 6: immediate       places between runs)
inside I/O callback: immediate then timeout

Why:

  1. All synchronous code runs first.
  2. Then the process.nextTick queue, then promise microtasks.
  3. setTimeout(..., 0) vs setImmediate from the main module: the order is not guaranteed. It depends on whether the timer's 1 ms minimum has passed when the loop starts. In testing for this lesson, three runs gave both orders.
  4. Inside an I/O callback, setImmediate always runs before setTimeout(..., 0), because after the poll phase comes the check phase, before the loop returns to timers.

Trick detail: run the same code as an ES module (order.mjs with import) and "4 promise" prints before "3 nextTick". The reason: Node.js evaluates an ES module inside a promise job, so the code is already running in the microtask phase, and new promise callbacks run before Node.js gets back to the nextTick queue. Only mention this if the interviewer goes deep, but it shows real understanding. In normal code, do not depend on the exact order between nextTick and promises.

FunctionRuns
process.nextTick(fn)Right after the current operation, before promises. Overusing it can starve I/O.
queueMicrotask(fn) / promisesAfter nextTick, before the next phase
setImmediate(fn)In the check phase of this loop iteration
setTimeout(fn, 0)In the timers phase, after at least 1 ms

How to say it in an interview

"Node.js runs JavaScript on one main thread with an event loop provided by libuv. Network I/O is non-blocking using the operating system's mechanisms, while file system work, DNS lookups and some crypto go to libuv's thread pool of four threads by default. The event loop cycles through timers, pending callbacks, poll, check and close phases, and between callbacks it drains the process.nextTick queue and then the promise microtask queue. So one thread can serve many concurrent connections because most work is waiting, but any CPU-heavy synchronous code blocks every request."

Key words

WordMeaning
ThreadOne sequence of instructions executed by the CPU
Non-blocking I/OStarting I/O and continuing other work until it finishes
libuvThe C library providing Node.js's event loop and async I/O
Thread poollibuv's worker threads for file, DNS and crypto work
Event loop phasestimers, pending, poll, check, close
process.nextTickRuns a callback before promise microtasks
setImmediateRuns a callback in the check phase

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.