Ömer Faruk YILDIRIM
tutorials

Node.js Production Failure Lab · part 9

How an Optional Service Takes Down Product Pages: Timeout Budgets, Cancellation and Graceful Degradation

In the busiest hour of the week product pages won't load; there are no 5xx at the edge, the API's latency panel looks normal, and the recommendations service's dashboard is green. We follow step by step why requests that never finish don't show up in any histogram, how a few slow requests lock up a fixed number of workers, and how to replace a 30-second timeout with a 250 ms budget that really cancels the request, plus a fallback.

31 min read75 min hands-oncode(opens in a new tab)

Node.js Production Failure Lab · Part 9 · Difficulty ★★☆ · Reading time ~25 min · Lab ~45–75 min

On June 12, 2025, a number of Cloudflare products were partially or completely down for about two and a half hours (Cloudflare’s postmortem). The trigger was an outage at a third-party cloud provider hosting part of the storage behind Workers KV. But the postmortem’s real lesson lies elsewhere: many products, such as Access, Gateway, WARP, Workers AI and Turnstile, had a hard dependency on KV; when KV couldn’t answer, neither could they. During the outage a “kill switch” was flipped for Turnstile, and Gateway tried to “gracefully” disable rules that relied on identity and device posture; at the top of the action items is making every product survive the loss of any single dependency. Even though Cloudflare attributes the trigger to a third party, it writes that it is ultimately responsible for its dependency choices.

In this part we’ll live through a small, sneaky version of the same lesson. The dependency doesn’t crash, it just slows down; and the dependency isn’t even critical: it’s the “Customers also bought” box on the product page. Yet in the busiest hour of the week, product pages won’t load. There isn’t a single 5xx at the edge, the API’s own latency panel looks normal, and the recommendations service’s dashboard is all green.

In Part 8, checkout waited for the payment provider while holding a lock: a slow external call was taking a far more valuable resource (a row lock) hostage. This time, what gets taken hostage is a page itself. And this time the problem isn’t solved by a faster dependency, but by knowing how long we’re willing to wait.

What you’ll learn

  • Why requests that never finish don’t show up in any latency histogram; comparing the 499s at the edge with the API’s own measurement
  • How a service with a fixed number of workers slows down for every request when 10% of requests get slow (queueing), and why the dependency’s dashboard stays green
  • Deriving a timeout not from the dependency’s usual speed but from the caller’s budget
  • The difference between actually cancelling a request with AbortSignal.timeout() and merely giving up on waiting with Promise.race
  • Graceful degradation: showing the page without an optional feature (or with the old behavior) when it doesn’t answer
  • Linking active socket counts, the dependency’s worker/queue metrics and its logs into a chain of evidence

Prerequisites

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

TopicWhyResource
AbortController and AbortSignal.timeout()The fix’s core toolNode.js, Globals · MDN, AbortSignal.timeout()
Choosing timeouts and retriesBudgets, the false timeout rate, retries multiplying loadMarc Brooker, Timeouts, retries, and backoff with jitter
Cascading failures, deadlinesHow queues and waiting spreadGoogle SRE book, Addressing Cascading Failures
Edge vs. in-service latencyTo read the dashboardPart 1, Step 1

1. The concept: slow requests, queues, and “how many seconds should we wait?”

Many services, such as recommendation services, model servers, PDF generators and image processors, run with a fixed number of workers. If the workers are busy, a new request waits in a queue. This setup has a weakness: the queue grows not with the average request duration, but with how long the slowest requests hold a worker.

A sample calculation (with the lab’s numbers):

  • ~30 requests per second, 8 workers.
  • 90% of requests take 20 ms: 27 × 0.02 ≈ 0.5 workers is enough.
  • 10% take 8–20 seconds (~14 s on average): 3 × 14 ≈ 42 workers needed.

8 workers can’t do 42 workers’ worth of work. They all fill up with slow requests in no time, and the 20 ms requests queue up behind them. From this point on, what’s slow isn’t the model, it’s the queue.

So how long does the queue get? This is where the caller’s timeout comes in. If the only way a slow request releases its worker is the caller giving up and closing the connection, the caller’s timeout determines the length of the queue. A caller willing to wait 30 seconds has effectively ordered a 30-second queue.

Second question: what happens when the caller “gives up”?

                      after 250 ms, the caller...
Promise.race   ──►  stops waiting for the result; the HTTP request stays OPEN, the worker keeps working
AbortSignal    ──►  cancels the request; the connection closes, the service drops the work, the worker is free

Promise.race saves the page but not the service: the queue stays exactly the same, new requests still wait for seconds, and almost none of them finish within 250 ms.

See for yourself: a 50-line experiment

Before getting into the lab, seeing this on your own machine takes a minute. A single file holds both a 4-worker “recommendations service” (10% of requests take 3 s, the rest 20 ms; it drops the work when the client leaves) and a “product page” that calls it 40 times a second:

// budget.mjs: node budget.mjs <long|race|abort>
import http from 'node:http';
import { setTimeout as sleep } from 'node:timers/promises';

// --- "Recommendations service": 4 workers, 10% of requests take 3 seconds, the rest 20 ms ---
const WORKERS = 4;
let busy = 0, maxQueue = 0;
const queue = [];
const free = () => { busy--; queue.shift()?.(); };

http.createServer(async (req, res) => {
  let gone = false;
  res.on('close', () => { gone = !res.writableFinished; });
  if (busy >= WORKERS) {
    await new Promise((r) => queue.push(r));
    maxQueue = Math.max(maxQueue, queue.length + 1);
  }
  busy++;
  const ms = Math.random() < 0.1 ? 3000 : 20;
  for (let t = 0; t < ms && !gone; t += 10) await sleep(10); // drop the work when the client leaves
  if (!gone) res.end('[1,2,3,4]');
  free();
}).listen(3002);

// --- "Product page": 40 requests per second, for 15 seconds ---
const MODE = process.argv[2];
const url = 'http://localhost:3002/';
const waits = [];
let withRecs = 0, total = 0;

async function productPage() {
  const start = performance.now();
  let recs;
  try {
    if (MODE === 'long') recs = await (await fetch(url, { signal: AbortSignal.timeout(30_000) })).text();
    if (MODE === 'abort') recs = await (await fetch(url, { signal: AbortSignal.timeout(250) })).text();
    if (MODE === 'race') recs = await Promise.race([fetch(url).then((r) => r.text()), sleep(250)]);
  } catch {} // no recommendations, the page is shown anyway
  waits.push(performance.now() - start);
  total++;
  if (recs) withRecs++;
}

const timer = setInterval(productPage, 25);
await sleep(15_000);
clearInterval(timer);
await sleep(MODE === 'long' ? 20_000 : 500);
waits.sort((a, b) => a - b);
const p95 = waits[Math.floor(waits.length * 0.95)];
console.log(`${MODE.padEnd(5)}  page p95: ${p95.toFixed(0).padStart(5)} ms  pages with recs: ${((100 * withRecs) / total).toFixed(0).padStart(3)}%  longest queue: ${maxQueue}`);
process.exit(0);
for m in long race abort; do node budget.mjs $m; done

On my machine (Node.js 22.18) the result looks like this:

long   page p95: 23889 ms  pages with recs: 100%  longest queue: 444
race   page p95:   253 ms  pages with recs:   7%  longest queue: 426
abort  page p95:   251 ms  pages with recs:  90%  longest queue: 1

Read the three lines:

  1. long (30 s timeout): every page eventually gets its recommendations, but p95 is 24 seconds. 90% of the requests are 20 ms of work, yet the queue reaches 444. No customer waits 24 seconds.
  2. race (stop waiting after 250 ms): the page opens on time, but the queue is almost the same (426). The requests carry on in the background and the workers are still full; only 7% of pages get their recommendations in time.
  3. abort (cancel the request after 250 ms): the queue is 1. Slow requests hold a worker for at most 250 ms; fast requests don’t wait at all. 90% of pages get their recommendations: exactly the share that can be answered quickly.

Same service, same load, same 250 ms. The difference is whether the timeout cancels the request.


2. The incident: Friday evening, the busiest hour of the week

🔥 [FIRING] ClientsGivingUp: clients give up on more than 1 % of API requests before getting an answer (currently ~47 %)

Friday, December 4, 18:20. Since 17:10, product pages won’t load: browsers spin and then give up. Everything else works: listings, checkout, “My orders”. The strange part:

  • No 5xx at the edge, and in the API’s own latency panel product pages look normal.
  • Google Merchant Center has started flagging products as “Landing page unavailable”; the Shopping ads for those products have been paused.
  • Recent deploys:
VersionWhenChange
2.24.03 days agofeat(catalog): “Customers also bought” on product pages from the data team’s Recommendations service (previously: products from the same category)
2.23.11 week agofix(checkout): authorize the card before locking (the fix from Part 8)
  • The data team released model v7 of Recommendations today at 17:00. Their dashboards are green: inference p99 under 40 ms, no errors. They can’t roll back (v6’s data has been deleted), and recomputing what v7 is missing will take until tomorrow morning.
  • Recommendations belongs to the data team: you can read its code, but you can’t change it.

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 009

💡 Want to try it yourself first? Stop here, open Grafana (http://localhost:3000), and investigate on your own for 30 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 009. The symptom builds up in the first minute after traffic starts.


3. Investigation, step by step

Step 1: What does the edge say, and what does the API say?

“No 5xx” sounds like good news. Open the dashboard’s Requests per second by status and Latency measured by the API panels side by side.

What do we see?

At the edge, ~30 of ~63 requests per second are 499: the client closed the connection without waiting for the response. That’s ~47% of requests. 5xx really is zero; no request ends in an error, they just don’t end.

In the API’s own latency panel, on the other hand, /api/products/:id is barely visible. As far as it can be measured, its p95 is ~5 ms. But look at the Requests per second by route panel: the API finishes only ~1.5 product pages per second. ~35 product pages arrive per second. The ones that finish are served from the 60-second response cache; the rest never finish, so they’re never measured.

Grafana: on the left, requests at the edge by status; half of ~63 req/s is red 499, no 5xx; on the right, the API's per-route p95, with product pages on the floor after a 10 s peak in the first seconds

On the left: from 02:40 on, half the requests are 499 (the red area), but there isn’t a single 5xx. On the right: in the API’s own measurement, product pages (purple) are on the floor after the first half minute. The panel isn’t lying; it just can’t see requests that never finish.

Grafana: on the left, request rate by route, product pages only 1–2 req/s; on the right, active libuv resources in the API, with TCPSocketWrap rising from ~40 to ~1,150 and staying there

On the left: the product pages the API finishes (purple) are 1–2 per second, while ~35 per second arrive from the edge. On the right: the number of open TCP sockets climbs from ~40 to 1,100–1,200 while the request rate is steady. The API is waiting for something, thousands of times over.

Lesson: A histogram only counts finished work. “Latency is normal” and “half the requests never finish” can both be true at once. 499s at the edge (or client-side timeouts) are the signal that shows the gap.

Step 2: Who is the API waiting for?

A thousand open sockets are connected to something. Look at the Calls to other services panels.

The dependency

The API calls recommendations ~30 times per second; ~3 of those are error (calls that ended without a response). The calls’ p95 is 30 s: the panel’s top bucket, i.e. the API’s timeout. MailWave, PayFlow and TaxRate are as usual.

Grafana: on the left, calls to other services; recommendations 200 at ~27/s, recommendations error at ~3/s; on the right, call latency p95, with recommendations rising to 30 s and staying flat there while the other services sit on the floor

Recommendations calls (blue, on the right) climb to 30 s within a minute and stay there. The “error” line on the left is ~3 per second: calls that waited until the timeout and got no answer.

A product page trace in Jaeger (sampling is 20%; slow traces arrive a little late, because the call’s span stays open for up to 30 seconds):

Jaeger: a product page trace, 27.8 s in total; the traefik and API spans end at 10 s with a 499, and after two 8 ms queries the GET recommendations span lasts until 27.8 s, followed by one more query

The proxy’s and the API’s spans end at 10 s: the customer gave up (499). But the GET (the Recommendations call) that starts after two 8 ms queries lasts 27.8 s, and when the response arrives the API runs one more query and builds a page nobody will ever see.

Lesson: The product page is waiting for Recommendations. But Recommendations’ dashboard says “p99 < 40 ms”. How can both be true?

Step 3: Look at the dependency from the inside

Recommendations exports its own metrics to Prometheus (recs_*). In Grafana → Explore, look at: recs_workers, recs_workers_busy, recs_queue_length, and two histograms: recs_inference_duration_seconds (model computation time) and recs_request_duration_seconds (from the moment a request arrives until the response).

Recommendations from the inside
  • recs_workers = 8, recs_workers_busy = 8: every worker is busy at every moment.
  • recs_queue_length ~800–870: the number of requests waiting for a worker.
  • recs_inference_duration_seconds p99: 39 ms. What the dashboard says is true.
  • recs_request_duration_seconds p95: 29 s.

Grafana Explore: on the left, workers at 8 and busy workers flat at 8 from the first seconds on; on the right, the number of requests waiting for a worker climbs from 0 to ~850 by 02:41 and hovers there

On the left: all 8 of the 8 workers are busy a few seconds after the lab starts and never free up. On the right: the queue waiting for a worker reaches ~850 within a minute.

Grafana Explore: inference p99 rises to as much as 27 s in the first minute and drops to zero after 02:41:30; request duration p95 flat at 29 s

Yellow: the requests that got answered took ~29 s from arrival to response. Green: the computation time of those same requests is under 40 ms after 02:41:30. The green peak in the first minute is slow computations that managed to start and finish before the queue formed; once the queue settles in, no slow computation can finish, so none of them ever make it into the histogram.

The requests that did get answered spent 99.9% of their time waiting for a worker, not computing. And the slow computations don’t appear in these histograms at all: none of them get answered, because the API gives up at 30 s. The data team’s dashboard isn’t lying; like the API panel in Step 1, it only shows the work it finished.

Step 4: What’s holding the workers?

Which requests hold a worker for seconds? ./lab logs recommendations.

The logs

Recommendations logs: alternating "no precomputed vector for this product, computing it now" and "client went away, stopped computing" lines with afterMs ~30000; the two lines for product 12056 are highlighted

The two highlighted lines are the same product (12056): at 23:46:59.632, “no precomputed vector, computing it now”; 3.8 s later, “client went away, stopped computing”, afterMs: 29998. The request waited 26 s in the queue and computed for 4 s, and when the API gave up at the 30th second the work was left half done.

Two messages alternate:

  • no precomputed vector for this product, computing it now: products (~10%) whose vector v7’s nightly batch job failed to compute. For these, the vector is computed during the request: 8–20 seconds of a worker.
  • client went away, stopped computing, with afterMs always ~30,000: the API’s 30 s timeout closes the connection, and the service drops the work.

The counter in Prometheus says the same: recs_requests_total{outcome="cancelled_while_computing"} at ~3.2 per second; ok at ~27 per second.

The chain is complete:

  1. For ~10% of products, v7 computes the answer during the request: 8–20 s of a worker.
  2. ~3 of these arriving per second keeps all 8 workers permanently full.
  3. The 20 ms requests wait in the queue. The queue grows as far as the only thing that makes a slow request release its worker allows, namely the API’s 30 s timeout: ~28 s.
  4. The product page can’t be shown without Recommendations’ answer, so it waits 30 s. Customers and Googlebot give up at 10 s: 499.
  5. For every page nobody will see, the API holds a socket and a pending request: ~1,150 open sockets.

Step 5: The latest code

Now you know where to look:

// catalog/recommendations.ts (2.24.0)
// Generous on purpose: the data team's dashboard shows an inference p99 under 40 ms.
const TIMEOUT_MS = 30_000;

export async function customersAlsoBought(productId: number, limit: number): Promise<number[]> {
  const response = await callService(
    'recommendations',
    `${config.recommendationsUrl}/v1/products/${productId}/recommendations?limit=${limit}`,
    { signal: AbortSignal.timeout(TIMEOUT_MS) },
  );
  if (!response.ok) throw new Error(`Recommendations answered ${response.status}`);
  const { items } = (await response.json()) as { items: { productId: number }[] };
  return items.map((item) => item.productId);
}

// catalog/catalog.routes.ts
const [relatedIds, purchases] = await Promise.all([customersAlsoBought(product.id, 4), countPurchases(product.id)]);
const related = await listProductsByIds(relatedIds);

Two decisions, both of which looked “reasonable”:

  1. The timeout was chosen based on the dependency’s speed. “p99 is 40 ms, so 30 s is more than generous.” But the question shouldn’t have been “how long does Recommendations usually take?”, it should have been “how long can the product page wait, at most?”. The answer is a few hundred milliseconds.
  2. No fallback. If Recommendations doesn’t answer or returns an error, customersAlsoBought throws, Promise.all rejects, and the page becomes a 500. An optional box was put on the page’s critical path.

The irony: the timeout is already set up with an AbortSignal, i.e. the right mechanism; only its duration is wrong. The 30 s cancellation also explains why Recommendations’ queue settles at ~28 s. What if there had been no timeout at all? Node’s fetch (undici) waits 300 seconds for headers by default (undici, Client: headersTimeout). The queue would have been ten times longer, and the API’s open socket count ten times higher.

Submitting your diagnosis: the lab’s questions and answers (./lab submit 009)
QuestionAnswer
What are the product pages waiting for?The Recommendations service
Recommendations computes most answers in 40 ms. Why does every one of them take seconds?A few slow requests keep all its workers busy, and every other request queues behind them
Why does a recommendations problem take down the product pages?The page waits up to 30 s for them, and fails without them

4. Mitigation: stop the bleeding first

A proper fix needs a code change and a review. In the meantime, to rescue customers and Googlebot:

  • Take Recommendations off the page: a hotfix that shows “products from the same category” on every product page (the query from before 2.24.0 is still in the code). Product pages come back instantly. “Customers also bought” disappears everywhere, but that beats losing the product page.
  • Don’t retry, and don’t wait longer. Every extra request joins the queue, which is the problem itself.
  • Ask the data team for more workers, if they can add them. The slow requests need 25–60 workers; more workers shorten the queue, but don’t eliminate it.

5. The fix: a short leash for an optional feature

There are three parts:

  1. A timeout from the page’s budget. When healthy, Recommendations answers in ~20 ms; a product page should answer in a few hundred milliseconds. After 250 ms, the page goes on without it.
  2. A timeout that cancels the request. AbortSignal.timeout() cancels the request itself: the connection closes, and Recommendations stops working on a request nobody is waiting for anymore. Slow requests hold a worker for 250 ms instead of 30 s; the queue disappears.
  3. Fallback behavior. If there’s no answer in time, the page shows products from the same category, as before 2.24.0. A counter (recommendations_fallbacks_total{reason}) tells you how often this happens.
// catalog/recommendations.ts
// Recommendations are a nice-to-have: a product page must never wait long for them.
// Healthy, the service answers in ~20 ms; after 250 ms the page goes on without it.
const TIMEOUT_MS = 250;

const fallbacks = new Counter({
  name: 'recommendations_fallbacks_total',
  help: 'Product pages shown without "Customers also bought", because Recommendations failed or was too slow.',
  labelNames: ['reason'] as const,
  registers: [registry],
});

export async function customersAlsoBought(productId: number, limit: number): Promise<number[] | undefined> {
  try {
    // The signal aborts the request itself, not just our wait for it: the connection
    // closes, and Recommendations stops working on a request nobody needs anymore.
    const response = await callService(
      'recommendations',
      `${config.recommendationsUrl}/v1/products/${productId}/recommendations?limit=${limit}`,
      { signal: AbortSignal.timeout(TIMEOUT_MS) },
    );
    if (!response.ok) {
      await response.body?.cancel();
      throw new Error(`Recommendations answered ${response.status}`);
    }
    const { items } = (await response.json()) as { items: { productId: number }[] };
    return items.map((item) => item.productId);
  } catch (err) {
    fallbacks.inc({ reason: err instanceof Error && err.name === 'TimeoutError' ? 'timeout' : 'error' });
    logger.debug({ err, productId }, 'no recommendations, showing the page without them');
    return undefined;
  }
}
// catalog/catalog.routes.ts
const [relatedIds, purchases] = await Promise.all([customersAlsoBought(product.id, 4), countPurchases(product.id)]);
const related = relatedIds ? await listProductsByIds(relatedIds) : await listRelatedProducts(product);

A few details:

  • The error name is TimeoutError. When AbortSignal.timeout() fires, fetch rejects with a DOMException named TimeoutError; a manual controller.abort() call gives AbortError instead (MDN). The counter’s reason label relies on this difference.
  • response.body?.cancel(). Leaving the body of a non-200 response unread can keep the connection busy in undici until the body is consumed. Cancelling the body hands the connection back to the pool right away.
  • Budget ordering. The Recommendations call runs in parallel with countPurchases (Promise.all), while the fallback query runs only when needed and after the call. Worst case for the page: 250 ms + one ~8 ms query.
  • Caching. Product pages already sit in a 60-second response cache. A page shown with the fallback goes into the cache too; this is a deliberate trade-off: the same product stays without recommendations for a minute, but for that minute Recommendations isn’t called again for that product.

6. Verification

./lab deploy
./lab verify 009

verify runs Friday evening traffic for 60 seconds: ~66 req/s, ~35 of them per second product pages from shoppers and Googlebot. Clients give up after 10 s.

MetricTargetBeforeAfter
Product pages p95 (Googlebot)< 500 ms10.00 s (client gives up)271 ms
Error rate< 0.5%47.2%0%
Product pages without “Customers also bought”< 15%97.4%8.9%
Catalog p95 (listings and product pages)10.00 s82 ms
Checkout p95665 ms645 ms
Completed requests (60 s)3,5593,979
CPU0.23 cores0.25 cores
Event loop utilization26%28%
Event loop delay (max)158 ms159 ms

All the functional checks passed too: when Recommendations answers, the product page is exactly as before.

Note three rows:

  • CPU, event loop and checkout are the same. The API was never busy; it was just waiting. Anyone looking at the event loop or database panels in this incident would have seen nothing.
  • 97% of pages without recommendations in the “Before” column. Almost no page got its recommendations before the customer gave up; the 30 s wait set up to “protect” the feature had killed the feature too. The 8.9% still without recommendations after the fix are the products with missing vectors.
  • Completed requests. Before: 3,559 requests in 60 seconds: even the load generator filled up with hanging requests and couldn’t send some of its requests at all. After: 3,979 (~66/s), the full planned rate.

The graphs say the same thing. The second orange dashed line is the moment the fix was deployed (02:48:45):

Before and after the fix: on the left, the 499s (purple) disappear with the deploy and almost all of the ~66 req/s total is 200; on the right, the product page p95 measured by the API becomes visible for the first time after the deploy, at ~0.4 s

On the left: after the deploy, 499s are zero. The total request rate rises from ~63 to ~66, because every request now actually finishes. On the right: product pages (purple) show up in the API panel for the first time, p95 ~0.4 s. The 5 ms in the old panel that looked “normal” was only the pages served from the cache. For the short spike at 02:55:40, see the publishing notes.

Before and after the fix: on the left, requests finished by the API, with product pages rising from 1–2/s to ~35/s; on the right, open TCP sockets dropping from ~1,150 to ~40

On the left: product pages finished by the API (purple) go from 1–2 per second to ~35. On the right: open sockets go from ~1,150 to ~35–40. No pages waiting, no sockets waiting.

Before and after the fix: on the left, Recommendations calls on both sides of the deploy at ~27–30/s 200 and ~3/s error; on the right, call p95 drops from 30 s to the floor

On the right: call p95 drops from 30 s to 0.36 s. The “error” line on the left (dark green) is still ~3 per second after the deploy: products without vectors still get no answer. But now after 250 ms instead of 30 s; we didn’t touch Recommendations.

Grafana Explore, before and after the fix: on the left, busy workers drop from 8 to between 0 and 4; on the right, the queue goes from ~850 to zero

Inside Recommendations, deploy at 02:48:45: busy workers go from 8/8 to ~2 on average, and the queue from ~850 to zero. The service’s code, worker count and model are the same; what changed is how long we wait for it, and that the work we give up on is really dropped.

Grafana Explore: product pages finished by the API at ~35/s after 02:49; pages falling back (timeout) at ~3.2/s

After the deploy (02:48:45), ~34 product pages finish per second, ~3.2 of them (~9.4%) with the fallback behavior: products without a precomputed vector. This rate will stay until the data team computes the missing vectors; it’s their bug, but it’s no longer your outage.

Jaeger: a product page trace after the fix, 269 ms in total; the GET recommendations span is cut off with an error at 251 ms, followed by an 8 ms fallback query

The page of a product without a vector, after the fix: the Recommendations call is cut off at 251 ms (red exclamation mark), followed by the 8 ms “same category” query; the customer sees the page at 269 ms. The earlier trace was 27.8 s, and the customer saw nothing.


7. Fixes that look right but aren’t

AttemptWhy it’s not enough
Promise.race([call, sleep(250)])The page answers on time, but the request carries on. Recommendations keeps computing every slow request until the 30 s timeout and stays saturated; almost every call loses the race. In the demo: 7% of pages with recommendations. A “pages without recommendations” SLO catches this.
Short timeout, no fallbackThe slow 10% get a 500 after 250 ms instead of hanging. An error instead of a hang.
Fallback in place, timeout 30 sPages still wait 30 s before falling back. The customer is long gone.
A very short timeout (20 ms)Healthy responses get cut off too; pages lose their recommendations for nothing. The timeout has a budget too: comfortably above the dependency’s healthy p99, comfortably below the page’s budget.
RetryOne more request into the same queue. Never retry an optional feature on the critical path, especially after a timeout.
“Googlebot is too fast, let’s rate limit it”30 requests per second × 20 ms doesn’t fill even one of the 8 workers. What fills the workers isn’t volume but a few slow requests per second.
“More connections to Recommendations”The API isn’t limited by connections; a thousand are already open. The queue is inside Recommendations.

8. In production: alternatives and prevention

What you can add on top of this fix:

ApproachAssessment
Loading recommendations from the browser, after the page (a separate endpoint)The best design for an optional box: the product page never depends on Recommendations, and Googlebot never waits for it. A bigger change than tonight’s fix.
Circuit breakerStop calling Recommendations for a while when it’s completely down: pages don’t pay 250 ms every time, and the service gets room to recover (Martin Fowler, CircuitBreaker). Here 90% of requests still succeed; the breaker would rarely open.
A per-product recommendations cache (minutes to hours), serving the stale answer when slowFewer calls, and recommendations for recently seen products even during an outage.
Limiting concurrent calls (bulkhead)Caps what the API spends on a hanging dependency (sockets, memory, pending requests); beyond the limit it falls back immediately (Microsoft, Bulkhead pattern).
Propagating cancellationWhen the client gives up, also cancel the downstream calls it started (req.on('close') → AbortController). Before the fix, the API waited 30 s for pages nobody would see. The Google SRE book covers this under “cancellation propagation” and “deadline propagation”.

The smallest form of cancellation propagation in Express:

// When the client leaves, cancel everything this request started; the budget is at most 250 ms too.
const clientGone = new AbortController();
res.on('close', () => { if (!res.writableFinished) clientGone.abort(); });
const signal = AbortSignal.any([clientGone.signal, AbortSignal.timeout(250)]);

Alert on unfinished work, not on the symptom. In this incident, both the 5xx alert and the latency alert were silent. Two things carried the signal: the 499 rate at the edge, and the calls left unfinished per dependency.

- alert: ClientsGivingUp
  expr: |
    sum(rate(traefik_entrypoint_requests_total{entrypoint="web",code="499"}[5m]))
      / sum(rate(traefik_entrypoint_requests_total{entrypoint="web"}[5m])) > 0.01
  for: 3m
  labels:
    severity: page

- alert: DependencyCallsFailing
  expr: |
    sum by (peer) (rate(http_client_request_duration_seconds_count{job="api",status_code="error"}[5m]))
      / sum by (peer) (rate(http_client_request_duration_seconds_count{job="api"}[5m])) > 0.05
  for: 5m
  labels:
    severity: ticket

Code review checklist:

  • Does every external call have a timeout, and is that timeout derived from the caller’s budget? “The dependency usually answers in 20 ms” isn’t a budget.
  • Does the timeout really cancel the request (AbortSignal), or does it just stop waiting (Promise.race, setTimeout + a flag)?
  • Is the dependency critical or optional? If optional: what’s the fallback behavior, and is the “dependency is slow” case tested (not just “dependency is down”)?
  • Is there a retry after the timeout? If so, why?
  • Are fallbacks measured (a counter, a label)? An unmeasured fallback silently becomes permanent.

Look at the dependency from your side. The dependency’s own dashboard only shows the work it finished. On your side, measure latency, errors, timeouts and the number of calls still in flight per peer. And for the data team: measure queue time and worker utilization alongside inference time, and give the slow path a separate worker pool or its own deadline.


Key takeaways

  • Every external call’s timeout is derived from the caller’s budget, not from the callee’s usual speed. A “generous” 30 s timeout is an invitation to a 30 s queue.
  • A timeout must cancel the request. Promise.race saves the page, not the dependency.
  • If an optional feature sits on the critical path, its outage is your outage. Design a fallback behavior and measure it.
  • In a service with fixed workers, a few slow requests slow down the fast ones too: the queue grows with how long the slowest requests hold a worker.
  • Histograms only count finished work. “Latency is normal, no 5xx, the dependency’s dashboard is green” can all be true while half your customers are giving up. Look at 499s and open sockets.
  • Once again, the trigger (model v7) and the root cause (an optional call sitting on the critical path with the wrong budget and no fallback) are different.

Test yourself

1. Recommendations’ inference p99 is 39 ms and its request p95 is 29 s. How can both be true at the same time?

The inference histogram only counts the computation time of answered requests. The answered ones are the fast requests anyway (20 ms); they spent their time not computing but waiting for a worker (~29 s in the queue). The slow computations, on the other hand, were never answered (the API gave up at 30 s), so they’re in no histogram at all. “How fast a service computes” and “how long the caller waits” are separate measurements.

2. After the fix, ~3 Recommendations calls per second still end in “error”. Why isn’t that a problem anymore?

The error rate is the same, but the cost of an error changed. Before: each one took 30 s, held a worker for 30 s, kept the queue at ~850, and took the page down. After: it’s cut off at 250 ms, holds a worker for 250 ms (3/s × 0.25 s ≈ 0.75 workers; together with the fast requests, a measured average of ~2 busy workers), no queue forms, and the page is shown with products from the same category. The dependency’s problem isn’t solved; it just stopped being your outage.

3. Wouldn’t pages be even faster with a 20 ms timeout instead of 250 ms?

They would, but for nothing. When healthy, Recommendations answers in 5–30 ms; a 20 ms timeout also cuts off some of the healthy responses, and those pages lose their recommendations. A good timeout sits comfortably above the p99 (or p99.9) of the dependency’s healthy state, and comfortably below the page’s latency budget. That’s the approach in Brooker’s article too: choose an acceptable “false timeout” rate and take the percentile that corresponds to it.

4. The API has ~1,150 open sockets. Can you roughly calculate that number?

Little’s law: concurrent work = arrival rate × duration. ~30 product pages per second call Recommendations, and each call lasts ~28–30 s: 30 × ~29 ≈ ~870 open calls, each on its own socket. (The ~850 waiting + 8 in-progress requests on Recommendations’ side are the other end of these calls.) The product page connections from the proxy also stay open until the client gives up: ~30/s × 10 s ≈ ~300. Total ~1,170; the rest are a few dozen connections to the database and the other services. After the fix: 30 × 0.02 s + 3 × 0.25 s ≈ 1–2 concurrent calls to Recommendations; ~35–40 sockets in the panel.

Further reading

Basics

  • Marc Brooker, Timeouts, retries, and backoff with jitter (Amazon Builders’ Library): choosing a timeout from an acceptable false timeout rate and the dependency’s latency percentiles; how retries multiply load (243× with three retries at each of five layers), and why retries should happen at a single layer.
  • MDN, AbortSignal.timeout(): using it with fetch, and the difference between TimeoutError and AbortError.
  • Node.js, Globals: AbortController, AbortSignal.timeout() and the global fetch.

Deep dives

  • Google SRE book, Addressing Cascading Failures: the “Picking a deadline”, “Deadline propagation”, “Cancellation propagation”, “Queue Management” and “Retries” sections read like a sequel to this article.
  • undici, Client: the client underneath Node’s fetch; headersTimeout and bodyTimeout default to 300 s.
  • Microsoft, Bulkhead pattern: isolating the resources dedicated to a dependency; the example of an unresponsive service exhausting the caller’s connection pool.
  • Martin Fowler, CircuitBreaker: stopping calls after repeated failures; the pattern was popularized by Michael Nygard’s book Release It!.
  • Jeffrey Dean and Luiz André Barroso, The Tail at Scale (Communications of the ACM, 2013): why rare slowness becomes everyone’s problem in large systems.

Real-world incidents

  • Cloudflare, Cloudflare service outage June 12, 2025: an outage of part of Workers KV’s storage at a third-party provider took down dozens of products with a hard dependency on it; a kill switch for Turnstile, graceful degradation in Gateway, and the goal of every product surviving the loss of any single dependency.

Next up: Duplicate orders. Customers appear to have paid two, three, even four times for a single purchase; most of them say the app told them checkout had failed. The new mobile app automatically retries a checkout that takes longer than 2 seconds, with the same Idempotency-Key. It’s the flip side of this part’s “don’t retry after a timeout” warning: we’ll follow requests that time out but are actually still running, and what an idempotency key really needs to guarantee.

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