How Node.js Works Under the Hood: V8, libuv and the Event Loop
/ Node.js / 11 min read

JavaScript was born in the browser, so how does it read files and serve HTTP on a server? A deep walk through V8, C++ bindings, libuv, the event loop phases and the thread pool, with examples you can run.
I have been writing Node.js backends for over three years, and the question I get most from junior developers is simple: JavaScript was built for the browser, so how does it talk to files, sockets and the operating system on a server? The honest answer takes more than a paragraph. This guide walks through the whole machine, from the moment you type `node app.js` to the moment a callback fires, and finishes with the practical rules that follow from it.
What Node.js actually is
Node.js is not a programming language and it is not a framework. It is a JavaScript runtime: a program that embeds a JavaScript engine and surrounds it with the capabilities the engine does not have on its own, such as file access, networking, timers, child processes and a module system. The language you write is the same JavaScript you know from the browser. What changes is the environment. There is no `window` or `document`, but there is `process`, `Buffer` and a rich standard library.
Why browsers could not do this
Browsers deliberately stop web pages from touching the file system or opening raw sockets. That is a security feature, and it is why backends were historically written in Java, PHP or Python. In 2009 Ryan Dahl's idea was to take the engine that already powered Chrome and give it those missing powers, with an architecture built around non-blocking I/O. That is Node.js.
The three pieces
Node.js is best understood as three cooperating components. V8 executes your JavaScript. C++ bindings connect JavaScript to native code. libuv provides the event loop and handles asynchronous work. Everything else, including `fs`, `http`, `crypto`, `stream` and the rest of the core modules, is built from those three.
V8: the engine that runs your code
V8 is Google's open-source JavaScript and WebAssembly engine, written in C++. When it receives your source code, it first parses it into an abstract syntax tree. That tree is handed to Ignition, V8's interpreter, which generates compact bytecode and starts running it immediately. Starting fast matters, because most code runs only once.
While your program runs, V8 watches which functions are hot, meaning called often or looping heavily. Those get compiled to optimised machine code by TurboFan, the optimising compiler. Recent V8 versions also add intermediate tiers (Sparkplug and Maglev) so that code can be sped up in stages rather than in one big jump. This approach is called just-in-time compilation, and it is the reason a long-running Node.js server tends to get faster after warm-up.
TurboFan makes assumptions, and two matter for everyday code. V8 tracks the internal shape (a hidden class) of every object, and uses inline caches to make property access cheap when objects of the same shape keep passing through the same code. If you build objects with the same properties in the same order, V8 can optimise them well. If one function sees many different shapes, or a variable switches between numbers and strings, V8 has to throw its optimised code away (a deoptimisation) and fall back to slower paths.
// Consistent shapes: V8 can optimise property access
const a = { id: 1, name: 'Asha' };
const b = { id: 2, name: 'Ravi' };
// Different property order creates a different shape
const c = { name: 'Mei', id: 3 };V8 also owns memory management. Objects live on the heap, and function calls live on the call stack. Garbage collection is generational: new objects go to a small young generation that is collected very often and very quickly (a scavenge), and objects that survive are promoted to the old generation, which is collected less often with a mark-sweep-compact approach that runs largely in parallel and in small increments to avoid long pauses. The heap has a size limit that depends on the machine, and you can raise it with the `--max-old-space-size` flag, but if a server needs that, the real fix is usually to find the leak.
What V8 cannot do is anything outside JavaScript. It has no concept of a file, a socket or a clock. That is exactly the gap the next two pieces fill.
C++ bindings: the translator
When you call `fs.readFile`, you start in a JavaScript function that Node ships as part of its standard library. A few layers down, that function crosses into C++ through bindings. The bindings convert JavaScript values such as strings, buffers and callbacks into native types, call the right native function, and convert results back. Think of them as a translator sitting between two people who speak different languages.
The same mechanism is open to you. Native addons, written against Node-API (formerly N-API), let you ship compiled C or C++ code as a module. Libraries such as `bcrypt` and image processors use it to get native speed while still looking like normal `require` calls.
libuv: what makes Node non-blocking
libuv is a cross-platform C library, originally written for Node.js, that gives Node its event loop, its thread pool and a consistent way to talk to Windows, Linux and macOS. Your JavaScript runs on a single main thread. If every slow operation blocked that thread, a server could only handle one request at a time. libuv avoids this by taking slow work somewhere else and telling Node when it is finished.
There are two ways it does that. For network sockets it relies on the operating system's own readiness notifications (epoll on Linux, kqueue on macOS, IOCP on Windows), which let one thread watch thousands of connections cheaply. For things the operating system cannot do asynchronously in a uniform way, it uses a pool of worker threads.
The thread pool
The pool defaults to four threads. It is used for most file system operations, `dns.lookup`, several `crypto` functions such as `pbkdf2`, `scrypt` and `randomBytes`, and `zlib` compression. You can raise the size with the `UV_THREADPOOL_SIZE` environment variable before the process starts. A common misconception is worth correcting: network I/O does not use the thread pool. That is why a single Node process can hold a huge number of idle connections, but a handful of simultaneous password hashes can queue up behind each other.
const crypto = require('crypto');
const start = Date.now();
for (let i = 1; i <= 6; i++) {
crypto.pbkdf2('password', 'salt', 200000, 64, 'sha512', () => {
console.log(`hash ${i}: ${Date.now() - start}ms`);
});
}
// With the default pool of 4, hashes 1-4 finish together,
// then 5 and 6 finish roughly one batch later.Following one readFile call end to end
const fs = require('fs');
fs.readFile('data.txt', 'utf8', (err, text) => {
console.log('file ready:', text.length);
});
console.log('this prints first');Here is what happens. V8 runs the call and finds a native-backed function. The C++ binding translates the arguments and asks libuv to read the file. libuv gives the job to a thread-pool thread, and the main thread carries on, so the second line prints immediately. When the operating system finishes the read, libuv puts the callback in a queue. The event loop notices the call stack is empty, moves the callback onto it, and V8 executes it. One request, three components, two threads, no blocking.
The event loop, phase by phase
Introductory diagrams show a single callback queue, but the real loop runs in a fixed order of phases. Each phase has its own queue of callbacks, and the loop drains it before moving on.
The timers phase runs callbacks from `setTimeout` and `setInterval` whose time has elapsed. The pending callbacks phase handles certain deferred system-level callbacks. An internal idle and prepare phase follows. The poll phase is the heart of the loop: it retrieves new I/O events, runs their callbacks, and, if nothing else is scheduled, waits there for work to arrive. The check phase runs `setImmediate` callbacks. Finally the close callbacks phase handles things like a socket's `close` event. Then the loop starts again, for as long as there is something left to do.
Microtasks and process.nextTick
Between every callback, Node drains two more queues before the loop continues. `process.nextTick` callbacks run first, then the Promise microtask queue (`then`, `catch`, `await` continuations). They are not part of the phases at all, which explains the ordering in this classic puzzle.
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 and immediateThe last two are worth a note. From the main module, the order of `setTimeout(fn, 0)` and `setImmediate(fn)` depends on how quickly the process starts and is not guaranteed. Inside an I/O callback, `setImmediate` always runs first, because the loop is already past the timers phase and heads straight to check. Also be careful with `nextTick`: because it runs before the loop can continue, a function that keeps scheduling itself with it will starve I/O completely.
Blocking the event loop
Everything above leads to the single most important rule in Node.js: do not block the main thread. While your JavaScript is running a long synchronous task, no other request is served, no timer fires and no callback runs.
app.get('/report', (req, res) => {
let total = 0;
for (let i = 0; i < 5e9; i++) total += i; // blocks everyone
res.json({ total });
});Typical culprits are large `JSON.parse` calls, complex regular expressions with catastrophic backtracking, synchronous APIs such as `fs.readFileSync` inside request handlers, image or PDF processing, and heavy loops over big arrays. The fixes depend on the job. Use the asynchronous API instead of the `Sync` one. Move CPU-heavy work to a worker thread with `worker_threads`. Push long jobs onto a queue such as RabbitMQ and process them in a separate service. Use the `cluster` module or a process manager to run one process per CPU core, so that one busy process does not stop the others.
Streams and backpressure
Reading a large file with `readFile` loads the entire thing into memory, which is fine for configuration and a problem for a one-gigabyte export. Streams process data in chunks, and backpressure makes a fast producer wait for a slow consumer so memory stays flat. The `pipeline` helper wires streams together and handles errors and cleanup for you.
const { pipeline } = require('stream/promises');
const fs = require('fs');
const zlib = require('zlib');
await pipeline(
fs.createReadStream('big-export.csv'),
zlib.createGzip(),
fs.createWriteStream('big-export.csv.gz')
);A debugging checklist I actually use
When a Node.js service feels slow, I ask three questions in order. First, is the main thread busy? A CPU profile or the `--cpu-prof` flag will show a long synchronous function straight away. Second, is the thread pool saturated? Lots of simultaneous file, DNS or hashing work can queue behind four threads, and raising `UV_THREADPOOL_SIZE` or moving the work out can help. Third, is the slowness outside Node entirely, such as a database query, a third-party API or the network? Measuring event loop delay and tracing outgoing calls usually settles it.
Common questions
Is Node.js single-threaded? Your JavaScript runs on one main thread, but the runtime is not: libuv's pool, V8's garbage collector and worker threads all use additional threads. Is Node.js good for CPU-heavy work? Not on the main thread. It excels at I/O-heavy workloads such as APIs, real-time dashboards, chat and streaming, and it can handle CPU work well when you move that work to workers or separate services. Does `async/await` create threads? No. It is syntax over Promises, and the work after an `await` resumes as a microtask on the same main thread.
Putting it together
V8 executes and optimises your JavaScript. C++ bindings translate between JavaScript and native code. libuv runs the event loop, waits on the operating system and farms slow work out to a small thread pool. Once you can picture those three working together, a lot of Node.js behaviour stops being surprising: why callbacks run when they do, why a heavy loop freezes the whole server, and why one process can serve thousands of connections.
This post was inspired by Chirag Jaipal's introductory article "How Node.js Works Under the Hood" on Hashnode (https://chiragjaipal.hashnode.dev/how-nodejs-works-under-the-hood), which is a great starting point. I expanded it with the event loop phases, microtasks, thread-pool behaviour and the practical rules I rely on in production.
- how Node.js works
- Node.js internals
- Node.js architecture
- Node.js event loop
- event loop phases
- libuv
- V8 engine
- Node.js thread pool
- non-blocking I/O
- asynchronous JavaScript
- process.nextTick vs setImmediate
- Node.js interview questions
- Node.js developer Kochi
- Arun Muraleedharan