skip to content

Reliability and Diagnostics

What happens to an error nobody caught, how to exit without dropping in-flight requests, and how to see inside a running process. Asked because swallow-it and restart-blindly lose data quietly.

on this pageshow

explore

questions

27

In Node.js, how does the error-first callback convention work, and what rules must a callback-style API and its caller follow?

level: juniorimportance: must knowfreq 70%

answer

  1. what the first parameter is for
  2. the value of err on success
  3. early return after handling
  4. called once, never synchronously
  5. try/catch cannot reach it

basics

~20 s

A Node.js callback API calls its last argument as callback(err, result): err is an Error on failure and null on success. The caller checks err first and returns; the API calls back exactly once, always asynchronously.

solid answer

~40 s

Node's callback APIs such as `fs.readFile` take a callback as the last argument and invoke it as `callback(err, value)`. On failure `err` is an `Error`, usually carrying a `code` such as `ENOENT`; on success it is `null` and the result follows. The caller tests `if (err)` first, handles it and returns, so the success path never runs with bad data. The API has two duties: call the callback exactly once, and never call it synchronously on some paths and asynchronously on others; the official event-loop guide defers early errors with `process.nextTick(callback, err)`. Because the result arrives after the calling function has returned, a `try/catch` around the call cannot see the I/O error, and anything the callback itself throws escapes as an uncaught exception rather than coming back as `err`.

code

javascript · 31 lines
javascript
import { readFile } from 'node:fs';

function loadManifest(path, callback) {
  if (typeof path !== 'string') {
    // Report early errors asynchronously so the API is never sync on one path.
    process.nextTick(callback, new TypeError('path must be a string'));
    return;
  }
  readFile(path, 'utf8', (err, text) => {
    if (err) {
      callback(err); // ENOENT, EACCES, ... passed up unchanged
      return;
    }
    let manifest;
    try {
      manifest = JSON.parse(text);
    } catch (parseErr) {
      callback(parseErr);
      return;
    }
    callback(null, manifest); // outside the try: a throwing caller cannot trigger a second call
  });
}

loadManifest('./manifest.json', (err, manifest) => {
  if (err) {
    console.error('manifest not loaded:', err.code ?? err.message);
    return;
  }
  console.log(Object.keys(manifest));
});

go deeper

for a junior

Recall the signature callback(err, value), that err is null on success, and the habit of checking err first and returning straight after handling it.

for a middle

Explain why try/catch around a callback call misses I/O errors, and the API author's duties: call back exactly once and never synchronously on some paths.

for a senior

Show the subtle bugs: a success callback invoked inside the API's own try, a cache hit that calls back synchronously, and errors flattened to strings that lose their code.

for a principal

Weigh where a codebase still exposes callback APIs, how its wrappers keep the contract, and whether new modules should offer promises only.

## The shape of the convention Node.js grew up on **callback APIs**: you pass a function as the **last argument**, and Node calls it when the work finishes. The **error-first** convention fixes the order of that function's parameters: `callback(err, value)`. - On **failure**, `err` is an `Error` object. For operating-system failures it carries a string `code` such as `ENOENT` or `EACCES`, plus fields like `syscall` and `path`. - On **success**, the first argument is `null` and the result, if there is one, comes second. - The caller therefore tests `if (err)` **before** touching the result, handles the failure and **returns**, so the success path never runs with missing data. The official Node.js guide to asynchronous callbacks states it plainly: the first parameter in any callback is the error object, and if there is no error it is `null`. ## Four ways a Node API reports an error The callback is only one of the channels. Node's errors documentation lists how each API style reports failure, and you have to know which one you are calling: | API style | Example | How the error reaches you | |---|---|---| | Synchronous | `fs.readFileSync` | `throw`, caught by `try...catch` | | Callback | `fs.readFile` | the `err` argument of the callback | | Promise | `fs/promises` `readFile` | a rejected promise, caught with `await` in `try` or `.catch()` | | Event emitter | a `net.Socket`, a stream | an `'error'` event; with no listener it is thrown and crashes the process | The docs also warn that a handful of normally asynchronous methods still throw, so the per-method documentation is the final word. ## Rules for the caller - **Check `err` first, then return.** Forgetting the `return` runs the success code with `undefined` data. - **Do not wrap the call in `try...catch` to catch I/O failures.** The `try` block has already exited by the time the callback runs, so only synchronous throws, such as argument validation, are caught there. - **Do not throw from inside the callback and expect it to come back as `err`.** A throw there unwinds into Node's internals and surfaces as an uncaught exception, which by default ends the process. - **Pass the error on unchanged** when you cannot handle it, so its `code` survives for whoever can. ## Rules for the API author 1. **Call the callback exactly once.** Success and failure are mutually exclusive. Node's internals use the code `ERR_MULTIPLE_CALLBACK`, "a callback was called more than once", for the same violation. 2. **Be consistently asynchronous.** An API that calls back synchronously on one path (a cache hit, an early validation failure) and asynchronously on another makes the caller's code run in an order that depends on the data. The Node.js event-loop guide shows the fix: report early errors with `process.nextTick(callback, err)`, so the callback runs after the caller's code but before the event loop moves on. 3. **Never call the success callback inside the `try` that guards your own work.** If the caller's callback throws, your `catch` receives the caller's exception and calls back a second time with it. Compute inside `try`, call back outside it. 4. **Pass an `Error`, not a string.** Callers read `err.code` and `err.stack`; a string has neither. ## Node core's own split Node core itself does not defer everything. Its callback APIs validate arguments **before** starting any work and **throw synchronously** on a programmer mistake: `fs.open({}, cb)` throws `TypeError [ERR_INVALID_ARG_TYPE]` at once. Operational failures that come from the operating system, such as a missing file, always arrive through the callback. So the guide's `nextTick` pattern is for errors your API chooses to report through the callback; argument checks that throw immediately are an equally valid, and common, design. ## Bridging the two styles Modern code mixes callbacks and promises. `util.promisify` turns an error-first function into one returning a promise, and `util.callbackify` goes the other way, delivering a rejection as `err` (or `null` on success). How to write those wrappers by hand is covered in the JavaScript lesson on promisification; what matters here is that both rely on every callback API keeping this convention. One edge shows why `null` is special. Because a `null` first argument means success, `util.callbackify` cannot pass a falsy rejection reason through as-is: if the promise rejects with `null`, `0` or `''`, Node wraps that value in an `Error` with code `ERR_FALSY_VALUE_REJECTION` and keeps the original in a `reason` property. The convention depends on every real failure being a truthy value, ideally an `Error`.

  • Why should a callback-style API not call callback(null, result) inside the try block that guards its own parsing?
    If the caller's callback throws, that `catch` receives the caller's exception and calls `callback(err)`, so the callback runs twice: once with success, then with an error that is not the API's. Compute inside `try`, call back outside it. Node's internals report the same bug class as `ERR_MULTIPLE_CALLBACK`.
  • Node core throws a TypeError synchronously when fs.open is given an object as its path. Doesn't that break the always-asynchronous rule?
    Node separates the two cases. Invalid arguments are programmer mistakes, checked before any work starts and thrown at once as `TypeError` with codes like `ERR_INVALID_ARG_TYPE`. Failures from the operating system, such as `ENOENT`, always arrive through the callback. The rule is about errors an API chooses to deliver through its callback: those must never be delivered synchronously.

  • Wrapping fs.readFile in try/catch will catch a missing-file error.
  • On success err is an empty Error, so check err.message instead.
  • Calling back synchronously on a cache hit is a harmless optimisation.
  • An exception thrown inside the callback comes back as its err argument.
  • After handling err there is no need to return; the rest is skipped.
open as a page

In Node.js, what does registering process.on('uncaughtException') change about a crash, and why is it unsafe to keep serving afterwards?

level: juniorimportance: must knowfreq 70%

basics

~20 s

A process 'uncaughtException' listener replaces Node's default of printing the stack trace and exiting with code 1, so the process keeps running. Its state is now unknown, so the handler should log synchronously, clean up and exit non-zero.

open as a page

In a Node.js HTTP service, how does `AsyncLocalStorage` keep a request id available to every log line and to an error thrown several awaits deep?

level: middleimportance: must knowfreq 62%

basics

~10 s

Wrap each request in asyncLocalStorage.run(store, handler). Timers, I/O callbacks and awaits started inside inherit that store, so logging and error code read it with getStore() instead of passing the id through every call.

open as a page

In a Node.js service, what separates an operational error from a programmer error, and which one calls for a retry, a client-error response, or a crash?

level: middleimportance: must knowfreq 55%

basics

~20 s

In Node.js, an operational error is a failure correct code must expect, such as ENOENT or ECONNRESET; a programmer error is a bug, such as ERR_INVALID_ARG_TYPE. Retry transient operational errors, report permanent ones, and never retry bugs.

open as a page

In Node.js, what does a system error such as ENOENT or ECONNRESET carry, and why should code branch on error.code rather than error.message?

level: middleimportance: must knowfreq 60%

basics

~20 s

A Node.js system error is a plain Error with a string code such as ENOENT, a negative platform-specific errno, the failing syscall, and a path or address when relevant. Node documents code as stable; message text may change in any release.

open as a page

A Node.js 24 worker service crashed overnight on a rejected fire-and-forget call: what path took it down, and how do the --unhandled-rejections modes change it?

level: middleimportance: must knowfreq 65%

basics

~20 s

Under Node 24's default mode, throw, Node emits 'unhandledRejection'; with no listener it raises the rejection as an uncaught exception, which crashes the process with exit code 1. The strict, warn, warn-with-error-code and none modes change that path.

open as a page

How do you implement graceful shutdown on SIGTERM in a Node.js HTTP service, from refusing new work to the final exit?

level: middleimportance: must knowfreq 78%

basics

~10 s

Catch SIGTERM, stop taking new work with server.close() and by pausing queue consumers, let in-flight requests finish, then close database pools, and arm an unref'd timer that calls process.exit(1) if draining stalls.

open as a page

In Node.js, what do the rss, heapUsed, heapTotal and external fields of process.memoryUsage() measure, and why can RSS grow while the heap stays flat?

level: middleimportance: must knowfreq 55%

basics

~20 s

heapUsed and heapTotal describe V8's JavaScript heap, external counts memory outside it such as Buffer and ArrayBuffer storage, and rss is the whole process's resident memory. RSS can climb with a flat heap when Buffers, native code or allocator fragmentation grow.

open as a page

A Node 24 service in a 1 GiB container is killed by the orchestrator instead of failing with 'JavaScript heap out of memory'; how should you set its V8 heap limit?

level: seniorimportance: must knowfreq 60%

basics

~20 s

Set V8's heap limit explicitly and well below the container limit, leaving room for memory outside the heap: --max-old-space-size in MiB, or in Node 24.6 and later --max-old-space-size-percentage, which uses the cgroup limit when one is set. A leak then fails inside V8, with diagnostics.

open as a page

In Node 24, how do you capture heap snapshots from a production process whose memory climbs for hours, and what does each capture cost the process?

level: seniorimportance: must knowfreq 55%

basics

~20 s

Start Node with --heapsnapshot-signal or --heapsnapshot-near-heap-limit, or call v8.writeHeapSnapshot() from a protected trigger. Each snapshot blocks the event loop and needs about twice the heap's memory, so take them from an instance out of rotation, then compare two or three.

open as a page

How do you attach a debugger to a Node.js process, and how do `--inspect`, `--inspect-wait` and `--inspect-brk` differ?

level: juniorimportance: should knowfreq 55%

basics

~20 s

Start Node with --inspect to open a Chrome DevTools Protocol endpoint, by default on 127.0.0.1:9229, then attach DevTools, an IDE or node inspect. --inspect runs immediately, --inspect-wait waits for a client, --inspect-brk also pauses on line one.

open as a page

In Node.js, what happens when the process receives SIGTERM or SIGINT with no listener, and what changes once you call process.on('SIGTERM')?

level: juniorimportance: should knowfreq 52%

basics

~20 s

With no listener, Node's default handler exits at once with code 128 plus the signal number, cutting off in-flight work. Installing a listener removes that default: Node stops exiting, so the handler must drain and end the process itself.

open as a page

In Node.js, what does a MaxListenersExceededWarning ('Possible EventEmitter memory leak detected') mean, and how should you respond to it?

level: juniorimportance: should knowfreq 45%

basics

~20 s

Node prints it when one EventEmitter holds more than 10 listeners for a single event, a common sign that code adds a listener per request and never removes it. Find that code and remove the listener instead of raising the limit.

open as a page

In Node.js, when is the process 'beforeExit' event emitted versus 'exit', and why can only 'beforeExit' do asynchronous work?

level: middleimportance: should knowfreq 40%

basics

~20 s

'beforeExit' fires when the event loop has drained and Node is about to exit naturally; a listener may schedule async work, which keeps the process running. 'exit' fires once exit is certain, such as after process.exit(), and its listeners must be synchronous.

open as a page

A job runner reports Node.js scripts exiting with codes 1, 7, 9 and 13: what does each code say about how the process ended?

level: middleimportance: should knowfreq 30%

basics

~20 s

Node exits 1 for an uncaught exception no handler took, 7 when the exception handler itself threw, 9 for an invalid command-line option, and 13 when top-level await never settled. Codes above 128 mean a fatal signal: 128 plus its number.

open as a page

In a Node 24 HTTP server, what does server.close() wait for, and how do closeIdleConnections() and closeAllConnections() differ from it?

level: middleimportance: should knowfreq 55%

basics

~10 s

server.close() stops new connections, closes idle ones, and calls back only when every connection has ended. closeIdleConnections() destroys only idle connections; closeAllConnections() destroys active ones too, except upgraded sockets such as WebSocket.

open as a page

In a Node.js service, an error several awaits deep keeps its callers in the stack, but one from a callback-based driver, or under deep middleware, shows only library frames. Why, and what helps?

level: seniorimportance: should knowfreq 42%

basics

~20 s

An Error captures only the current tick's frames when created. Along an await chain V8 appends the awaiting async functions; a driver callback runs on a fresh tick with no link back. Promisify, await and wrap at the boundary.

open as a page

In a Node.js service, `asyncLocalStorage.getStore()` returns undefined, or another request's id, inside callbacks from a pooled client library. Why does that happen, and how do you fix it?

level: seniorimportance: should knowfreq 38%

basics

~20 s

The callback runs in the async context of whatever triggered it inside the library, such as a freed connection or another request's emit, not where you passed it. Promisify the API, or bind the callback with AsyncLocalStorage.bind or AsyncResource.

open as a page

A Node.js production process is misbehaving and you cannot restart it. How do you inspect it live, and what does each option cost?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Send SIGUSR1 to open the inspector, by default on 127.0.0.1:9229, reach it through a tunnel, and profile rather than pause. Or write a diagnostic report, if enabled with --report-on-signal or via process.report.writeReport(), which never stops the loop for long.

open as a page

A Node.js 24 client's net.connect to localhost on a closed port fails with an AggregateError rather than one ECONNREFUSED; why, and how should retry and logging code read it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Since Node 20, net.connect defaults to autoSelectFamily: true and tries every resolved address in turn. When all attempts fail it emits one AggregateError whose errors array holds each attempt, with the first attempt's code copied onto it.

open as a page

In a Node.js module that wraps low-level failures such as ENOENT or ECONNRESET in its own errors, how do you keep them matchable by code and still diagnosable?

level: seniorimportance: should knowfreq 40%

basics

~20 s

In Node.js, throw an Error subclass with a stable code of your own and pass the original as cause. Callers match on code, util.inspect prints the cause chain, and retry logic walks cause, as it must for fetch's 'fetch failed'.

open as a page

Why does a Node.js crash handler that logs to stdout and then calls process.exit(1) often lose its final log lines in a container, and what fixes it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

On POSIX, process.stdout writes to a pipe are asynchronous, and process.exit() terminates without waiting for queued writes. Set process.exitCode and let the loop drain, write the fatal line synchronously, or exit from the write callback with a timer as backstop.

open as a page

During a rolling deploy, a Node.js API calls server.close() on SIGTERM, yet it hangs for the whole grace period and some clients see connection resets; why?

level: seniorimportance: should knowfreq 58%

basics

~20 s

Keep-alive connections busy at close time stay open and keep carrying requests, and pools, consumers or intervals keep the event loop alive, so the process runs until SIGKILL cuts whatever is in flight and clients see resets.

open as a page

In Node.js, how do you read --trace-gc output to tell a memory leak apart from a heap that is merely under heavy garbage collection pressure?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Each --trace-gc line shows heap used before and after one collection. A leak shows as full collections whose after-value rises every time and frees little; pressure shows as frequent collections that keep returning to the same level while taking a large share of time.

open as a page

As the lead for several Node.js HTTP services, which shutdown defaults would you standardise so each one drains within its deploy budget, and what does each choice cost?

level: principalimportance: should knowfreq 30%

basics

~20 s

Standardise one shutdown module: a hard-exit timer below the platform's grace period, a fixed close order, Connection: close while draining, request time limits that fit the budget, and a rule for long-lived connections. Each trades deploy speed against dropped work.

open as a page

In Node.js 24, what is a process warning, how do you capture one with process.on('warning'), and which flags silence or escalate warnings?

level: middleimportance: nice to knowfreq 22%

basics

~20 s

A process warning is an Error-shaped notice, such as a DeprecationWarning, that Node emits on the 'warning' event and prints to stderr without stopping the process. --no-warnings hides printing, --disable-warning filters by code or type, --throw-deprecation escalates deprecations.

open as a page

Why does Node.js steer tooling away from `async_hooks.createHook` toward `AsyncLocalStorage` and `node:diagnostics_channel`, and what does each replacement provide?

level: seniorimportance: nice to knowfreq 20%

basics

~10 s

createHook fires callbacks for every async resource, forces costly promise tracking and kills the process if a hook throws. AsyncLocalStorage covers context propagation; diagnostics_channel gives libraries cheap named events that tools subscribe to.

open as a page