Ömer Faruk YILDIRIM
tutorials

Node.js Production Failure Lab · part 11

A Ten-Second Blip, an Outage That Won't End: Retry Storms and Metastable Failure

The tax provider has a ten-second failover and it's over; checkout, however, doesn't come back, and restarts change nothing. We trace step by step how retries multiplied across layers keep a dependency in permanent overload, how abandoned work eats its capacity, and the retry budget + jitter fix that breaks the loop.

32 min read90 min hands-oncode(opens in a new tab)

Node.js Production Failure Lab · Part 11 · Difficulty ★★★ · Reading ~25 min · Lab ~60–90 min

On the morning of Sunday, 20 September 2015, a brief network disruption hit DynamoDB in AWS’s US-East region (AWS’s incident summary). Normally it would have been the kind of hiccup nobody notices. But some storage servers’ requests to the metadata service — which tells them which data they are responsible for — took longer than the allowed time. The servers took themselves out of service and retried. The already-loaded metadata service slowed down even further; now routine requests from healthy servers timed out too, and they in turn dropped out and started retrying. The error rate climbed to 55% within 18 minutes and stayed there. Even adding capacity wasn’t possible, because the service was too busy to answer administrative requests. The loop was only broken at 05:06, when requests to the metadata service were paused; only then could the team add capacity and let requests back in. The total impact lasted almost five hours.

The network disruption had been short. What kept the system down for hours was the retry logic written to rescue it.

In this part we live through a small version of the same incident. The tax provider TaxRate has a ten-second database failover, and it’s over. Checkout, however, doesn’t come back. TaxRate says “everything is fine”, the on-call engineer restarts the API twice, nothing changes.

In Part 10 we saw how to make a retry safe: a retry carrying the same key must not create a new order. This part is the other side of the coin: even when a retry is safe, it isn’t free. Every retry is one more request in the dependency’s queue, and retries arrive in the greatest numbers exactly when the dependency is weakest.

What you’ll learn

  • What a metastable failure is: a self-reinforcing loop that keeps a system in a bad state after the trigger is gone
  • Retry amplification: how retries across layers multiply (app 4 × API 4 = 16)
  • Abandoned work: the server keeps computing after the client has given up, and its capacity goes into that
  • Reading a dependency’s insides through its own metrics: busy workers, queue length, a “nobody was waiting” counter
  • Why restarting the API changes nothing; recovering by shedding load
  • The fix: at most one retry, a retry budget (token bucket), full jitter, retrying only retryable errors. And why backoff alone isn’t enough

Prerequisites

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

TopicWhySource
Timeout, retry, jitterThe core tools of this articleMarc Brooker, Timeouts, retries, and backoff with jitter (Amazon Builders’ Library)
Retries under overloadRetry budget, “retry at a single layer”Google SRE book, Handling Overload
Metastable failureThe name and model of the incidentMarc Brooker, Metastability and Distributed Systems
Edge vs. in-service measurement, 499For reading the dashboardPart 1, Step 1 · Part 9, Step 1
Idempotent checkout, the app’s retriesBackground to the incidentPart 10

1. Concept: two stable states, one trigger

Picture a service that can do 2 jobs at a time, each job ~80 ms, so a capacity of ~25 jobs per second. 3 requests arrive per second. The service is 12% busy; the queue is empty and every request comes back in ~80 ms. This is the good state.

Now add the client’s rule: “If there’s no answer in 1 second, give up and ask again, up to 4 times.” And the server’s rule: “I finish the work I started, even if the client is gone.” Most servers behave like this, because they usually only notice that the client has left when they try to write the response.

Let the server slow down for ten seconds: each job takes 2–3 seconds. What happens?

  1. Every request times out after 1 s and the client asks again. 3 requests per second become 12 per second (in our incident there’s one more layer: 48).
  2. The server can’t finish even one job per second; the queue grows to hundreds of requests.
  3. The ten seconds end and the server does a job in 80 ms again. But there are hundreds of requests in the queue, and every one of their clients has long since given up. Every new request lands behind that pile, waits more than 1 s and also times out. The client asks again.
  4. As long as incoming load stays above capacity, the queue never drains. The server runs at full capacity and every response it produces goes in the bin.

Same traffic, same code, same server: but the system is now in the bad state, and it stays there. Failures like this are called metastable. The HotOS 2021 paper by Bronson and colleagues puts the definition like this: a trigger pushes the system into a bad state that persists even after the trigger is removed (Brooker’s summary). The key point: what sustains the bad state (retries, abandoned work) is not what pushed the system into it (the failover). Fixing the trigger — “let’s make TaxRate’s failover shorter” — changes nothing at the next hiccup.

Layers multiply

There are two layers that retry in our incident:

customer taps "Pay"
└─ mobile app: retry if no answer in 2 s or a 5xx comes back, 4 attempts
   └─ API: ask again if TaxRate doesn't answer in 1 s or returns an error, 4 attempts
      └─ TaxRate: 4 × 4 = 16 requests

Each layer looks reasonable on its own: “4 attempts, enough to ride out a hiccup.” But the layers don’t know about each other, and the attempts multiply. In the example from Brooker’s Builders’ Library article, if every layer of a five-layer stack tries 3 times, the database at the bottom sees 243 times the load.

See for yourself: a 45-line experiment

Before we get into the lab, you can see this in a single Node.js process. The server does 2 jobs at a time (40 ms each, so ~50 per second); the client sends 20 requests per second and gives up after 200 ms. Between second 2 and second 4, the server slows down:

// storm.mjs — node storm.mjs [attempts] [budget]
import http from 'node:http';

const ATTEMPTS = Number(process.argv[2] ?? 4);
const BUDGET = process.argv[3] === 'budget';
let busy = 0, slowUntil = 0, abandoned = 0;
const queue = [];

http.createServer(async (req, res) => {
  if (busy >= 2) await new Promise((r) => queue.push(r));
  busy++;
  await new Promise((r) => setTimeout(r, Date.now() < slowUntil ? 1000 : 40));
  busy--; queue.shift()?.();
  if (res.destroyed || req.socket.destroyed) { abandoned++; return; } // nobody is waiting
  res.end('ok');
}).listen(3011);

const agent = new http.Agent({ keepAlive: true, maxSockets: Infinity });
let sent = 0, ok = 0, failed = 0, tokens = 10;
const ask = () => new Promise((resolve) => {
  sent++;
  const req = http.get({ port: 3011, agent, timeout: 200 }, (res) => { res.resume(); res.on('end', () => resolve(true)); });
  req.on('timeout', () => { req.destroy(); resolve(false); });
  req.on('error', () => resolve(false));
});
async function call() {
  tokens = Math.min(10, tokens + 0.1);                // budget: every call earns 0.1 of a retry
  for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {
    if (await ask()) return ok++;
    if (BUDGET) { if (tokens < 1) break; tokens--; }  // a retry spends one whole token
  }
  failed++;
}

const start = Date.now();
setTimeout(() => { slowUntil = Date.now() + 2000; }, 2000);
const load = setInterval(call, 50);                  // 20 calls per second
const report = setInterval(() => {
  const t = Math.round((Date.now() - start) / 1000);
  console.log(`t=${String(t).padStart(2)}s  sent/s=${String(sent).padStart(3)}  ok=${String(ok).padStart(2)}  failed=${String(failed).padStart(2)}  queue=${String(queue.length).padStart(4)}  abandoned=${abandoned}`);
  sent = ok = failed = abandoned = 0;
  if (t >= 14) { clearInterval(load); clearInterval(report); setTimeout(() => process.exit(0), 300); }
}, 1000);

First with 4 attempts and no waiting (node storm.mjs 4). On my machine (Node.js 22.18):

t= 2s  sent/s= 19  ok=20  failed= 0  queue=   0  abandoned=0
t= 3s  sent/s= 56  ok= 0  failed= 4  queue=  54  abandoned=0
t= 4s  sent/s= 80  ok= 0  failed=20  queue= 132  abandoned=2
t= 5s  sent/s= 76  ok= 0  failed=19  queue= 160  abandoned=48
t= 6s  sent/s= 80  ok= 0  failed=20  queue= 191  abandoned=49
  ...
t=14s  sent/s= 80  ok= 0  failed=20  queue= 433  abandoned=50

Then with at most one retry, under a budget (node storm.mjs 2 budget):

t= 2s  sent/s= 20  ok=20  failed= 0  queue=   0  abandoned=0
t= 3s  sent/s= 26  ok= 1  failed=15  queue=  24  abandoned=0
t= 4s  sent/s= 22  ok= 0  failed=20  queue=  44  abandoned=2
t= 5s  sent/s= 22  ok= 0  failed=19  queue=  21  abandoned=45
t= 6s  sent/s= 20  ok=10  failed=14  queue=   0  abandoned=33
t= 7s  sent/s= 20  ok=19  failed= 0  queue=   0  abandoned=0
  ...
t=14s  sent/s= 19  ok=19  failed= 0  queue=   0  abandoned=0

Note three things:

  1. In the first run the slowdown ends at second 4, yet even at second 14 there isn’t a single successful response. The server finishes ~48 jobs per second (its entire capacity) and all of them are abandoned: nobody is left waiting for the response.
  2. Requests sent go from 20 per second to 80: 4 attempts, 4 times the load. With a capacity of 50, the queue grows by ~30 every second. (The demo’s queue is unbounded; TaxRate’s in the lab fills up at 1,000 and rejects the overflow with 503.)
  3. In the budgeted run, requests sent during the slowdown stay at 20–26. The budget runs out after a few retries, after which every call fails with a single attempt. When the slowdown ends, the queue drains in 2 seconds and the system returns to the good state on its own.

Same trigger, same capacity. The only thing that makes the difference is how much the client multiplies the load at the moment of failure.


2. The incident: Monday afternoon, 18 minutes after the failover

🔥 [FIRING] ApiHighErrorRate: more than 1 % of API requests are failing (currently ~7 %)

Monday, 14 December, 14:20. At 14:02 the database of the tax provider TaxRate failed over: for about ten seconds every tax quote took several seconds. The status pages say “Resolved”. Since then, checkout has been failing for everyone; browsing products works.

What’s strange:

  • TaxRate says it is fully operational. They are processing ShopFlow’s requests at the rate its plan allows. Their support team adds a note: ShopFlow is sending them “a lot of traffic”.
  • The on-call engineer restarted the API twice. Nothing changed.
  • Nobody deployed anything today. Recent changes:
VersionWhenChange
2.25.03 days agoRetry TaxRate quotes, so a hiccup at TaxRate doesn’t fail the payment
2.24.34 days agoPlacing an order is idempotent (the fix from Part 10)
  • The mobile app hasn’t changed either: since 5.2 it retries a payment attempt that takes longer than 2 s or returns a 5xx, up to 4 attempts.

If you have 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 011

In this lab, TaxRate’s database fails over every 5 minutes after the first minute of traffic; you can watch the incident begin, and you can also see your fix ride it out.

💡 Want to try it yourself first? Stop here, open Grafana (http://localhost:3000) and investigate on your own for 30 minutes. TaxRate’s own metrics are in Prometheus (taxrate_*). The results of the steps below are in collapsed boxes; open them when you get stuck. For the lab’s own hints: ./lab hint 011.


3. Investigation, step by step

The trap in this incident: we always look for something that is still broken. Here, no single part is broken. TaxRate is fast, the API is healthy. What’s broken is the loop between the two.

Step 1: Establish the scope

Look at the Requests per second by status and Latency measured by the API panels on the dashboard. What is not broken matters as much as what is.

What do we see?
  • Successful orders (201, yellow) are zero after 03:32. Two errors have taken their place: at the edge, ~6.9 499s per second (the app gives up after 2 s and closes the connection) and ~5.6 500s (the API uses up all four of its attempts and returns an error).
  • The browsing side (200, ~63 per second) is completely unaffected. Same picture per route: products, categories, order history are flat; only POST /api/orders p95 has shot up from ~750 ms before the failover to ~2.3 s.
  • The incident starts at 03:32: right on top of TaxRate’s failover (03:31:59–03:32:09). But it doesn’t end.

Grafana: on the left, edge requests by status; after 03:32 the 201s disappear and are replaced by 499 and 500, with a brief dip of 502s around 03:37:40; on the right, the API's per-route p95, /api/orders at ~2.3 s from 03:33

Browsing (green) is untouched; checkout never comes back after the failover. The dip and the brief 502s at 03:37:40 are the API restart: after the restart the picture is exactly the same.

Lesson: If only the path through a particular dependency is broken, narrow the search to your relationship with that dependency.

Step 2: How many requests go to TaxRate?

The Calls per second, by service and status panel counts the API’s calls to other services. Look at the TaxRate rows before and after the failover. How many checkouts are there per second?

What do the call counts say?
  • Before the failover: ~3 calls per second to TaxRate, all 200. 3 checkouts per second, 3 quotes.
  • During the failover: timeouts (taxrate error) shoot up to ~47 per second.
  • After 03:33: ~25 timeouts per second and 10–30 instant 503s. In total ~50 calls per second, none of them successful. There are still 3 checkouts per second.

50 / 3 ≈ 16–17 requests per checkout. At the edge there are ~12.4 payment attempts per second (499 + 500), i.e. ~4 quote requests per attempt.

Grafana: on the left, calls to other services; taxrate 200 drops to zero after the failover, taxrate error ~25/s and taxrate 503 10–30/s; on the right, the API's CPU at 0.25–0.3 cores

The purple taxrate 200 drops to zero at 03:32 and doesn’t come back. In its place, two kinds of error: timeouts (taxrate error, ~25/s) and queue full (taxrate 503). On the right, the API’s CPU is below 0.3 cores: the API isn’t short of anything.

Lesson: Compare the requests going to a dependency with the work that needs them. If “requests per checkout” has gone from 1 to 16, the problem isn’t the dependency’s speed, it’s how hard you’re leaning on it.

Step 3: Look inside TaxRate

TaxRate isn’t our service, but it publishes its own metrics. In Prometheus or Grafana Explore:

taxrate_workers_busy                                    # quotes being computed right now
taxrate_queue_length                                    # requests waiting in line
sum by (reason) (rate(taxrate_requests_total[15s]))     # ok, abandoned, queue_full
sum(rate(taxrate_requests_received_total[15s]))         # incoming requests
What is TaxRate busy with?
  • taxrate_workers = 2, taxrate_workers_busy = 2: full capacity.
  • taxrate_queue_length = ~1,000: the queue is full, and has been since 03:33.
  • reason="abandoned" at ~25 per second, reason="ok" at 0. TaxRate’s capacity is ~25 quotes per second and all of it goes on quotes whose client has long since left.
  • reason="queue_full": another ~25 requests per second get a 503 before they can even enter the queue.
  • Incoming requests: ~50 per second, twice the capacity.

TaxRate’s support team was right: they are fast and they really are getting “a lot of traffic”. But every quote they compute goes in the bin. This is the lab’s counterpart of the demo in section 1.

Grafana Explore: TaxRate's queue length rises from 0 at 03:32, reaches 1,000 at 03:33 and stays there; a brief dip at 03:37:40

The queue starts filling with the failover and hits the 1,000 limit within a minute. The failover ended at 03:32:09; the queue doesn’t care. The small dip at 03:37:40 is the API restart: full again within 20 seconds.

Grafana Explore: requests arriving at TaxRate at 35–55 per second, abandoned flat at ~25/s, queue_full 10–30/s, ok zero after the failover

The blue ok is ~3 per second before the failover and zero afterwards. The yellow abandoned is dead flat at ~25 per second: all of TaxRate’s capacity goes on quotes nobody is waiting for.

Lesson: “The dependency is slow” and “the dependency is busy” are different diagnoses. If you can see inside the dependency, look at how much of the work it produces actually gets used.

Step 4: The trace of a single checkout

In Jaeger, look at POST /api/orders traces for the shopflow-api service. How many POSTs go to TaxRate in one payment attempt, how far apart, and how do they end?

What does the trace show?

A single payment attempt (03:36:00):

  • Three short database queries (~25 ms).
  • Four POSTs to TaxRate, back to back, with no waiting at all: the first two time out at exactly 1.0 s, the last two get a 503 (queue full) in under 1 ms.
  • The edge (Traefik) closes the request at 2.0 s with a 499: the app gave up. The API’s retries carry on regardless.

The app will retry this attempt: at 0.5 s, 1 s and 2 s intervals, 4 times in total. Every attempt means 4 more requests to TaxRate.

Jaeger: POST /api/orders trace, 2.0 s; after three database queries, four POSTs to TaxRate: two at 1.0 s, two with 503 in under 1 ms; the Traefik spans are 499

Four POSTs one under the other: two timeouts, two instant 503s. No waiting between them; as soon as the first request fails, the second goes out. Traefik’s 499 shows the app giving up after 2 seconds.

Step 5: Separate the trigger from the restart

TaxRate’s logs (./lab logs taxrate) tell you when it broke and when it recovered.

How long did the trigger last?
database failover: quotes are slow   00:31:59Z   (03:31:59 local)
database failover complete           00:32:09Z

Ten seconds. The next failover comes 5 minutes later and again ends in 10 seconds; since the system is already in the bad state, it doesn’t even leave a mark on the graphs.

Terminal: ./lab logs taxrate output; "database failover: quotes are slow" at 00:31:59, "database failover complete" at 00:32:09, the same at 00:36:59 and 00:37:09

Every failover is exactly 10 seconds. The outage, however, has lasted since the first failover.

And the restart? I restarted the API at 03:37:37. The queue went down from 1,000 to ~960 and was full again within 20 seconds (the dip in the graph in Step 3); a few seconds of 502 were added at the edge. A restart kills the API’s in-flight retries, but the queue isn’t in the API, it’s in TaxRate. The new process’s first quotes also land behind those 1,000 requests, time out after 1 s, and the loop carries on where it left off.

Lesson: The trigger and the mechanism that sustains the loop are different things. If the outage lasts longer than the trigger, look for a feedback loop that keeps it going.

Step 6: Finally, the code

Now you know what to look for: a loop that calls TaxRate over and over.

// checkout/tax.ts (2.25.0)
// A quote normally takes well under 100 ms. If TaxRate doesn't answer within a
// second, or answers with an error, ask again: a blip at TaxRate shouldn't fail
// the customer's checkout.
const ATTEMPTS = 4;
const TIMEOUT_MS = 1_000;

export async function quoteTax(request: { country: string; amountCents: number }): Promise<TaxQuote> {
  let lastError: unknown;
  for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {
    try {
      const response = await callService('taxrate', new URL('/v1/quotes', config.taxrateUrl).href, {
        method: 'POST',
        /* ... */
        signal: AbortSignal.timeout(TIMEOUT_MS),
      });
      if (response.ok) return (await response.json()) as TaxQuote;
      lastError = new Error(`TaxRate responded ${response.status}: ${await response.text()}`);
    } catch (err) {
      lastError = err;
    }
  }
  throw lastError;
}

Four problems, all well-intentioned:

  1. 4 attempts, and inside the app’s 4 attempts at that: 16 requests.
  2. No waiting between attempts. A retry right after a timeout lands in the same full queue.
  3. Every error is retried: the queue-full 503 as well as a 400. When TaxRate says “I’m too busy”, the API immediately sends it another request.
  4. No limit. A retry that is rarely needed while TaxRate is healthy gets applied to every request once TaxRate is in trouble. The retry rate is highest exactly when it does the most damage.

The arithmetic: normally 3 quotes per second against TaxRate’s capacity of ~25 (12% busy). While quotes are failing, 3 × 16 = ~48 requests per second, twice the capacity. When the failover ends there are hundreds of requests in the queue; every new request waits more than 1 s, times out and is retried. As long as 48 > 25, the queue doesn’t drain.

The lab’s diagnosis questions and answers (./lab submit 011)
QuestionAnswer
TaxRate is healthy again. What keeps checkout down?Retries: every failing checkout sends TaxRate more requests than it can answer
What are TaxRate’s workers busy with?Quotes for requests the API already gave up on
While quotes are failing, how many requests can a single checkout send to TaxRate?16

4. Mitigation

The loop only breaks if the load on TaxRate drops below its capacity and stays there long enough for the queue to drain. There’s ~40 seconds of work in the queue.

  • Shed load for a minute: put checkout into maintenance mode for 60 seconds (a 503 with Retry-After at the edge, or a feature flag), then turn it back on. TaxRate’s queue drains, quotes are fast again and with normal traffic the system stays in the good state. Until the next hiccup. This was AWS’s solution in 2015 too: pausing requests to the metadata service.
  • Turn off the API’s retries, if there’s a switch for it. That’s the direction the permanent fix takes as well.
  • Don’t: restart the API (the queue is on the other side), shorten the timeout (giving up sooner means retrying sooner), or ask TaxRate for an emergency plan upgrade (it gets you out of this trigger, not the next bigger one).

5. The fix: retries that don’t multiply the load on failure

Neither the app nor TaxRate is ours. The only thing we can change is how hard the API leans on TaxRate.

// checkout/tax.ts (fix)
import { setTimeout as sleep } from 'node:timers/promises';

const TIMEOUT_MS = 1_000;
// A retry rescues a lost request; but while TaxRate is overloaded it adds one more
// request to its queue, behind the one we just gave up on. So: at most one retry,
// after a random wait, and only while retries stay below a tenth of the quotes
// requested.
const MAX_ATTEMPTS = 2;
const MAX_BACKOFF_MS = 250;

const retryBudget = {
  tokens: 10,
  earn() { this.tokens = Math.min(10, this.tokens + 0.1); },   // every quote earns 0.1 of a retry
  spend(): boolean {                                           // a retry spends one whole token
    if (this.tokens < 1) return false;
    this.tokens -= 1;
    return true;
  },
};

export async function quoteTax(request: { country: string; amountCents: number }): Promise<TaxQuote> {
  retryBudget.earn();
  for (let attempt = 1; ; attempt++) {
    const result = await askTaxRate(request);                  // { quote } or { error, retryable }
    if (result.quote) return result.quote;
    if (!result.retryable || attempt >= MAX_ATTEMPTS || !retryBudget.spend()) throw result.error;
    await sleep(Math.random() * MAX_BACKOFF_MS);               // full jitter
  }
}

async function askTaxRate(request: { country: string; amountCents: number }): Promise<Attempt> {
  try {
    const response = await callService('taxrate', /* ... */ { signal: AbortSignal.timeout(TIMEOUT_MS) });
    if (response.ok) return { quote: (await response.json()) as TaxQuote };
    // A 5xx may succeed on a second try; a request TaxRate rejected won't.
    const error = new Error(`TaxRate responded ${response.status}: ${await response.text()}`);
    return { error, retryable: response.status >= 500 };
  } catch (err) {
    return { error: err, retryable: true };                    // timeout, network error
  }
}

Four changes:

  1. At most one retry (2 attempts instead of 4).
  2. A retry budget (token bucket): every quote earns a tenth of a retry, every retry spends a whole one. While TaxRate is healthy, a request that gets lost now and then is still retried. Once every quote starts failing, the budget runs out within a few seconds and the API stops adding load on top of the app’s own retries: at most ~10% extra.
  3. Full jitter: a random wait of 0–250 ms before the retry. Retries from lots of checkouts don’t hit TaxRate at the same moment.
  4. Only retry what a retry can fix: timeouts, network errors, 5xx. A 4xx says the request itself is wrong; asking again won’t change the answer.

During a failover a checkout now generates 4–5 requests, not 16: the app’s attempts plus a few retries from the budget. For 3 checkouts per second that’s ~12–15 requests, below capacity (25). When the failover ends, the queue drains.

Why isn’t backoff enough?

The first fix that comes to mind is usually “let’s put an exponential wait between retries”. The lab’s solution notes measured this separately: with 4 attempts + exponential backoff + jitter, at the end of verify 98% of payments still fail, with a peak of 44 requests per second. Backoff spreads the same requests over time; it removes none of them: every checkout still sends 16 requests. To get out of the metastable state, the number of retries has to go down, not their timing. Jitter is still valuable: it stops retries from piling up in the same millisecond. But it’s no substitute for a budget.

6. Verification

I deployed the fix at 03:42:13. There were still 1,000 requests in the queue; I didn’t restart TaxRate or the app, and I didn’t put anything into maintenance mode. The fix had to break the loop on its own.

After the deploy, the API’s new requests were still landing behind the full queue and timing out. But now each failed quote meant not a retry but (once the budget was spent) zero retries: requests arriving at TaxRate fell from ~50 per second to 8–14, below capacity (~25). The queue drained at ~12 requests per second and went from 1,000 to 0 in 80 seconds (03:42:13 → 03:43:33). The first successful quote arrived at 03:43:35.

Before and after the fix: TaxRate's queue at 1,000 from 03:33 to 03:42; after the deploy (03:42:13) it drops to zero in 80 seconds; at the 03:47 failover it rises to 69 and is back to zero within 15 seconds

The queue drains by itself after the deploy; nobody restarted anything. The small bump at 03:47 is the first failover after the fix: the queue peaks at 69 and is empty 15 seconds after the failover ends.

Before and after the fix: requests to TaxRate drop from 35–60/s to 8–14/s after the deploy, then to ~3/s; abandoned drops to zero once the queue drains, ok returns to ~3/s

After 03:42, the yellow abandoned stays at ~25 until the queue drains (03:43:33); TaxRate is computing the old garbage. Then the blue ok returns to ~3 per second. At the 03:47 failover, incoming requests only rise to ~12.

The real test was the first failover after the fix (03:46:59–03:47:09). Two traces show how the budget works:

Jaeger: a checkout in the first seconds of the failover after the fix; two POSTs to TaxRate, the first times out at 1.0 s, the second after a ~100 ms jitter wait; the edge returns 499 at 2.0 s

03:47:02, 3 seconds into the failover. There are tokens in the budget: the first request times out at 1.0 s, and after a random wait of ~100 ms there is one retry. Two requests, not four.

Jaeger: another checkout two seconds later; a single POST to TaxRate, times out at 1.0 s and the API immediately returns 500

03:47:04, two seconds later. The budget is spent: a single request, a timeout at 1.0 s and an immediate 500. The checkout still fails, but without piling load onto TaxRate; the app will retry a few seconds later, and by then TaxRate will be ready.

The dashboard tells the same story. The orange dashed lines are the start of the lab (03:31) and the deploy (03:42:13):

Before and after the fix: 499s and 500s at the edge disappear ~1.5 minutes after the deploy and 201s come back; /api/orders p95 drops from 2.3–2.5 s to ~750 ms, with a brief spike at 03:47

The yellow 201s come back around 03:43:30, and the 03:47 failover leaves only a brief bump of 499/500. On the right, /api/orders p95 returns to its pre-failover ~750 ms; the sharp peak at 03:47 is the failover itself, followed by an immediate drop.

Before and after the fix: TaxRate calls after the deploy first drop to 10–15/s of timeouts, then to ~3/s of successful calls; a brief bump of ~8/s timeouts at 03:47; CPU at ~0.25 cores throughout

The purple taxrate 200 comes back at 03:43:30. In the 03:47 failover, timeouts rise to ~8 per second and fall back, whereas in the failover before the fix they had reached ~47. CPU doesn’t change: the fix didn’t take load off the API, it gave TaxRate room to breathe.

Finally, the lab’s own verification:

./lab verify 011

verify runs the standard traffic (~66 requests/s, 3 checkouts per second) for 60 seconds and slows TaxRate down for 10 seconds at second 10. It measured the original code first, then the fix:

MeasurementTargetBeforeAfter
Failed checkouts after TaxRate recovers (last 20 s)< 1%98.4%0%
Requests per second to TaxRate (peak, 15 s average)< 204910.2
CPU0.24 cores0.26 cores
Event loop delay (max)162 ms126 ms

The API’s own metrics barely changed; what changed is what the API asks of TaxRate. The fix didn’t make the API faster; it stopped the API from drowning its dependency.


7. Fixes that look right but aren’t

AttemptWhy it falls short
Restarting the APIThe queue is in TaxRate. The new process’s requests also land behind 1,000 requests; the queue is full again within 20 seconds.
4 attempts + exponential backoff + jitterMeasured: 98% failure, a peak of 44 requests per second. Backoff spreads requests over time; it doesn’t reduce their number.
A shorter timeoutGiving up sooner means retrying sooner: more requests against the same capacity.
A longer timeout, same retriesFewer timeouts at first, but once the queue holds more work than the timeout, every checkout is back to 16 requests. It moves the tipping point; it doesn’t remove it.
A bigger pool, more CPUThe API isn’t short of anything; CPU is below 0.3 cores.
A bigger plan from TaxRateGets you out of this trigger; the next, bigger one starts the same loop. The problem isn’t 25 per second, it’s 16 per checkout.

Removing the retries altogether also passes verify: the app’s own retries cover the occasional lost request. A legitimate fix. The budget keeps the benefit of a retry while TaxRate is healthy.

8. In production: alternatives and prevention

Complementary mechanisms:

ApproachWhen
Circuit breakerAfter consecutive errors, don’t call TaxRate at all for a few seconds, fail fast, then probe with a few requests. Protects TaxRate even from the app’s retries, and spares checkouts from waiting out a timeout. Complements the budget. Downside: modal behaviour, hard to test.
Retrying at a single layerIf both the app and the API retry, attempts multiply. Agree on which layer retries (usually the outermost); the others steer with Retry-After. The Google SRE book says the same: only the layer immediately above the one rejecting should retry.
503 + Retry-After when tax can’t be computedTells the app to wait before the next attempt; a bare 500 gets retried immediately.
Deadline propagationPassing the remaining time to the other side (in a header); the server can drop an expired request instead of computing it. TaxRate isn’t ours, but our own services should do this for each other.
Adaptive concurrency limitLimiting the API’s in-flight requests to TaxRate and lowering the limit as latency rises (like TCP congestion control).

Alert on the mechanism, not the symptom. Retry amplification is measurable: requests to the dependency ÷ requests that need it.

- alert: RetryAmplification
  expr: |
    sum(rate(http_client_request_duration_seconds_count{peer="taxrate"}[1m]))
      / sum(rate(http_server_request_duration_seconds_count{route="/api/orders", method="POST"}[1m]))
    > 1.5
  for: 2m
  labels:
    severity: page

This query gave 8.9 during the incident and 1.1 after the fix. (The real ratio is ~4 per attempt: the API doesn’t record the 499 attempts the app gave up on in its own counter, so the denominator stays small. The threshold still does its job.)

Code review checklist (for every retry loop):

  • How many attempts? Who else retries above and below this layer? What’s the product?
  • Is there a random wait between attempts?
  • Does a budget or a circuit breaker cut off retries when the dependency breaks?
  • Which errors are retried? 4xx and “I’m too busy” (503, 429) should get different treatment.
  • Does the other side keep working after a timeout? If so, every timeout + retry is two jobs for it.
  • Is the retry loop hand-written? A single shared HTTP client policy per dependency (timeout, at most 1–2 retries, jitter, budget, list of retryable errors) is safer.

Load-test with a slow dependency. The retries had been tested against a dependency that returns errors, and they worked there. They were never tested against a slow dependency; that’s where they turn into load. The test should verify that the system recovers on its own after the slowdown ends. That is exactly what the lab’s verify step does.

Know your dependencies’ limits. The TaxRate plan allows 2 quotes at a time. The worst-case load you can send (attempt product × traffic) should stay below that limit.


Key takeaways

  • If the system doesn’t recover even though the trigger is over, look for a feedback loop keeping it in the bad state: retries, abandoned work, full queues.
  • Retries across layers multiply. 4 × 4 = 16, and that multiplication kicks in exactly when the dependency is weakest.
  • A request that timed out is often still being processed on the other side. Timeout + retry means two jobs for the other side.
  • A retry budget makes retries plentiful in healthy times and scarce in bad times. Backoff alone spreads requests over time; it doesn’t reduce their number.
  • A restart doesn’t help if the queue is on the other side. The emergency way out of a metastable state is shedding load.
  • A provider saying “everything’s fine, but you’re sending us a lot of traffic” is handing you the diagnosis.

Test yourself

1. TaxRate’s failover lasted 10 seconds. Why didn’t the outage end after 10 seconds?

During the failover, the queue filled up with hundreds of requests whose clients had long since given up. When the failover ended, every new request waited more than 1 s behind that pile, timed out and was retried. As long as incoming load (~50/s) stayed above capacity (~25/s), the queue didn’t drain. What sustained the bad state wasn’t the failover but the retries and the abandoned work: a metastable failure.

2. The on-call engineer restarted the API twice. Why didn’t that help?

The queue isn’t in the API, it’s in TaxRate. The restart killed the API’s in-flight retries, but TaxRate’s queue still held ~1,000 requests. The new process’s first quotes landed behind them and timed out, and the loop carried on where it left off within 20 seconds.

3. Why isn’t adding exponential backoff between retries enough?

Backoff spreads the same number of requests over a longer time. Every checkout still sends 16 requests; measured: 98% failure, a peak of 44 requests per second. To break the loop, incoming load has to drop below capacity, i.e. the number of retries has to go down. That’s what a budget does (or removing the retry, or a circuit breaker).

4. Which metric catches a retry storm against a dependency early?

The retry ratio: requests to the dependency ÷ requests that need it (for example, TaxRate calls ÷ payment attempts). Normally ~1; going above 1.5 for a few minutes shows amplification has started. If the dependency has its own metrics, the abandoned-work rate (abandoned) is a strong signal as well.

Further reading

Basics

  • Marc Brooker, Timeouts, retries, and backoff with jitter (Amazon Builders’ Library): 5 layers × 3 retries = 243 times the load, “retry at a single point”, a local retry limit with a token bucket, jitter.
  • Google SRE book, Handling Overload: 3 attempts per request, a per-client budget of “retries below 10% of requests”, retrying only at the layer directly above.
  • Google SRE book, Addressing Cascading Failures: how retries keep a system overloaded, randomized exponential backoff, and getting out of a death spiral by cutting load hard and restoring it gradually.

Deep dives

Real-world incidents


Next up: Errors on every deploy. After Monday, the platform team made deploys safe: the API runs as two replicas, deploys replace the replicas one at a time, and the proxy probes each replica’s /ready every 2 seconds. The promise was zero downtime; yet on every deploy hundreds of requests fail with 502. The code’s “graceful shutdown” has been there since the first version. We’ll see what a replica gets wrong as it shuts down, and the recipe for zero errors in a rolling deploy (announce, drain, close).

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