Volume 7 · Chapter 8 — Advanced .NET Engineering, Performance & Production Excellence

Resilience Engineering

Goutham Mayaluri 8 min read .NETC#ILPerformanceResilience

8.1 Introduction

Resilience engineering accepts a hard truth about distributed systems: failures are not exceptional, they are constant. Networks drop packets, dependencies slow down, instances die, and traffic spikes. A resilient system is not one that never fails but one that degrades gracefully and recovers automatically. In .NET this is expressed with a small, composable set of patterns - timeout, retry, circuit breaker, bulkhead, fallback - typically via the Polly-based resilience pipelines built intoMicrosoft.Extensions.Http.Resilience.

8.2 Timeouts - the Foundation

The most important resilience pattern is also the simplest: never wait forever. A call without a timeout can hold a request thread and resources indefinitely when a dependency hangs, and that is how a single slow dependency cascades into a full-service outage. Every network call needs a bounded timeout.

8.3 Retry with Backoff and Jitter

Retries recover from transient faults (a dropped connection, a brief blip). But naive retries are dangerous: retrying immediately and in lockstep across many callers creates a retry storm that amplifies load exactly when a dependency is struggling. The fix is exponential backoff with jitter (randomization) and a strict attempt cap, and retrying only idempotent operations or transient errors.


// Retry only transient failures, with exponential backoff + jitter.
builder.Services.AddHttpClient<LedgerClient>()
    .AddResilienceHandler("ledger", b =>
    {
        b.AddRetry(new HttpRetryStrategyOptions
        {
            MaxRetryAttempts = 3,
            BackoffType = DelayBackoffType.Exponential,
            UseJitter = true,
            ShouldHandle = args => ValueTask.FromResult(
                args.Outcome.Result?.StatusCode is HttpStatusCode.ServiceUnavailable
                    or HttpStatusCode.RequestTimeout)
        });
    });

8.4 The Circuit Breaker

When a dependency is genuinely down, continuing to call it (and retry) wastes resources and delays recovery. A circuit breaker tracks the failure rate and, once it crosses a threshold, “opens” - failing fast without calling the dependency - for a cool-down period. It then goes “half-open,” allowing a trial request; if that succeeds it closes, otherwise it re-opens. This gives the dependency room to recover and protects the caller from piling up on a dead service.

stateDiagram-v2
  [*] --> Closed
  Closed --> Open: failure rate > threshold
  Open --> HalfOpen: cool-down elapsed
  HalfOpen --> Closed: trial call succeeds
  HalfOpen --> Open: trial call fails
  note right of Open
      Calls fail fast (no request sent),
      giving the dependency time to recover
  end note

8.5 Bulkhead Isolation

Named after a ship’s watertight compartments, the bulkhead pattern limits the resources any one dependency or workload can consume, so a failure in one cannot sink the whole ship. Concretely: separate connection pools, bounded concurrency per dependency, or isolated thread/queue budgets. If the fraud service hangs, only the bulkhead’s slots are consumed; the rest of the API keeps serving.

8.6 Fallback and Graceful Degradation

When a call ultimately fails, a fallback provides a degraded-but-useful response instead of an error - a cached value, a default, or a reduced feature. Graceful degradation is a product decision as much as a technical one: decide in advance which features are essential and which can be shed under stress.

8.7 Composing a Resilience Pipeline

The patterns compose in a deliberate order: timeout innermost (bound each try), retry around it (with backoff), circuit breaker around that (stop retrying a dead dependency), and fallback outermost (last resort). The diagram shows a single outbound call flowing through the stack.

sequenceDiagram
  autonumber
  participant App as Caller
  participant CB as Circuit Breaker
  participant Retry as Retry (backoff+jitter)
  participant TO as Timeout
  participant Dep as Dependency
  App->>CB: call
  alt circuit open
      CB-->>App: fail fast -> fallback (cached value)
  else circuit closed
      CB->>Retry: proceed
      Retry->>TO: attempt (2s budget)
      TO->>Dep: request
      Dep-->>TO: slow/error
      TO-->>Retry: timeout/fault -> backoff, retry
      Retry-->>CB: exhausted -> record failure
      CB-->>App: fallback response
  end

8.8 Load Shedding and Rate Limiting

Resilience also means protecting yourself from too much inbound work. Rate limiting and load shedding reject or queue excess requests so the service stays healthy for the requests it does accept, rather than melting down and failing all of them. Failing fast with a429is friendlier than timing out.

Senior Interview Question

Why are retries alone not enough - and how can they make things worse?

Retries only address transient faults; against a dependency that is genuinely overloaded or down, they amplify the problem. If every caller retries immediately and in lockstep, the retries multiply load precisely when the dependency is weakest, creating a retry storm that prevents recovery - a self-inflicted DDoS. Retries must therefore use exponential backoff with jitter to spread attempts out, cap the number of attempts, apply only to idempotent operations and transient errors, and be paired with a circuit breaker that stops retrying once failures are sustained. Retry is one pattern in a stack, not a standalone cure.

Senior Interview Question

Explain the circuit breaker states and why the half-open state matters.

A circuit breaker has three states. Closed: calls flow normally while failures are counted. Open: once the failure rate crosses a threshold, calls fail fast without touching the dependency for a cool-down, protecting both sides. Half-open: after the cool-down, it lets a limited number of trial calls through - if they succeed it closes and normal traffic resumes, if they fail it re-opens. The half-open state is essential because it is how the breaker automatically detects recovery without flooding a just-recovering dependency with full traffic; without it you would either stay open too long or slam the dependency the instant the timer expires.

Senior Interview Question

What is the bulkhead pattern and what failure does it prevent?

The bulkhead pattern isolates resources so a failure in one area cannot exhaust the resources the whole application shares. For example, giving each downstream dependency its own bounded connection pool or concurrency limit means that if one dependency hangs, only its slots fill up - other dependencies and endpoints keep working. It prevents the common cascading failure where one slow dependency consumes all threads or connections and takes the entire service down with it. It trades a little peak capacity per dependency for containment of blast radius.

Senior Interview Question

In what order do you compose timeout, retry, and circuit breaker, and why?

Timeout goes innermost so each individual attempt is bounded; retry wraps the timeout so a timed-out or failed attempt can be retried with backoff; the circuit breaker wraps the retry so that once failures are sustained it stops the retries altogether and fails fast; and a fallback sits outermost as the last resort. The ordering matters because a breaker outside the retry sees the aggregate outcome and can cut off futile retry cycles, while the timeout inside each retry ensures no single attempt hangs. Reversing them - for instance retrying outside a breaker - would let retries keep hammering an open-circuit dependency.

Principal Engineer Question

How do you design a system so one failing dependency cannot cause a full outage?

I assume every dependency will fail and contain the blast radius by default. Each outbound call gets a timeout, a jittered capped retry for transient faults, and a circuit breaker to fail fast when it is truly down. I isolate dependencies with bulkheads so one hang cannot exhaust shared threads or connections. I identify the essential versus optional features up front and build fallbacks and graceful degradation for the optional ones, so a failed recommendation or enrichment call degrades the experience instead of the transaction. Inbound, I add rate limiting and load shedding so overload is rejected cleanly rather than collapsing everything. And I verify it: chaos/failure-injection testing that deliberately kills or slows dependencies, plus dashboards on breaker state and fallback rate. The architecture treats partial failure as the normal case and keeps the critical path alive when non-critical parts fail.

Principal Engineer Question

How do you validate that your resilience patterns actually work before a real incident?

Resilience that is never exercised tends to be resilience that is misconfigured - a timeout set too high, a breaker threshold never reached, a fallback that throws. I validate it deliberately. In testing, I inject faults: latency, errors, and outright dependency kills, asserting that timeouts fire, breakers open and recover, bulkheads contain the damage, and fallbacks return sensible responses. In staging or production I run controlled chaos experiments (game days) that degrade a dependency and confirm the system sheds the right features and stays within SLO. I also make resilience observable - metrics on breaker state transitions, retry counts, timeout rates, and fallback usage - so I can see the patterns engaging in real traffic and tune thresholds from data. The goal is that the first time a breaker opens for real is not the first time it has ever opened.

8.9 Banking Enterprise Scenario

A bank’s payment API depends on an external card network that occasionally degrades. Each call has a two-second timeout, three jittered retries for transient errors, and a circuit breaker that opens after sustained failures so the API fails fast instead of piling up. A bulkhead caps concurrent card-network calls so a hang there cannot starve account and balance endpoints, and a fallback queues the payment for later settlement with a “processing” status rather than erroring. When the network had a real outage, breaker and bulkhead metrics showed the containment working: card payments degraded gracefully while the rest of the platform stayed fully available and within SLO.

Chapter Revision Notes

  • Failures are constant; design for graceful degradation and auto-recovery.
  • Every network call needs a timeout - waiting forever causes cascades.
  • Retry only transient faults, with backoff + jitter and a cap; avoid retry storms.
  • Circuit breakers fail fast and use half-open to detect recovery safely.
  • Bulkheads isolate resources; fallbacks provide degraded responses.
  • Compose timeout < retry < breaker < fallback, and test with fault injection.