Ömer Faruk YILDIRIM
tutorials

Node.js Production Failure Lab · part 3

How One Failed Email Can Take Down an Entire API: Unhandled Promise Rejections in Node.js

The error alert keeps flapping, and customers who see 'Bad Gateway' place their order again. Step by step, from 502 graphs to a stack trace, we trace how the unhandled rejection of a confirmation email sent in the background kills the entire Node.js process.

29 min read45 min hands-oncode(opens in a new tab)

Node.js Production Failure Lab · Part 3 · Difficulty ★☆☆ · Reading time ~20 min · Lab ~30–45 min

In February 2026, an issue was filed against the open-source OpenClaw project: when the language model API returned a 403 or 404 to a call, the resulting unhandled promise rejection instantly took down the entire Node.js gateway process. The process manager restarted it, the new process found the port still in use and died again, and the chat interface became completely unresponsive (openclaw/openclaw#23441). In January 2026, a similar picture was described on the Ghost forum: a blog upgraded to 6.10.3 was stuck in an endless systemd restart loop because of an unhandled rejection from background services at startup. What stopped the loop was a single .catch() (Ghost Forum).

In both incidents the trigger was mundane: an external service returned an error, once. What brought the system down wasn’t the error itself but the fact that nobody owned it. Since Node.js 15, an unowned promise rejection isn’t an application error; it’s the death of the process.

In this article we’ll live through the same picture in a production incident. Back-to-school orders are coming in, the error alert flaps about once a minute, and customers who see “Bad Gateway” place their order again and end up ordering twice. The culprit is yesterday’s “customers shouldn’t wait for the email” optimization.

In Part 2, what killed the process was a heap filling up. This time there are restarts and 502 waves again, but memory is flat. What kills the process isn’t a resource; it’s a single line.

What you’ll learn

  • What it means to “own” a promise, and why Node.js treats an unowned rejection as fatal
  • Why void promise silences the linter but catches nothing
  • How to match 502 waves to restarts, and how to read a dead process’s last words from stderr
  • Why a crashing process’s own metrics are the least reliable witness, and why the other side’s records are better
  • How a background task’s failure cuts off requests from customers who have nothing to do with it (and the duplicate orders that follow)
  • The fix: handling the error where it happens, retrying transient errors with backoff, idempotency keys, the outbox

Prerequisites

You can read this article without running the lab. These will help:

TopicWhyResource
Error handling with promisesTo know .catch(), chaining, and rejection eventsMDN, Using promises (the “Error handling” and “Promise rejection events” sections)
The unhandledRejection eventTo see how Node.js notices an unowned rejectionNode.js process: ‘unhandledRejection’
--unhandled-rejections modesTo see why the default is throwNode.js CLI: —unhandled-rejections
The previous partThe idea that a 502 wave = no process behind the proxyPart 2: Memory leak

1. The concept: every promise needs an owner

When you call an async function, you get back a promise. Later, that promise is either fulfilled with a value or rejected with an error. When it’s rejected, someone has to receive the error. There are two ways to do that:

  • You await it: the error is thrown in the function doing the await, and your own try/catch or a higher layer, such as Express’s error middleware, catches it.
  • You attach a .catch() (or a two-argument .then()): the error goes to that callback.

If you do neither, the promise is left floating. When it’s rejected, Node.js looks around, sees that nobody attached a handler within one turn of the event loop, and emits the unhandledRejection event. If nobody is listening for that event either, it throws the rejection as an uncaught exception. And the outcome of an uncaught exception is well known: the error and stack trace are written to stderr, and the process exits with code 1.

It wasn’t always this way. Up to Node.js 14, the default was to print a warning (UnhandledPromiseRejectionWarning) and keep going. With Node.js 15, the default became throw (v15.0.0 release notes). The reason is simple: a process that silently swallows an error is a process that keeps running in an unknown state.

request (POST /api/orders)
 ├─ save the order ──► response: 201 ✔  (the customer is done)
 └─ void confirmOrder(order)  ──► MailWave ... 503 ──► rejection ──► no owner
                                                           │
                                     Node.js: "unhandled rejection" → uncaught exception → exit(1)
                                                           │
    EVERY request in the process at that moment (including other customers' checkouts) ──► cut off ──► 502

Notice three things:

  1. try/catch only sees errors that are awaited. Wrapping the call in a try block catches nothing if the promise isn’t awaited: the rejection arrives long after the try block has finished.
  2. void is not a handler. void confirmOrder(order) tells the linter “I’m deliberately not waiting for this.” typescript-eslint’s no-floating-promises rule accepts void in its default configuration, but its documentation states plainly that this doesn’t handle the error and doesn’t change runtime behavior (no-floating-promises).
  3. What dies isn’t the request that triggered the error; it’s the process. That customer may already have their order. The requests that get cut off belong to everyone who happened to be in the process at that millisecond.

See it for yourself: a 30-line experiment

// fire-and-forget.mjs
import http from 'node:http';

// "Send an email" in the background: the provider returns 503 on every 5th order.
async function sendEmail(orderId) {
  await new Promise((resolve) => setTimeout(resolve, 50));
  if (orderId % 5 === 0) throw new Error(`provider responded 503 (order ${orderId})`);
}

let orders = 0;
http.createServer(async (req, res) => {
  if (req.url === '/order') {
    const id = ++orders;
    try {
      void sendEmail(id); // not awaited: try/catch can't see this error
    } catch {
      console.log('never reached');
    }
    return res.end(`order ${id} ok\n`);
  }
  if (req.url === '/slow') {               // another customer's long-running request
    await new Promise((resolve) => setTimeout(resolve, 1000));
    return res.end('slow ok\n');
  }
  res.end('ok\n');
}).listen(3002, () => console.log(`pid ${process.pid} ready`));

A small script that starts the server, fires a 1-second /slow request, then sends seven orders 100 ms apart:

# run.sh
node "$1" & server=$!
sleep 0.5
curl -s -o /dev/null -w 'slow: http=%{http_code} time=%{time_total}s\n' localhost:3002/slow & slow=$!
for i in 1 2 3 4 5 6 7; do
  curl -s -o /dev/null -w "order $i: http=%{http_code}\n" localhost:3002/order
  sleep 0.1
done
wait $slow
kill -0 $server 2>/dev/null && echo "server: up" || echo "server: dead"
kill $server 2>/dev/null

On my machine (Node.js 22.18), ./run.sh fire-and-forget.mjs:

order 1: http=200
...
order 5: http=200
./fire-and-forget.mjs:7
  if (orderId % 5 === 0) throw new Error(`provider responded 503 (order ${orderId})`);
                               ^

Error: provider responded 503 (order 5)
    at sendEmail (./fire-and-forget.mjs:7:32)

Node.js v22.18.0
slow: http=000 time=0.563132s
order 6: http=000
order 7: http=000
server: dead

Four things to read here:

  1. Order 5 got a 200. The customer who triggered the error noticed nothing; their request had finished 50 ms earlier.
  2. The /slow request was cut off with 000 after 0.56 seconds. A customer with nothing to do with orders lost their connection while waiting for a response.
  3. Orders 6 and 7 couldn’t even connect. There’s no process behind them. In production, with a proxy in front of you, the customer sees this as 502 Bad Gateway.
  4. try/catch caught nothing; the “never reached” line was never printed.

Let’s change one line: replace void sendEmail(id) with sendEmail(id).catch((err) => console.error(email could not be sent: ${err.message})):

order 1: http=200
...
order 5: http=200
email could not be sent: provider responded 503 (order 5)
order 6: http=200
order 7: http=200
slow: http=200 time=1.010969s
server: up

Same error, same frequency. The only difference is that the error has an owner.


2. The incident: back-to-school week

🔥 [FIRING] ApiHighErrorRate: more than 1 % of shopflow-api requests are failing

It’s the last week of August, and back-to-school orders are pouring into ShopFlow. Since yesterday afternoon, the error alert has been firing and resolving on its own: about once a minute a batch of requests fails, then everything goes back to normal. The support team forwards two messages:

“I got ‘Bad Gateway’ when I clicked Place order, so I clicked again. Now I have two identical orders.”

“Your site freezes for a few seconds. It’s fine if I wait a bit.”

Here’s what you know:

  • Traffic is normal: ~38 requests/s, ~3 orders/s.
  • Between the waves, latency is normal.
  • The status page of the email provider, MailWave, shows no incidents.
  • Recent deploys:
VersionWhenChange
2.18.1today 10:15OpenTelemetry packages upgraded; outgoing fetch calls are now traced
2.18.0yesterday 16:40order confirmation emails sent via MailWave, in the background
2.17.32 weeks agoa catalog limit above 100 returns 400 instead of 500

If you’ve set up the lab, start the incident:

git clone https://github.com/FARUK-YILDIRIM/nodejs-production-failure-lab.git
cd nodejs-production-failure-lab
./lab start 003

💡 Want to try it yourself first? Stop here, open Grafana (http://localhost:3000), and investigate on your own for 30 minutes. The first waves arrive within a few minutes. The results of each step below are tucked into collapsible sections; open them when you get stuck. For the lab’s built-in hints: ./lab hint 003.


3. Investigation, step by step

Step 1: Is a 502 a bad response, or no response at all?

Look at the Requests per second by status panel at the top of the dashboard. Are the errors 500s, 502s, or 503s? Then, for the same range, switch to the API restarts (1h) count and the Node.js runtime → Memory panel.

What do we see?

Every error is a 502. There isn’t a single 500 produced by the application itself. A 502 is Traefik saying “I couldn’t reach the service behind me”: the API isn’t giving a bad response; it isn’t there at all.

In my run, over a 14-minute window (23:56–00:10), ~234 of ~32,100 requests came back as 502: 0.73% on average, but as high as 4.9% in a single minute. That’s why the alert flaps around its “above 1%” threshold. In the same window the API restarted 10 times, and the 502 waves line up exactly with the restarts.

Memory, on the other hand, is flat: heap used sits between 30 and 70 MiB and never gets close to the heap limit (256 MiB). No sawtooth. This isn’t the leak from Part 2: the process isn’t dying because something fills up; it dies all at once.

Grafana: on the left, requests by status code, with thin blue 502 waves at irregular intervals on top of the 200s and 201s; on the right, the memory panel, with heap used flat in the 30–70 MiB band and short gaps at restart times

The blue 502 waves are irregular: sometimes 20 seconds apart, sometimes none for 2.5 minutes. On the right, the gaps in the memory graph are the restarts; the heap is far below its 256 MiB limit and isn’t climbing.

The intervals between restarts aren’t regular either. According to the timestamps in the container logs, the gaps between the first 12 crashes range from 1 to 152 seconds (averaging ~30 seconds), followed by a quiet stretch of 2.5 minutes. Irregular intervals suggest not a resource filling up but an event arriving at random.

Lesson: When you see a 502, the first question shouldn’t be “what did the application respond?” but “was the application there?”

Step 2: Read the last words before death

A dying process can’t log its own death with its logger, but it does write to stderr, and the container runtime keeps the output of previous runs. In the output of ./lab logs api, every Debugger listening line is a fresh start. What comes right before it?

The last lines

Right before every restart, the same stack trace:

Terminal: output of ./lab logs api; after the 'shopflow-api listening' line, the throw line in order-confirmation.ts:31, a red 'Error: MailWave responded 503: service_unavailable', with sendOrderConfirmation and async confirmOrder in the stack; then Node.js v24.22.1 and a fresh start with Debugger listening; at the bottom, the MailWave delivery log showing status 503 at 21:00:57.440 for order 509396

The process dies at 21:00:57 on MailWave’s 503 and starts listening again 0.6 seconds later (21:00:58.116). The delivery log at the bottom shows the same moment from the other side: the confirmation email for the order saved at 21:00:57.31 got a 503 at 21:00:57.440, and the process died ~100 ms later.

There are three clues here:

  • The error is MailWave’s 503. sendOrderConfirmation throws on an unsuccessful response; that’s normal and correct.
  • There’s no request handler anywhere in the stack. Above confirmOrder there’s nothing: this code isn’t being awaited inside an HTTP request.
  • There’s no request failed line and no 500 response. The application’s error middleware never saw this error. It climbed up the stack uncaught and terminated the process.

In my first 8-minute observation, the log had 12 Error: MailWave responded 503 lines and the container had restarted 12 times. One for one.

Lesson: When a process crashes, it’s not the application logs that talk; it’s stderr and the output of the previous run.

Step 3: Is the dependency broken? Read the records from both sides

Your first reflex might be “MailWave is down.” Look at the Calls to other services → Calls per second, by service and status panel on the dashboard. Then ask the other side the same question: MailWave publishes its own metric (mailwave_requests_total) and has a delivery log (http://localhost:8025/v1/messages?orderId=<id>).

The two sides of the story

According to the API’s own metric, every call to MailWave succeeded: the panel has a single series, mailwave 202, mostly at 2.5–3.5 calls per second. Not a single 503.

Grafana: the Calls per second, by service and status panel; only the 'mailwave 202' series, between 1.5 and 4 per second; no error series at all

From the API’s point of view, MailWave is flawless: the only series is “mailwave 202.” And yet the process is dying precisely because of MailWave’s errors.

MailWave’s own counter says something else. Three queries in Explore over the same range:

sum(increase(mailwave_requests_total{status="503"}[1m]))                       # the provider's record
changes(process_start_time_seconds{job="api"}[1m])                             # API restarts
sum(increase(http_client_request_duration_seconds_count{job="api",peer="mailwave",status_code!~"2.."}[1m]))  # the API's record

Grafana Explore: green MailWave 503 responses and yellow API restarts rise and fall together at the same moments; the blue MailWave errors from the API's metrics stay flat at zero

Green (the 503s MailWave returned) and yellow (API restarts) are nearly on top of each other. Blue, the MailWave errors the API recorded itself, is zero from start to finish.

Why? The API does write the failed call to its metric, but it dies before Prometheus’s next scrape. The counter goes down with the process. A crashing process’s own metrics are the least reliable witness; stderr and the other side’s records are better. For the same reason, you won’t find a MailWave span with a 503 in Jaeger either: spans are exported in batches, and the ones waiting to be sent die with the process.

So is MailWave actually broken? According to the counters, 12 of 1,946 calls in the first ~10 minutes were 503s: 0.6%. That’s an ordinary day for a healthy external service. The problem isn’t that the provider returns errors; it’s what the API does with that 0.6%.

Lesson: A dependency with 99.4% success is healthy. Write your code assuming every external call will fail every now and then.

Step 4: Spot the work that runs “after the response” in the trace

In Jaeger, open one of the POST /api/orders traces. Compare the proxy’s span with the span of the MailWave call: which one finishes first?

What does the trace show?

Jaeger: a traefik POST trace, 121 ms total; the traefik and shopflow-api POST /api/orders spans finish with 201 at 9 ms; at the bottom, the shopflow-api POST 202 span (the MailWave call) starts after the response and lasts 112 ms

The customer’s request finishes with a 201 in 9 ms. The MailWave call at the bottom (112 ms) starts after the response has been sent: nobody is waiting for it. When it succeeds, no problem; when it fails, there’s nobody left to receive its error.

The flow in this trace is exactly the 2.18.0 change: “customers shouldn’t wait for the email provider.” The intent is right, and it does help latency. What’s missing is who owns the failure of this work that runs after the response has gone out.

Step 5: The code, last

The stack trace leads you to two files:

// notifications/order-confirmation.ts
export async function sendOrderConfirmation(message: OrderConfirmation): Promise<void> {
  const response = await callService('mailwave', `${config.mailwaveUrl}/v1/messages`, { /* ... */ });
  if (!response.ok) {
    throw new Error(`MailWave responded ${response.status}: ${await response.text()}`);
  }
}

// orders/orders.service.ts (2.18.0)
export async function placeOrder(input: NewOrder) {
  const orderId = await transaction(/* save the order and its line items */);
  const order = await getOrder(orderId);

  // Customers shouldn't wait for the email provider: confirm in the background.
  void confirmOrder(order);   // started, not awaited, no .catch()
  return order;
}

sendOrderConfirmation is right to throw: a failed send shouldn’t be silently swallowed. The bug is that there’s nobody to receive that error. void keeps the linter happy but catches nothing.

The math checks out too: ~3 orders per second × 0.6% errors ≈ ~1 crash per minute. My 14-minute window had 10 restarts; for a random event, that’s the same order of magnitude.

What about 2.18.1, the OpenTelemetry upgrade? New instrumentation is a classic suspect for crashes, and it’s the most recent deploy. But the waves started a day before it, with 2.18.0. Follow the evidence, not the latest deploy.

The lab’s diagnosis questions and answers (./lab submit 003)
QuestionAnswer
Why does the API process exit?A promise rejection that nothing handles
Which error triggers it?The email provider answering with an error
Requests to which endpoint lead to the crashes?POST /api/orders

What about the duplicate orders?

Remember the support team’s first message: “I got Bad Gateway, clicked again, and now I have two orders.” The crash isn’t tied to the request that triggered it. The order that started the error has long since been saved and answered. The requests that die belong to whoever was in the process at that moment; some of them are other customers’ checkouts that have already been committed to the database. Their browsers get a 502, the customer clicks again, and a second order is created. Without a server-side idempotency key, there’s no way to tell that retry apart. (The lab’s 10th incident covers exactly this topic.)


4. Mitigation: stop the bleeding first

  • Roll back 2.18.0. Confirmation emails won’t go out until the fix lands, but checkout becomes stable. You can send the emails in bulk later from the orders in the database.
  • Or temporarily add a global handler: process.on('unhandledRejection', (err) => logger.error({ err }, 'unhandled rejection')). The crashes stop immediately. But this changes the behavior of every unowned rejection in the process, including the ones that really should be fatal. It’s a tourniquet, not a cure; remove it once the fix is in.
  • Don’t: blame MailWave and switch providers, roll back the OpenTelemetry upgrade (the crashes started before it), loosen the restart policy, or add instances. Every instance dies the same way on its share of the 503s.

5. The fix: make the background task own its failure

Handle the error where the promise is born. A promise nobody awaits has to deal with its own failure:

// orders/orders.service.ts
const confirmationFailures = new Counter({
  name: 'order_confirmation_failures_total',
  help: 'Order confirmation emails that could not be sent, even after retries.',
  registers: [registry],
});

// Customers shouldn't wait for the email provider: confirm in the background.
// Nothing awaits this promise, so it has to handle its own failure: an
// unhandled rejection terminates the whole Node.js process.
confirmOrder(order).catch((err: unknown) => {
  confirmationFailures.inc();
  logger.error({ err, orderId: order.id }, 'order confirmation email could not be sent');
});

Now a failed email touches neither the request nor the process. On top of that, the error is logged, together with the order number, and counted in a metric: before, the only trace of an email that couldn’t be sent was a stack trace.

Retry transient errors. Just catching the error means losing the email. MailWave’s 503 says “try again a bit later”; 429s, other 5xx responses, and network errors are usually transient too:

// notifications/order-confirmation.ts
const MAX_ATTEMPTS = 3;
const RETRYABLE_STATUSES = new Set([429, 500, 502, 503, 504]);

export async function sendOrderConfirmation(message: OrderConfirmation): Promise<void> {
  for (let attempt = 1; ; attempt++) {
    let failure: string;
    try {
      const response = await callService('mailwave', `${config.mailwaveUrl}/v1/messages`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${config.mailwaveApiKey}`,
          'Idempotency-Key': `order-confirmation-${message.orderId}`,
        },
        body: JSON.stringify({ /* ... */ }),
      });
      if (response.ok) return;
      failure = `MailWave responded ${response.status}: ${await response.text()}`;
      if (!RETRYABLE_STATUSES.has(response.status)) throw new Error(failure);
    } catch (err) {
      if (!(err instanceof TypeError)) throw err; // fetch() throws TypeError on network errors
      failure = `MailWave unreachable: ${err.message}`;
    }

    if (attempt === MAX_ATTEMPTS) throw new Error(`${failure} (after ${attempt} attempts)`);
    await sleep(250 * 2 ** (attempt - 1));   // 250 ms, then 500 ms
  }
}

Two details matter:

  • Backoff: the wait between attempts doubles each time, and the number of attempts is capped, so you don’t bury a struggling provider under instant retries. With many clients, adding random variation to the wait (jitter) is also good practice.
  • Idempotency key: the same Idempotency-Key on every attempt. If a request reaches the provider but its response is lost on the way back, the retry won’t send the customer a second email; the provider recognizes the key and drops the duplicate.

Why not just await the email inside the request? We could; it’s a safe choice. But it ties checkout’s latency and availability to the provider: if MailWave slows down, checkout slows down; if MailWave goes down, checkout goes down. 2.18.0’s intent was right; what was missing was ownership of the error.

6. Verification

./lab deploy
./lab verify 003

verify runs the standard traffic (open model, ~38 requests/s) for 60 seconds and measures from the client side. A confession first: I ran verify three times before the fix, and all three passed. Error rate 0.00%, restarts 0.

That’s not a lab bug; it’s the nature of rare errors. There are a few hundred orders in 60 seconds; at a 0.6% error rate, it’s no surprise not to hit a single 503. In my runs, MailWave really didn’t return a single 503 during those three minutes. A short green test doesn’t prove the absence of a rare error. That’s why I made the comparison over longer windows of the same production traffic, from Prometheus:

MetricBefore (14 min, 23:56–00:10)After (9 min, 00:17–00:26)
5xx rate (at the edge)0.73%0%
5xx rate in the worst minute4.9%0%
502 responses~2340
API restarts100
503s returned by MailWave116
Emails that couldn’t be sent11 (every 503 was a lost email; nearly every one was also a crash: 10 restarts)0 (order_confirmation_failures_total)
p95 at the edge19 ms12 ms

Read it row by row: MailWave keeps returning errors at the same rate after the fix (6 503s in 9 minutes). What changed is that those 503s no longer bring anything down: no restarts, no 502s, no lost emails. After the fix, verify naturally passes too (error rate 0.00%, checkout p95 14 ms, restarts 0), but after the three green results above, that alone isn’t proof. The real proof is that the process stays up even though the provider keeps returning errors.

The graphs tell the same story. The deploy happened at 00:16:27; the gap between 00:11 and 00:16 comes from verify pausing production traffic for its own measurement:

Before and after the fix: in requests by status code, the 502 waves disappear after the deploy; the restart gaps in the memory panel end

The dashed orange lines are deploys: the first three are verify’s own deploys (the deep dips between 00:11 and 00:16 are verify pausing production traffic), and the last one is the fix (00:16:27). After it, there are no red 502 waves. On the right, the heap stays in the same 30–80 MiB band; the orange RSS crossing the heap limit line isn’t a leak, since RSS also includes memory outside the heap.

Explore before and after the fix: MailWave 503s keep coming after the deploy, but API restarts stay at zero

Before the deploy, the yellow restarts are both crashes and verify deploys. After 00:16, MailWave still returns 503s (green), but the yellow restart line stays at zero. And now the blue line rises too: because the process stays up, the API can record the errors it sees in its own metric for the first time. Orange, the emails that couldn’t be sent, is zero from start to finish.

You can also see from the provider’s delivery log that the retry actually works. Of the first ~670 orders after the fix, three got a 503 on their first attempt; all three were delivered on the second:

Terminal: three orders in the MailWave delivery log; each one first has status 503, then status 202 ~300–350 ms later

Two records per order: first a 503, then a 202 after the 250 ms backoff plus network time (~300–350 ms). With the old code, that first line meant a crash and a lost email.


7. Fixes that look right but aren’t

AttemptWhy it falls short
A global process.on('unhandledRejection', log)Stops the crashes immediately, but silences every unowned rejection, future ones included. The Node.js documentation says explicitly that it isn’t safe to resume normal operation after an uncaught error (process: Warning: Using ‘uncaughtException’ correctly). As a last line of defense, “log, then shut down cleanly” is reasonable; “log and carry on” is not.
node --unhandled-rejections=warnThe same thing, from the command line. It doesn’t remove the error, it makes it invisible; the emails are still lost.
Wrapping the call in try { void confirmOrder(order) } catch {}try/catch can’t see the rejection of a promise that isn’t awaited. That’s the “never reached” line from the experiment.
awaiting the email inside the requestSafe, but ties checkout’s latency and availability to the provider. A provider outage becomes a checkout outage.
“MailWave is broken,” switching providers99.4% success is healthy. Every provider returns errors now and then; the next one will too.
Rolling back the OpenTelemetry upgradeThe waves started a day earlier. The newest deploy isn’t the most likely suspect.
A faster restart policy, more instancesEvery crash still cuts off in-flight requests; you only spread the blast radius.

8. In production: alternatives and prevention

The durable design: a transactional outbox. .catch() + retry ends the crashes, but if the process dies between the commit and the email (a deploy, an OOM, a kill), that email is still lost. The robust solution: write a “send the confirmation for order X” record to an outbox table in the same transaction as the order, and have a separate worker read that table and send the email with retries and an idempotency key. No network call to the provider is left on the API’s hot path, and no email is ever lost (Pattern: Transactional outbox). The lab’s 14th and 15th incidents build in this direction.

ApproachWhen
.catch() + log + metricThe bare minimum for every fire-and-forget promise.
+ retry with backoff + idempotency keyAny external call where transient errors are normal.
Outbox + workerWhen the work must not be lost (emails, payment notifications, webhooks).
Queue (Kafka, SQS…) + consumerThe same idea with more moving parts; when you need scale or multiple consumers.

Prevent it with linting. Turn on the @typescript-eslint/no-floating-promises rule. Treat void somePromise as something that needs a justification in code review, not as a way to silence the rule. If you like, you can ban void as well with ignoreVoid: false.

Test the failure paths. The tests ran MailWave against a fake service that never returned an error. Also run the checkout tests against a provider double that returns 503s, times out, and drops connections. A rare error is caught by deliberately injected failures, not by a short load test.

Alert on the first restart. The error-rate alert kept flapping, and in this scenario it was ignored as “flapping” for 18 hours. A restart, on the other hand, is meaningful on its own:

- alert: ApiRestarted
  expr: changes(process_start_time_seconds{job="api"}[5m]) > 0
  labels:
    severity: page

Code review checklist:

  • Is every promise either awaited, returned, or given a .catch()?
  • Where does the error of a call prefixed with void go?
  • What happens if work that runs after the response (emails, webhooks, analytics) is lost? If it must not be lost, where’s the outbox?
  • For external calls, which errors are retried, how many times, with what wait? Is the retry safe (idempotency key)?
  • Are endpoints with side effects, like orders, resilient to client retries?

Key takeaways

  • Since Node.js 15, an unowned promise rejection kills the process. Every promise needs an owner: await or .catch().
  • void is not a handler; it silences the linter, not the error. try/catch can’t see a promise that isn’t awaited.
  • A crashing process cuts off other people’s requests too. The customer who triggered the error often notices nothing, while the customer next to them gets a 502 and clicks again.
  • 502 = no process behind the proxy. The first places to look are restarts and the previous run’s stderr.
  • A crashing process’s own metrics are the least reliable witness; the other side’s records are better.
  • A dependency with 99.4% success is healthy. The problem isn’t the error; it’s how you handle it.
  • A short green test doesn’t prove the absence of a rare error; inject the error on purpose.

Test yourself

1. The 502 waves line up with restarts and memory is flat. Which two observations tell you this isn’t the leak from Part 2?

Memory isn’t climbing (no sawtooth, well below the heap limit), and the restart intervals are irregular (anywhere from 1 to 152 seconds). With a leak, the process dies periodically because a resource fills up; here it dies instantly because of an event that arrives at random. The final piece of evidence is the previous run’s stderr: not FATAL ERROR … heap out of memory, but the stack trace of an application error.

2. Why does the customer who triggered the error notice nothing, while other customers get 502s?

The email is sent in the background after the order’s response has gone out. By the time the 503 arrives, the triggering request has long since finished with a 201. When the process dies, what gets cut off are the other requests in the process at that moment; some of them are committed checkouts, and clicking again creates a duplicate order.

3. Why isn’t a global unhandledRejection handler a permanent fix?

It suppresses the symptom, but the error still has no owner: the email is still lost, there’s no metric counting it, and future rejections that really should be fatal get silently swallowed too. The process keeps running in an unknown state. The right place is a .catch() where the promise is born; a global handler is at most a last line of defense for “log and shut down cleanly.”

4. You’ve added retries. Why send the same idempotency key on every attempt?

The first request may have reached the provider and been processed, with only its response lost on the way back. If the retry carries the same key, the provider knows it’s the same message and doesn’t send a second email. If the key changed on every attempt, the customer could receive the same confirmation twice.

Further reading

Basics

Deep dives

Real-world incidents


Next up: Slow checkout. The API’s CPU is idle, and the dashboard of the tax service, TaxRate, says it answers quotes in ~30 ms; yet placing an order takes one to three seconds. We’ll learn about Node.js’s libuv thread pool, the hidden cost of dns.lookup, and HTTP keep-alive.

The full lab: https://github.com/FARUK-YILDIRIM/nodejs-production-failure-lab. If you’ve solved the lab, run ./lab report 003 to generate a postmortem template and compare it with your own write-up.