Most tutorials explain the runtime with tiny scripts. A timer here, a file read there. That helps for learning, but real services also have routes, a database, failing requests and deployments. This guide follows a production-style API so you can see how Node.js works internally in code you might actually ship.
You will see where the V8 engine runs your code, where libuv takes over, and how the Node.js event loop keeps one thread busy with useful work. You will also see where a normal service goes wrong and how to fix it.
If you need help building a service like this, my backend development services cover APIs, databases and background jobs. Now, let's start with what happens at startup.
What Actually Runs When Your Server Starts
Before a single request arrives, Node.js does a fixed set of steps. Knowing them helps you debug slow starts and strange crashes.
Node.js Runtime Startup in Plain Steps
These steps show the order in which the runtime prepares itself before your first route can answer a user.
- The Node.js binary starts and creates a V8 instance.
- Node.js sets up libuv and creates the main event loop.
- Core modules such as http, fs and net become available.
- Your entry file runs from top to bottom as normal synchronous code.
- Calls like app.listen() register a socket with libuv and return at once.
- The event loop starts and waits for events.
Step 4 matters most. Everything at the top level of your file blocks the loop. That is fine at boot. It is a problem inside a request.
Where the V8 Engine Fits in Your Code
V8 compiles and runs JavaScript. It does not know about sockets, files or timers. When your route handler runs, V8 executes it on the call stack. When the handler calls pool.query(), V8 passes that work to Node.js bindings and moves on.
This split is the heart of the Node.js architecture. V8 is fast at running code. Libuv is good at waiting. Each does its own job, and the event loop connects them.
How Non-Blocking I/O Works With a Database Call
A database call is the most common slow step in a backend. It is also the best way to see non-blocking I/O in action.
Following a PostgreSQL Query Through libuv
Say a user asks for their profile. Your handler calls the pg driver. The driver writes the SQL to a TCP socket and returns a promise. Libuv asks the operating system to tell it when the database replies. Your JavaScript thread is now free to handle other requests.
When the reply arrives, libuv notices it in the poll phase. It queues the callback, the promise resolves, and V8 continues your handler. No thread sat waiting. The thread was never blocked, so one process can keep many queries in flight at once.
Connection Pool Limits and the Thread Pool Are Different
Developers often mix up two separate limits. The libuv thread pool has four threads by default, and it serves tasks such as file reads, some crypto work and dns.lookup. A PostgreSQL socket usually does not use it. The database connection pool is a different limit, set in your driver.
// db.js
const { Pool } = require('pg');
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 10,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
});
module.exports = pool;
Here, max: 10 means ten queries can run at once. The eleventh waits for a free connection. This is queueing at the database level, not inside libuv. Setting a connection timeout also means a slow database fails fast instead of piling up requests.
A Folder Structure That Respects the Event Loop
A clear structure keeps slow work out of the wrong place. This layout is simple and works well for mid-sized Express.js services.
These folders separate each concern so that blocking code is easy to spot during review.
- routes/ holds URL definitions only.
- controllers/ reads input and sends the response.
- services/ holds business logic and database calls.
- middleware/ holds shared logic such as error handling and auth.
- workers/ holds CPU-heavy tasks that run in worker threads.
Here is a service function that keeps SQL out of the route and uses a parameterized query.
// services/userService.js
const pool = require('../db');
async function getUserById(id) {
const { rows } = await pool.query(
'SELECT id, name, email FROM users WHERE id=$1',
[id]
);
return rows[0] || null;
}
module.exports = { getUserById };
Parameterized queries also protect you from SQL injection, which is a basic production rule.
Error Handling in an Async Node.js Service
Async code fails in ways that synchronous code does not. A thrown error inside a callback cannot be caught by a try block outside it. Planning for this early saves many late-night fixes.
Handling Rejected Promises in Express.js Routes
Express 5 passes rejected promises from async handlers to your error middleware. In Express 4 you need a wrapper or a library to get the same result. With Express 5, the route stays clean.
// routes/users.js
router.get('/users/:id', async (req, res) => {
const user = await getUserById(req.params.id);
if (!user) {
const err = new Error('User not found');
err.status = 404;
throw err;
}
res.json(user);
});
// middleware/errorHandler.js
function errorHandler(err, req, res, next) {
const status = err.status || 500;
console.error({ message: err.message, path: req.path, status });
res.status(status).json({
error: status === 500 ? 'Something went wrong' : err.message,
});
}
Notice that the 500 response hides the real message. Users should never see database details. Your logs should.
Process-Level Safety Nets
Some errors escape every handler. Log them and let the process restart under a manager. Do not keep running in an unknown state.
process.on('unhandledRejection', (reason) => {
console.error('Unhandled rejection:', reason);
process.exit(1);
});
process.on('uncaughtException', (err) => {
console.error('Uncaught exception:', err);
process.exit(1);
});
This only works well if something restarts the app, such as Docker, systemd or PM2.
Production Readiness Checklist for Node.js Event Loop Health
A service can pass every test and still fail under real traffic. These checks protect the event loop and the database in production.
Use this list as a quick review before each release.
- Add a /health route that runs a light query such as SELECT 1.
- Set timeouts on every outgoing HTTP call and database query.
- Stream large files instead of reading them fully into memory.
- Move CPU-heavy work, such as image resizing, to worker threads or a queue.
- Track event loop delay with perf_hooks.monitorEventLoopDelay().
- Use structured JSON logs so you can search them later.
- Run several processes with a process manager or container replicas to use all CPU cores.
Graceful shutdown is the item people forget most. When a deploy sends a stop signal, finish current requests first and then close the pool.
const server = app.listen(3000);
process.on('SIGTERM', () => {
server.close(async () => {
await pool.end();
process.exit(0);
});
});
The server.close() call stops new connections and waits for active ones. Then pool.end() closes database connections cleanly. Without this, a deploy can cut users off mid-request.
Putting the Node.js Runtime to Work
Learning how Node.js works internally pays off in daily work. V8 runs your code, libuv handles waiting, and the event loop decides what comes next. When you keep handlers short, size your pools with real numbers and plan for failure, the runtime does the rest.
The next time an endpoint feels slow, ask three questions. Is something blocking the thread? Is a pool full? Is an error being swallowed? Most Node.js problems start with one of these.
Source : https://jaypateldev.com/blog/how-node-js-works-internally/
Top comments (0)