What is an unhandled promise rejection in Node.js, and how does it arise?
A promise rejects, and by the time Node finishes draining the microtask queue, nothing has attached a .catch(), a second argument to .then(), or an await inside a try. At that point Node emits unhandledRejection. The check is deferred because a handler attached in the same synchronous run or microtask pass still counts. If a handler is attached later, Node emits rejectionHandled, but your crash policy may already have acted by then.
Common causes
- Fire-and-forget calls. Calling
sendMetrics()withoutawaitor.catch()throws the result away. When it rejects, the rejection has no owner. - A missing
await. Atry/catcharounddb.save(row)withoutawaitcatches nothing. The function returns a promise synchronously, and the rejection escapes the block. - APIs that ignore return values.
forEach,setTimeout, andEventEmitterlisteners all call your function and drop what it returns. Passing them anasynccallback means every rejection inside it is unhandled. - Created early, awaited late. Code like
const p = fetchUser(); await loadConfig(); await p;leavespwithout a handler whileloadConfig()runs. Ifprejects first, Node reports it before theawaitever attaches.
Event emitter pitfalls
These are not promise rejections, but they fail the same way. Emitting 'error' on an emitter with no 'error' listener throws synchronously, and that usually becomes an uncaughtException. Streams, sockets, and child processes all emit 'error', so each one needs a listener. Manual .pipe() chains do not forward errors. A failing source leaves the destination open and leaks file descriptors. Prefer stream.pipeline(), which propagates the first error to a single callback or promise and destroys every stream in the chain.
const { pipeline } = require('node:stream/promises');
const fs = require('node:fs');
const zlib = require('node:zlib');
// Placeholder async work that can reject.
const save = async (row) => { if (!row.id) throw new Error('missing id'); };
const fetchUser = async () => ({ id: 'user-123' });
const loadConfig = async () => ({ region: 'eu-west-1' });
async function bad(rows) {
try {
save(rows[0]); // missing await: rejection escapes the try
} catch (err) { /* never runs */ }
rows.forEach(async (r) => save(r)); // forEach drops every returned promise
const p = fetchUser(); // created early...
await loadConfig(); // ...p has no handler while this runs
return p;
}
async function good(rows) {
try {
await save(rows[0]); // rejection lands in catch
} catch (err) {
console.error('save failed:', err.message);
}
// Keep the promises so every rejection has an owner.
await Promise.all(rows.map((r) => save(r)));
// Start both together; handlers attach in the same pass.
const [user, config] = await Promise.all([fetchUser(), loadConfig()]);
return { user, config };
}
// pipeline() forwards the first error and destroys all streams on failure,
// unlike src.pipe(gzip).pipe(dest), which leaves dest open.
async function compress(src, dest) {
await pipeline(fs.createReadStream(src), zlib.createGzip(), fs.createWriteStream(dest));
}
compress('/var/log/app/app.log', '/tmp/app.log.gz')
.catch((err) => console.error('compress failed:', err.message));
Shows a missing await, an async forEach callback, and an early-created promise that each produce unhandled rejections, with fixes that use await, Promise.all, and stream pipeline() for error propagation and cleanup.
How do uncaughtException and unhandledRejection differ, and how does --unhandled-rejections change behavior?
uncaughtException fires when a synchronous throw unwinds all the way to the event loop with nothing to catch it. Common sources are a throw inside a timer or I/O callback, or an 'error' event emitted on an EventEmitter with no listener. unhandledRejection fires when a promise rejects and no .catch() or await has claimed it by the time Node processes the microtask queue.
Both events point to a programmer error, even when the underlying cause is operational, such as a refused connection. A refused connection is an expected failure. Reaching the global handler means the code had no path for it. The bug is the missing handler, not the network. The fix belongs at the call site, not in a global hook that has lost all context about which request or transaction failed.
The --unhandled-rejections flag controls what Node does when a promise rejects with no handler:
| Mode | unhandledRejection listener runs? |
Process behavior |
|---|---|---|
strict |
No; the rejection is raised as an uncaught exception | Exits unless an uncaughtException handler intervenes |
throw |
Yes, first | If no listener exists, raises as uncaught exception and exits |
warn |
Yes | Logs a warning and keeps running |
Defaults have changed across Node releases. Check the default for the runtime you actually deploy, then set the mode explicitly in your start command so a base-image upgrade cannot silently change your crash behavior.
Also audit the built bundle, not just your own code. Libraries and APM agents sometimes register their own process.on('uncaughtException') or unhandledRejection listeners. Registering any listener changes the default exit behavior, and a listener that logs without rethrowing or exiting will swallow the error. Call process.listeners() at startup to see what is attached.
// Set the mode explicitly in the start command so a Node or base-image upgrade
// cannot silently change crash behavior:
// node --unhandled-rejections=strict server.js
'use strict';
// Load the app first. This also loads its libraries and any APM agent, so the
// listeners they register exist before the audit runs.
require('./app');
// Startup audit: list every global error listener the bundle has registered.
// Any listener changes default exit behavior. One that logs but does not exit
// will swallow the error.
for (const event of ['uncaughtException', 'unhandledRejection']) {
for (const fn of process.listeners(event)) {
console.warn(
`[startup-audit] ${event} listener: ${fn.name || '<anonymous>'}`,
fn.toString().slice(0, 120)
);
}
}
// Our only crash handler: record the error, then exit.
// In strict mode, unhandled rejections also arrive here, with origin
// 'unhandledRejection'. Never resume serving, because process state is unknown.
process.on('uncaughtException', (err, origin) => {
console.error(`[fatal] origin=${origin}`, err);
process.exitCode = 1;
// Give buffered logs a moment to flush, then force the exit.
setTimeout(() => process.exit(1), 1000);
});
Starts Node with an explicit --unhandled-rejections=strict mode, logs every global error listener that libraries or agents registered at startup, and installs a single handler that logs the error and exits.
Why is resuming after uncaughtException unsafe in production?
An exception that reaches uncaughtException has, by definition, unwound the stack past every frame that knew how to clean up. Whatever that code was in the middle of doing stops partway through. A mutex or advisory lock acquired three frames up is still held. A database transaction is still open on a pooled connection. A socket has half a response written to it. An in-memory cache has had one of two related keys updated. The handler receives the error object, but it has no record of which of these intermediate states the process is now in, and no general way to roll them back.
Node's documentation is explicit about this. It describes uncaughtException as a crude mechanism intended only as a last resort, and states that it is not safe to resume normal operation afterward. The handler's job is synchronous cleanup and logging before exit, not recovery.
The common alternative is to log a warning and keep serving traffic. In the short term this keeps availability up, which is why it looks attractive. The cost shows up later and is harder to trace. The bug that caused the throw is now a log line rather than an incident, so nobody fixes it. Requests keep reading cache entries that are inconsistent and writing data based on them. Leaked resources accumulate. A pool that loses one connection per occurrence will run dry over hours, and requests then start timing out with no stack trace that points back to the original fault.
This policy applies to any long-running service that runs under a supervisor. If a supervisor restarts the process, exiting costs you a few seconds and gives you clean state. Continuing in an unknown state can cost you corrupted data.
How do you implement a crash policy in global error handlers?
The handler should do a fixed sequence of steps, each one bounded in time, and it should run once. Set a flag on the first fatal error so that a second error during shutdown does not start the sequence again.
- Write the fatal log entry first, synchronously. Include the stack, the error type, and whatever request or job context you have. Use
fs.writeSyncon file descriptor 2, or call your logger's flush with a strict time limit. Async transports put entries in a buffer and send them on a later event-loop tick. If the process exits before that tick, the stack trace you most need is the line that never gets written. - Flip readiness to failing. Health checks and load balancers should stop sending traffic before you begin closing anything.
- Call
server.close(). This stops the server from accepting new connections. Existing connections stay open until they finish. - Drain in-flight work under a hard cap. Give requests a fixed number of seconds to complete, and set that number below your supervisor's own kill timeout.
- Call
process.exitwith a non-zero code. A non-zero code tells the supervisor that the process failed, not that it stopped normally.
Before you start draining, arm a fallback timer that calls process.exit(1) and call .unref() on it. Because the timer is unref'd, it does not keep the process alive on its own. It fires only if something else is still holding the event loop open, which is exactly the case where draining is stuck.
Without that cap, one hung socket or keep-alive connection can stall the drain indefinitely. The process stays alive, and the supervisor sees a running PID, so it never restarts it. You end up with a zombie: a process that looks healthy to the supervisor but has stopped doing useful work.
const fs = require('node:fs');
const http = require('node:http');
const DRAIN_MS = 10_000; // hard cap; keep below the supervisor's kill timeout
let ready = true;
let shuttingDown = false;
const server = http.createServer((req, res) => {
if (req.url === '/readyz') {
res.statusCode = ready ? 200 : 503; // load balancer polls this
return res.end();
}
res.end('ok');
});
server.listen(8080);
function fatal(kind, err) {
if (shuttingDown) return; // run once; ignore errors raised during shutdown
shuttingDown = true;
process.exitCode = 1; // any exit path from here reports failure
// 1. Synchronous write to fd 2: no buffer, so it is written even if we exit right after.
const stack = err instanceof Error ? err.stack : String(err);
fs.writeSync(2, JSON.stringify({ level: 'fatal', kind, pid: process.pid, time: new Date().toISOString(), stack }) + '\n');
// 2. Fail readiness so new traffic is routed elsewhere.
ready = false;
// Fallback: unref'd, so it only fires if something is still holding the loop open (a stuck drain).
setTimeout(() => process.exit(1), DRAIN_MS).unref();
// 3 + 4. Stop accepting connections; the callback runs once in-flight requests finish.
server.close(() => process.exit(1)); // 5. Non-zero exit tells the supervisor to restart
server.closeIdleConnections(); // idle keep-alive sockets would otherwise stall the drain
}
process.on('uncaughtException', (err) => fatal('uncaughtException', err));
process.on('unhandledRejection', (reason) => fatal('unhandledRejection', reason));
This is a run-once fatal handler. It writes the stack synchronously to stderr, fails readiness, closes the server, and exits non-zero, with an unref'd timer as a hard cap so a hung drain cannot leave the process running indefinitely.
Where should error boundaries go, and how do you tell operational errors from programmer errors?
The fix for the zombie is to stop errors from ever reaching the process-level handlers by accident. Place a boundary wherever a unit of work begins. Each boundary has one job: turn a failure into an outcome the system already knows how to handle.
| Boundary | Unit of work | Outcome on operational error |
|---|---|---|
| HTTP error middleware | One request | 4xx/5xx response |
| Queue worker wrapper | One job | Retry with backoff, then dead-letter |
| Stream/topic consumer | One message | Negative ack or dead-letter |
Explicit .catch on fire-and-forget |
One background task | Log, record a metric, discard |
At these boundaries, classify the error before acting. Operational errors are failures the code anticipated: timeouts, ECONNREFUSED, a full disk, a payload that fails validation. The process state is still correct. Only the outside world misbehaved. Handle these at the boundary and keep serving.
Programmer errors are different: a TypeError, reading a property of undefined, an assertion that a broken invariant tripped. These show the code itself is wrong, and shared state may already be corrupted. Retrying a job that hit a TypeError only repeats the bug. Rethrow these past the boundary so the crash policy handles them.
Some work runs outside any request scope: setInterval timers, cache refreshers, and EventEmitter listeners. No middleware wraps it, so each needs its own handler. Give every emitter an 'error' listener, and wrap every timer callback. If you skip this, a single failed cache refresh can become an unhandled rejection that takes down the whole process.
class ValidationError extends Error {}
const OPERATIONAL_CODES = new Set(['ETIMEDOUT', 'ECONNREFUSED', 'ECONNRESET', 'ENOSPC']);
// Operational = the outside world failed; process state is still trustworthy.
const isOperational = (err) =>
err instanceof ValidationError || OPERATIONAL_CODES.has(err?.code);
// Programmer errors leave the boundary: rethrow outside any promise chain so
// it surfaces as 'uncaughtException' and the crash policy takes over.
const escalate = (err) => setImmediate(() => { throw err; });
// Boundary 1: HTTP error middleware, one request -> one response.
app.use((err, req, res, next) => {
const status = err instanceof ValidationError ? 400 : 503;
res.status(isOperational(err) ? status : 500).json({ error: 'request failed' });
if (!isOperational(err)) escalate(err);
});
// Boundary 2: queue worker, one job -> retry, dead-letter, or escalate.
async function runJob(job, handler) {
try {
await handler(job.data);
} catch (err) {
if (!isOperational(err)) return escalate(err); // retrying a TypeError repeats the bug
if (job.attempts < 5) await job.retry({ delayMs: 1000 * 2 ** job.attempts });
else await job.deadLetter(err);
}
}
// Boundary 3: background work outside request scope gets its own handler.
const onBackgroundError = (task) => (err) => {
if (!isOperational(err)) return escalate(err);
logger.warn({ task, code: err.code }, 'background task failed');
metrics.increment(`background_failure.${task}`);
};
setInterval(() => refreshCache().catch(onBackgroundError('cache-refresh')), 30_000);
sendAuditEvent({ action: 'login' }).catch(onBackgroundError('audit')); // fire-and-forget
brokerConnection.on('error', onBackgroundError('broker-connection'));
Each unit of work (request, job, timer tick, fire-and-forget call, emitter) has its own boundary. Operational errors become a response, a retry, a dead-letter, or a metric there. Programmer errors are rethrown outside the promise chain so the process-level crash policy handles them.
When should you avoid crash-on-error, and what are the alternatives?
Crashing has a blast radius. When one bad request triggers a fatal error, every in-flight request on that instance fails with it. For short HTTP calls, the cost is a handful of retries. For WebSockets or long-polling, thousands of clients reconnect at once and can overload the surviving instances. Shrink the blast radius instead of dropping the policy:
- Run enough replicas that losing one is routine.
- Give shutdown a drain window so the load balancer stops routing traffic before the process exits.
- Make clients retry idempotent operations with jittered backoff.
The second risk is a crash loop. A poisoned queue message or a startup bug crashes the process every time it runs. Restart with exponential backoff, and move a message to a dead-letter queue after a fixed number of failed deliveries. Alert on restart frequency, not only on downtime, because a fast loop can pass health checks between restarts.
Legacy codebases full of floating promises need a time-boxed rollout. Start in warn mode and emit a metric for each rejection, tagged by stack origin. Fix the top sources first. Set a fixed deadline, then switch to strict. Without a deadline, warn mode tends to become permanent.
| Approach | Risk | Availability |
|---|---|---|
| Warn-and-continue | High: corrupted state persists silently | High in the short term, but failures surface later and are harder to diagnose |
| Per-boundary handling only | Medium: any gap between boundaries leaks errors | High where boundaries exist |
| Crash-and-restart | Low: state is reset to a known-good baseline | Brief per-instance loss, covered by replicas and draining |
How do supervisors and lint rules reduce the cost of crashes and save engineering time?
A crash policy only works if crashes are cheap. Run every service under a supervisor or orchestrator that restarts the process on exit, and run at least two instances behind a load balancer so a restart drops only the requests in flight on one instance. Restarts that nobody sees can hide a failing deploy, so alert on restart rate rather than on single exits. Send crash output, including the final logged error and stack, through the same log pipeline as normal service logs so it can be searched and correlated with requests.
Catch floating promises before deploy
Type-aware lint rules find many rejections at review time. In typescript-eslint, no-floating-promises flags promises that are never awaited, returned, or given a rejection handler. no-misused-promises flags async functions passed where a callback's return value is ignored, such as event emitter listeners or forEach. In those places a rejection has no caller to receive it. These rules are a first line of defense and do not replace the runtime policy. Code with any types, third-party libraries, and dynamic dispatch can still let a rejection through.
The trade-off
The upfront work is writing the handlers, placing boundaries, and fixing lint violations in existing code. You get that time back by not chasing silent state corruption and slow leaks later.
Illustrative estimate (assumed numbers, not a benchmark): Hours saved per year = (incidents avoided × hours per investigation) − one-time setup hours.
Assume 6 incidents avoided, 8 hours each, and 30 hours of setup: 6 × 8 − 30 = 18 hours saved in the first year. In later years, with no setup cost, the saving is the full 48 hours.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to node unhandled promise rejection production, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.