Node.js

On this page 7

Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript outside the browser, most often on servers. In web architecture, it is a common foundation for the backend layer: HTTP APIs, real-time services, server-side rendering and build tooling for the frontend.

Node.js combines Google’s V8 JavaScript engine with the libuv library, which provides an event loop and asynchronous I/O. This design lets a single process serve thousands of concurrent connections without creating one thread per request, which made Node.js central to the full stack JavaScript model on the Web.

How the Node.js event loop handles requests

Node.js runs application JavaScript on a single main thread driven by an event loop. When code starts a network request, a file read or a database query, the runtime hands the operation to the operating system or to a background thread pool, registers a callback and immediately continues with other work.

When the operation completes, its callback or resolved Promise is queued and executed on a later loop iteration. This non-blocking I/O model is efficient for workloads dominated by waiting on networks and disks, because the thread never sits idle while a response travels across the network.

The event loop proceeds through ordered phases, and knowing them explains subtle timing behavior. The table summarizes the main phases in the order libuv processes them.

PhaseWhat runs thereExample
TimersExpired setTimeout and setInterval callbacksA retry after 500 ms
Pending callbacksDeferred system I/O callbacksCertain TCP error reports
PollNew I/O events and their callbacksAn incoming HTTP request
ChecksetImmediate callbacksWork scheduled after I/O
Close callbacksCleanup of closed handlesA socket close event
Main phases of the Node.js event loop

Between callbacks, Node.js drains the microtask queues, which hold resolved Promises and process.nextTick() callbacks. Overusing nextTick can therefore starve the event loop, delaying I/O indefinitely.

Core components of the runtime

Node.js is more than V8 with a loop; it is a layered runtime whose parts each solve a specific problem. The components below appear in nearly every production deployment.

ComponentFunctionPractical relevance
V8 engineCompiles JavaScript to machine codeExecution speed, memory limits
libuvEvent loop, thread pool, async I/OConcurrency and portability
Core moduleshttp, fs, crypto, stream, worker_threadsStandard server capabilities
npmPackage manager and registry clientAccess to a very large ecosystem
Module systemsCommonJS and ECMAScript modulesHow code is imported and bundled
Building blocks of a Node.js installation

The libuv thread pool has a default size of four threads, configurable through the UV_THREADPOOL_SIZE environment variable. File system calls, DNS lookups and some cryptographic operations use this pool, so a busy application can see unexpected queuing if the pool is too small.

Node.js follows a predictable release schedule: even-numbered major versions become Long-Term Support (LTS) releases with roughly 30 months of maintenance, which is why production teams generally run only LTS lines.

Node.js within common web architectures

Node.js appears in several architectural roles, sometimes simultaneously within one system. It powers the server tier of the MERN stack (MongoDB, Express, React, Node.js) and is the usual engine behind backend for frontend services that tailor APIs to a specific client.

RoleWhat Node.js doesTypical tools
API serverServes REST or GraphQL endpointsExpress, Fastify, NestJS
Server-side renderingRenders HTML for React or Vue pagesNext.js, Nuxt
Real-time serviceMaintains WebSocket connectionsSocket.IO, ws
Build toolingBundles and transpiles frontend codeVite, webpack, esbuild
Serverless functionRuns short event-driven handlersCloud function platforms
Roles Node.js plays in modern systems

Compared with the classic LAMP stack, where PHP typically handles each request in an isolated worker, Node.js keeps a long-running process with shared in-memory state. This enables connection pooling and fast responses but also means a single memory leak affects every request the process serves.

When Node.js fits and when it does not

Node.js excels at I/O-bound workloads and struggles with long CPU-bound computation on the main thread. The decision table summarizes typical situations.

WorkloadFitReason
JSON APIs and gatewaysStrongMostly waiting on databases and services
Chat and live updatesStrongMany idle connections cost little
Streaming file uploadsStrongStreams process data in chunks
Image or video encodingWeak on main threadBlocks the event loop
Heavy numeric analysisWeakBetter served by specialized runtimes
Suitability of Node.js for typical workloads

CPU-heavy tasks can still run in Node.js through worker_threads, child processes or native add-ons, but they add complexity. To use multiple cores for request handling, teams run one process per core using the cluster module, a process manager or container orchestration, in line with twelve-factor app principles of stateless, horizontally scaled processes.

Common mistakes and operational risks

Most production incidents with Node.js stem from a small set of recurring errors. Experienced teams guard against them with code review rules, monitoring and dependency policies.

  • Blocking the event loop with synchronous calls such as fs.readFileSync or large JSON.parse operations inside request handlers.
  • Unhandled Promise rejections, which terminate the process by default in current versions.
  • Dependency sprawl: hundreds of transitive npm packages enlarge the supply-chain attack surface.
  • Memory leaks from growing caches or forgotten event listeners in long-lived processes.
  • Running a non-LTS version in production, which shortens the security support window.

Monitoring event loop lag, heap usage and garbage collection pauses gives early warning. A sustained loop delay above roughly 100 milliseconds usually signals that some code is blocking the main thread.

A non-technical view

Picture a restaurant with one very fast waiter. The waiter takes an order, passes it to the kitchen and moves on to the next table. Nobody stands still waiting for food to cook.

Node.js works the same way for websites. It takes many requests, hands slow jobs to helpers and returns each answer when it is ready. That is why one small server can handle many visitors. The catch is simple: if the waiter starts cooking a long meal personally, every other table waits.

A concrete example

A regional ticketing company sells seats for concerts and needs a live seat map that updates for every visitor when someone reserves a seat. The team builds the backend in Node.js with Fastify for the REST API and the ws library for WebSocket connections, running on an LTS release.

During a popular on-sale event, about 20,000 browsers stay connected at once. Each reservation writes to the database and then broadcasts a small message to all connected clients. Four Node.js processes, one per CPU core behind a load balancer, keep median API response times near 40 milliseconds. PDF ticket generation, which is CPU-heavy, runs in a separate worker queue so it never blocks the event loop. The result is a responsive sale with no double-booked seats.