Designing for Failure (How Distributed Systems Keep Serving Users When Components Break) | PulseSoft
Skip to content

Designing for Failure (How Distributed Systems Keep Serving Users When Components Break)

PulseSoft Team · · 13 min read

Consider a checkout service whose database is not down, only slow. Query latency at the 99th percentile climbs from 15 milliseconds to 900 milliseconds, no health check fails, and within minutes the checkout service stops responding entirely. A dependency that was still answering every query has taken down a service that never crashed.

This is the core problem that designing for failure addresses. The failures that hurt distributed systems are rarely clean. A crashed process is easy to detect and route around. A slow, flaky, or half-working component is not, because the system keeps trusting it while it quietly consumes threads, connections, memory, and retry capacity.

The underlying principle is partial failure: in a distributed system, some components work while others do not, and a caller often cannot tell which. This article explains how to reason about partial failure from first principles, how failures propagate and correlate, how to design explicit degraded modes and recovery paths, and which tradeoffs each technique introduces. The goal is not a checklist of resilience patterns. It is a way of thinking in which failure is a normal operating condition the architecture is designed around.

Why Partial Failure Breaks the Assumptions in Your Code

A local function call has two outcomes: it returns, or it throws. A network call has a third: the caller does not know what happened. The request may have been lost before arrival, processed with the response lost, or still be executing. Every remote call carries this ambiguity, and most application code is written as if it did not exist.

Several assumptions hide inside ordinary service code:

  • A dependency is either available or unavailable.
  • A request that timed out did not take effect.
  • Requests arrive in the order they were sent.
  • Failures of different components are independent.
  • Recovery happens automatically once the cause is removed.

Each of these is false often enough to matter.

The causal chain of a slow dependency

Return to the checkout example. The API service handles 1,000 requests per second, and each request holds a database connection for the duration of its queries. Little's Law (concurrency equals arrival rate multiplied by time in the system) makes the consequence precise. At 50 ms per request, the service needs roughly 50 concurrent requests in flight. At 2 seconds per request, it needs roughly 2,000.

Nothing about the incoming traffic changed. Only latency changed, and latency converts directly into concurrency. The chain looks like this:

slow dependency
  -> requests hold connections and threads longer
  -> connection pool exhausted, requests queue for a connection
  -> latency rises for ALL requests, including ones that never touch the slow query
  -> clients hit their timeouts
  -> clients retry
  -> arrival rate increases while capacity is already saturated
  -> further degradation

Two details make this worse. First, timeouts do not cancel work on the server. A client that gives up after one second leaves the server still executing a request whose result nobody will read, so the system spends capacity on abandoned work. Second, a retried request that "failed" may have succeeded. If the first attempt committed an order and the response was lost, the retry creates a duplicate. Retries turn an availability problem into a correctness problem unless operations are idempotent.

Why distribution and growth make this inevitable

As component count grows, the probability that something is broken approaches certainty. If a request path touches 50 independent dependencies, each healthy 99.9% of the time, the chance that all of them are healthy at a given moment is about 95%. At sufficient scale, "everything working" is the exception. That is the practical meaning of treating failure as a normal operating condition: the system's steady state includes broken parts.

Fault Tolerance in Distributed Systems: Modeling, Containing, and Correlating Failure

Model failure as a set of behaviors, not a single event

The mental model that matters is a failure taxonomy, because each kind of failure demands a different response.

  • Crash failures: the component stops. These are the easiest case; timeouts and health checks detect them, and load balancers route around them.
  • Omission failures: messages are dropped. The sender sees silence, which is indistinguishable from slowness.
  • Timing failures: the component responds, but too slowly to be useful. A correct answer that arrives after the caller's deadline is functionally a failure that consumed resources.
  • Gray failures: the component appears healthy to its health check but is broken for real traffic. A process that answers /health while its disk is failing or its thread pool is wedged is the canonical example. The term comes from research describing how differential observability (the monitor and the application seeing different things) lets these failures persist.

Failure detection in an asynchronous network is always a guess. A timeout does not prove a remote node is dead; it proves the caller stopped waiting. Every timeout value is therefore a policy decision that trades false positives (declaring a slow node dead) against detection latency (waiting too long on a dead one). Setting timeouts from observed latency percentiles of the dependency, rather than round numbers, makes that tradeoff explicit.

Contain failure with bounded resources

The checkout collapse happened because a single slow dependency could consume an unbounded share of shared resources. Containment means bounding how much damage any one dependency can do.

Deadlines should propagate across calls, not be set independently at each hop. If the client allows 1 second and the API has used 700 ms, the downstream call has 300 ms remaining. Starting a fresh 1-second timeout downstream guarantees wasted work.

Bulkheads give each dependency its own bounded pool of concurrency. When the recommendation service slows down, it exhausts its own 50 slots, not the connection pool that order writes depend on. The tradeoff is utilization: partitioned capacity sits idle that a shared pool could have used.

Load shedding rejects work early when capacity is exhausted. A queue in front of saturated capacity does not add throughput; it adds latency. Rejecting a request in 1 ms is better for the system than accepting it and timing out after 2 seconds, because the rejection costs almost nothing and the timeout consumed capacity the whole time.

Circuit breakers stop calling a dependency after a failure threshold, fail immediately for a period, then probe for recovery. They protect the caller's resources and give the dependency room to recover. They also introduce new risks: a breaker tuned too aggressively turns a brief blip into a minutes-long outage, and breakers on many instances trip and close in their own uncoordinated rhythms.

Here is the containment logic for an optional dependency, expressed in Go:

// Recommendations are optional: bounded concurrency, short deadline, empty fallback.
var recsSlots = make(chan struct{}, 50)

func recommendations(ctx context.Context, userID string) []Product {
	select {
	case recsSlots <- struct{}{}:
		defer func() { <-recsSlots }()
	default:
		// Bulkhead full: shed immediately instead of queueing behind a slow dependency.
		metrics.Inc("recs.shed")
		return nil
	}

	// WithTimeout respects the parent deadline, so this never exceeds the caller's budget.
	ctx, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
	defer cancel()

	items, err := recsClient.Get(ctx, userID)
	if err != nil {
		metrics.Inc("recs.degraded")
		return nil // The page renders without recommendations.
	}
	return items
}

The interesting part is not the syntax. It is the decision encoded in the code: this dependency is not allowed to make checkout slower than 80 ms, and its absence is an acceptable product state.

Retries are a load multiplier

Retries exist because many failures are transient. They help when failures are random and capacity is available. They hurt when failures come from overload, because they increase load at exactly the moment the system has none to spare.

Amplification compounds across layers. If three layers each make up to four attempts, a single user request can produce up to 64 attempts at the bottom of the stack. A dependency at 80% capacity that starts failing can see its load multiply just as it degrades.

Three mechanisms keep retries safe. Exponential backoff with jitter spreads retries in time so clients do not synchronize. Retry budgets cap retries as a fraction of total traffic (for example, retries may not exceed 10% of requests) so retries cannot dominate during an outage. Retrying at only one layer prevents multiplicative amplification. Underneath all three, operations must be idempotent: an idempotency key stored with the result lets a server recognize a duplicate and return the original outcome instead of executing twice.

Correlated failures and metastable states

Redundancy calculations assume independent failures. Two replicas at 99.9% availability each yield 99.9999% only if they never fail together. In practice, replicas share far more than the math admits: the same binary, the same configuration push, the same certificate expiry, the same DNS, the same upstream dependency, the same availability zone, and the same traffic spike.

A useful exercise is to list what every "redundant" copy shares. That list is the system's correlated failure surface. A bad configuration deployed to every region at once defeats multi-region redundancy completely; staged rollouts exist to reintroduce independence that the deployment pipeline removed.

The most dangerous correlated failures are self-sustaining. Research on metastable failures describes systems that enter a bad state due to a trigger, such as a brief latency spike, and then stay there after the trigger is gone. Retries keep load above capacity. A cache that was flushed causes every request to hit the database, which slows down, which prevents the cache from refilling. The system has two stable states, healthy and collapsed, and the collapsed one persists. Recovery requires breaking the feedback loop deliberately by shedding load, disabling retries, or admitting traffic gradually, not waiting for the root cause to clear.

Enjoying this so far?

Join thousands of engineers receiving practical engineering, Cloud, Distributed Systems, Infrastructure and AI engineering insights.

No spam. Unsubscribe anytime.

Architecture: A Checkout System With Explicit Degraded Modes

Consider a hypothetical e-commerce checkout. The design starts not with services but with a question: which dependencies are required to take an order, and which only improve the experience?

Client
  |
  v
Load Balancer
  |
  v
Checkout API ----------------------------------+
  |        |            |            |         |
  v        v            v            v         v
Orders   Inventory   Pricing      Payment    Recommendations
  DB     Service     Cache        Provider   Service
  |                     |         (external)  (optional)
  |                     v
  |                  Pricing DB
  v
Outbox table --> Relay --> Event Stream --> Workers
                                           (email, fulfillment, analytics)

Classifying dependencies

DependencyRoleBehavior when slow or unavailable
Orders DBSource of truth for ordersCritical. Fail fast with a clear error; never accept an order that cannot be recorded.
Payment providerAuthorizationCritical, but ambiguous outcomes are possible. Use idempotency keys; reconcile unknown results asynchronously.
Inventory serviceStock checkDegradable. Accept the order against a slightly stale count and resolve oversell during fulfillment, if the business accepts that risk.
Pricing cacheFast price lookupDegradable. Serve last known price within a bounded staleness window; fall back to the pricing DB under a strict concurrency limit.
RecommendationsCross-sellOptional. Omit from the response.
Event streamDownstream notificationsDecoupled. Checkout does not wait for it.

State ownership and consistency boundaries

The orders database owns order state. Everything downstream is derived. Writing to the database and publishing to the event stream as two separate operations creates a dual-write problem: a crash between them leaves the two inconsistent. The outbox pattern writes the order and its event in a single local transaction; a relay publishes events afterward. Delivery becomes at-least-once, so workers must deduplicate, but the invariant holds: no event exists for an order that was not committed, and no committed order loses its event.

The payment provider is the hardest boundary because it is outside the system's control. If the authorization call times out, the checkout service does not know whether the customer was charged. The correct response is not to retry blindly or to fail the order silently, but to record the attempt as pending, reuse the same idempotency key on any retry, and let a reconciliation process query the provider for the true outcome.

Recovery paths

Recovery is a design concern, not an operational afterthought. When the event stream recovers after an outage, a backlog of outbox events drains. If workers process it at full speed, they can overload the email provider or fulfillment system they call. Rate-limited draining turns a recovery spike into a controlled ramp. Similarly, a restarted cache should be warmed or admitted gradually, because a cold cache in front of a database sized for cache hits is a metastable failure waiting for a trigger.

Tradeoffs: Choosing How Each Component Should Fail

Graceful degradation is not free. Every degraded mode is a code path that runs rarely, which means it is tested rarely, and it changes the product's guarantees.

DecisionWhen it makes senseWhat it makes harder
Fail fastCritical dependencies where a wrong answer is worse than no answer (payments, order writes)Users see errors during transient blips that a retry would have absorbed
Retry with backoffTransient faults on idempotent operations with spare capacityAmplifies overload; requires idempotency; increases tail latency
Serve stale dataRead paths where bounded staleness is acceptable (prices, catalog, feeds)Defining and enforcing the staleness bound; explaining it to the business
Asynchronous processingWork that does not need to complete before respondingConsumer lag, ordering, duplicate handling, and a new "pending" state users can observe
Static stability (precomputed state that keeps working without its control plane)Systems where control-plane outages must not affect the data planeData can become stale; more state to distribute and version
Active redundancyComponents whose loss would halt critical pathsCost, coordination, and a false sense of safety if failures are correlated

Two observations cut across the table. First, most of these techniques move complexity rather than remove it. Asynchronous processing removes a timing dependency and creates a state-management problem. Caching removes database load and creates a freshness problem. The design question is where that complexity is easiest to own.

Second, degradation decisions are product decisions. Whether checkout should accept an order without a live inventory check is a question about oversell risk versus lost sales, and engineering cannot answer it alone. Making the decision explicit, rather than letting it emerge from whatever the code does on an exception, is most of the value.

Cascading Failures and What Happens at Scale

The failure modes worth distinguishing are different enough to need different defenses:

  • Component failure is handled by redundancy and routing.
  • Dependency latency is handled by deadlines, bulkheads, and shedding.
  • Duplicate messages are handled by idempotency and deduplication.
  • Reordered messages are handled by versioning or sequence numbers on state transitions.
  • Retry storms are handled by budgets and jitter.
  • Cascading failures happen when one of the above crosses a shared resource boundary and spreads.

Scale changes which of these dominate. At 10 requests per second, a slow dependency barely matters: even 2-second latency means about 20 concurrent requests, which fits comfortably in default pools. Simple timeouts and a retry are sufficient, and bulkheads or circuit breakers are likely premature.

At 1,000 requests per second, latency-to-concurrency conversion becomes the dominant risk. The same 2-second slowdown requires roughly 2,000 concurrent requests, enough to exhaust connection pools and memory. Bulkheads, propagated deadlines, and retry budgets now pay for themselves.

At 100,000 requests per second, correlated and metastable failures dominate. Synchronized clients, cache stampedes, and fleet-wide configuration changes can each generate load spikes larger than any single component failure. Staged rollouts, admission control, and cell-based isolation (partitioning users into independent copies of the stack) become architectural necessities.

The complexity at each level is justified only by the level below it failing. Building cell-based architecture for a 10 request-per-second service adds failure modes without removing any.

Engineering Principles for Designing for Failure

Latency is a resource consumer, not only a user-experience metric. By Little's Law, slower responses at constant traffic mean more concurrent work, which means more memory, threads, and connections held.

A timeout is part of the system's failure model. It defines when the caller gives up, how long resources are held, and how quickly failures are detected. It deserves the same scrutiny as a schema.

Retries are a load multiplier unless the system is designed for them. Budgets, jitter, single-layer retries, and idempotency are what make them safe.

Redundancy only helps against failures the copies do not share. The useful question is not how many replicas exist but what all of them have in common.

Every degraded mode is a product decision. Choosing what to serve when a dependency is unavailable defines the system's real guarantees.

Recovery can fail too. A system that collapses when its backlog drains or its cache restarts has a second outage built into its recovery path.

Reject early rather than fail late. A fast rejection preserves capacity; a slow timeout spends it.

Final Thoughts

Designing for failure is less about adding resilience patterns than about removing optimistic assumptions. Most cascading failures trace back to an assumption that was true on the whiteboard: that a dependency is either up or down, that a timeout means nothing happened, that replicas fail independently, that the system returns to normal once the trigger is gone.

The deeper skill is building an accurate model of the system under stress. That means knowing where state lives and who owns it, which resources are shared, how latency converts into concurrency, which failures are correlated, and what the system is allowed to do when a component cannot answer. Patterns like bulkheads, circuit breakers, and outboxes follow from that model; applied without it, they add complexity without adding safety.

These are the kinds of engineering problems at the center of modern software systems: understanding where state lives, how components interact, and what happens when the assumptions between them stop being true. A system designed with those questions answered does not avoid failure. It keeps serving users while failure happens.

Key Takeaways

  • A slow dependency is often more dangerous than a dead one, because latency silently converts into held connections, threads, and memory until shared pools are exhausted.
  • Network calls have three outcomes (success, failure, unknown), so any retried operation that changes state must be idempotent to avoid turning availability problems into correctness problems.
  • Bulkheads, propagated deadlines, and load shedding bound how much damage one dependency can do, at the cost of lower peak utilization.
  • Retries can multiply load exponentially across layers, so retry policy belongs in the system's load-management design through budgets, jitter, and retrying at a single layer.
  • Redundancy protects only against independent failures; shared configuration, deployments, and dependencies create correlated failures that defeat replication.
  • Metastable failures persist after their trigger disappears, so recovery paths must actively break feedback loops through shedding, gradual admission, and rate-limited backlog draining.
  • Graceful degradation requires classifying every dependency as critical, degradable, or optional, and that classification is a product decision as much as an engineering one.

Get insights like this in your inbox

Join thousands of engineers receiving practical engineering, Cloud, Distributed Systems, Infrastructure and AI engineering insights.

No spam. Unsubscribe anytime.