MF Marcus Feld

Reliability · 11 min read

Design for the unhappy path

Timeouts, retries, idempotency and the quiet arithmetic of partial failure. This is the part of the system that decides whether you sleep tonight.

At 3:12 a.m. the alert fired: checkout error rate at 34%. By 3:20 the database was at full connection saturation and four other services were failing, none of which had anything to do with the original problem. The root cause, when we found it, was a single payment provider returning 503 for eleven minutes.

The system had retries. That was the problem. Three retries, at every layer, with no budget and no jitter, and a shared connection pool. One slow dependency became a self-inflicted denial of service, and the retry logic that existed to make the system resilient was the mechanism that took it down.

I have now seen this pattern at six companies. The details differ, the arithmetic does not.

A timeout is a design parameter, not a default

Most HTTP clients default to no timeout at all, or thirty seconds, which in a request-scoped system is the same thing as infinity. A request that hangs is worse than a request that fails: it consumes a worker, a connection, and a slot in every queue behind it, and it produces no error signal until something upstream gives up.

Timeouts should be allocated top-down, from a budget you can state out loud. For a checkout request with a two-second budget:

LayerDeadlineWhy
Edge / gateway1900 msCheckout must never hold a user longer than this.
Order service1500 msLeaves room for the response to be serialised and returned.
Payment call600 msProvider p99 is 380 ms; beyond 600 ms it is not coming back.
Fraud check250 msAdvisory only. Failure here degrades, it does not block.

Two rules make budgets work. Every downstream call receives the remaining budget, not a fresh one — that is what a deadline is for. And a timeout must be shorter than the caller's timeout, or the caller will have given up before the callee knows it should stop.

A timeout you cannot justify in milliseconds is a timeout you set by accident.

Retries multiply

Retries are not additive, they are exponential in the number of layers that implement them. With one retry at three layers, a single user request can produce eight calls to the same dependency. With three retries at four layers, eighty-one.

amplification = (retries + 1) ^ layers

# 3 retries at 2 layers, 1,000 requests/second
(3 + 1) ^ 2 = 16  →  16,000 requests/second
# the dependency is now down, and will stay down until traffic stops

So: retry at exactly one layer, the one that owns the user's outcome. Everywhere else, fail fast and let the caller decide. Add exponential backoff with full jitter, or every client in the fleet will retry in the same millisecond and rebuild the thundering herd you were trying to avoid.

import random, time

def call_with_budget(fn, budget_ms, max_attempts=3):
    deadline = time.monotonic() + budget_ms / 1000
    for attempt in range(1, max_attempts + 1):
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            raise TimeoutError("budget exhausted")
        try:
            # never give a single attempt more than the remaining budget
            return fn(timeout=min(remaining, 0.5))
        except TransientError:
            if attempt == max_attempts:
                raise
            ceiling = min(0.1 * (2 ** attempt), remaining)
            time.sleep(random.uniform(0, ceiling))  # full jitter

The remaining check is the part people skip. Retrying after the deadline has passed does not improve the user's outcome; it only adds load to a system that is already struggling.

Idempotency is the only real fix

Retries are safe only if repeating an operation is harmless. For reads it usually is. For writes it almost never is, and that is where the money is: double charges, duplicate shipments, two confirmation emails.

The mechanism is boring and it works. The client generates a key per logical operation, not per attempt. The server records the key and the response, and replays the stored response for any repeat.

-- first attempt inserts, replays return zero rows
INSERT INTO idempotency_keys (key, request_hash, created_at)
VALUES ($1, $2, now())
ON CONFLICT (key) DO NOTHING
RETURNING key;

-- if no row came back: this is a replay.
-- compare request_hash; if it differs, reject with 409.

Two details decide whether this survives production. Keys need a retention policy tied to your retry window plus your longest batch job — ninety days is a common answer, not forever. And the key must be stored in the same transaction as the effect, or you have recreated the problem one layer down.

Partial failure, and the fallback that lies

Fallbacks are where honest systems stop being honest. A cached price from four hours ago, a recommendation list from last week, an empty array returned because the service was unreachable — all of these look identical to a correct answer unless you label them.

My rule: a degraded response must carry its own degradation. A timestamp on the cache, a boolean on the payload, a header on the request, a banner in the UI. If the fallback is indistinguishable from the truth, someone will make a decision on it, and that decision will be wrong in a way that takes a week to trace.

And some things should have no fallback at all. Showing an approximate order total is a bad idea. Charging a card with an approximate total is a lawsuit.

What to measure

  • Latency at p99, per dependency. The average will tell you the system is fine while one in a hundred users waits six seconds.
  • Saturation, not just utilisation. Queue depth and connection pool occupancy predict outages hours before error rates move.
  • Retry rate. If you do not know how many retries are happening, you do not know your real traffic. It is usually 2–4× what the dashboard says.
  • Time to detect. Not time to fix. Detection is the number that determines how much of the incident your customers experience.

The checklist I actually use

  1. Every outbound call has an explicit timeout derived from a budget.
  2. Exactly one layer retries, with jitter, within the deadline.
  3. Every write that a user can trigger has an idempotency key.
  4. Every fallback is labelled as a fallback in the response.
  5. Load shedding exists and has been tested, not just configured.

None of this is novel, and that is the point. The systems that stay up are not the ones with the most sophisticated failure handling. They are the ones where someone wrote down the budget, made the retries boring, and refused to let a fallback pretend to be the truth.

The payment provider in that 3 a.m. incident returned to normal in eleven minutes. Our outage lasted four hours, because the recovery was blocked by our own retry queues. The provider was never the problem. We were.


MF

Marcus FeldIndependent software architect in Berlin. I review systems, embed with engineering teams, and write down what breaks. More about my work.