Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson6 / 9

    Timeouts, Retries, and Circuit Breaker Composition

    Diagnose before reading

    Three nested layers each allow one initial attempt plus two retries. What is the worst-case leaf-call count when every layer exhausts its policy? Then decide which layer should own retries and draw the total deadline around the entire sequence, including delays.

    Write your answer first. Then use this trace to check the boundary you chose.

    Boundary, outer → innerWhat it controlsWhat to verify
    Endpoint remaining-budget tokenRequest-bound work across dependenciesDoes every cooperative stage receive it?
    Standard HTTP rate limiterLocal pipeline admissionIts wait is outside that handler's total-timeout strategy
    Total timeout → retryWhole inner attempt sequence and delaysHow many attempts fit the remaining budget?
    Breaker → attempt timeoutHandled-attempt statistics and one attempt's budgetMinimum throughput, failure ratio and cancellation behavior
    Body read / deserialization outside handler pipelineThe response content and caller's remaining budgetIs cancellation passed through those operations too?

    Start with one end-to-end budget

    A resilient request begins with a deadline, not with a retry count. If the public API has a 3-second objective, reserve time for routing, serialization, and the final response. Give each dependency a smaller attempt timeout and ensure the entire retry sequence fits inside the total request timeout.

    Timeouts request that work stop; they do not make an operation succeed. Polly timeouts are cooperative and can overrun if the callback ignores the supplied token. Propagate the caller's CancellationToken and the pipeline-provided token so cooperating work can release sockets, database connections, and CPU.

    Compose policies deliberately

    A practical outbound HTTP order is:

    1. An outer total timeout requests cancellation of the work within that pipeline, including its retries and delays.
    2. A retry strategy handles a small set of transient failures.
    3. A circuit breaker stops sending work to a dependency that is persistently unhealthy.
    4. A per-attempt timeout requests cancellation when that attempt's budget expires.

    The standard .NET HTTP resilience handler orders its rate limiter, total timeout, retry, circuit breaker and attempt timeout from outermost to innermost. The breaker therefore normally sees individual attempts. Other compositions can count logical calls instead. Propagate an end-to-end caller budget as well: this handler does not cover all endpoint work, and its total timeout starts inside the outer rate limiter.

    This registration fragment requires Microsoft.Extensions.Http.Resilience, the relevant extension-method namespaces, an application-defined typed InventoryClient and a valid configured absolute base URL.

    C#
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Http.Resilience;
    
    builder.Services
        .AddHttpClient<InventoryClient>(client =>
        {
            client.BaseAddress = new Uri(
                builder.Configuration["Inventory:BaseUrl"]!);
        })
        .AddStandardResilienceHandler(options =>
        {
            options.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(3);
            options.AttemptTimeout.Timeout = TimeSpan.FromSeconds(1);
            options.Retry.MaxRetryAttempts = 2;
            options.Retry.Delay = TimeSpan.FromMilliseconds(200);
            // Explicit opt-in to this experimental extension; review the pinned package API.
    #pragma warning disable EXTEXP0001
            options.Retry.DisableForUnsafeHttpMethods();
    #pragma warning restore EXTEXP0001
            options.CircuitBreaker.SamplingDuration = TimeSpan.FromSeconds(30);
            options.CircuitBreaker.MinimumThroughput = 20;
            options.CircuitBreaker.FailureRatio = 0.5;
        });

    MaxRetryAttempts = 2 permits at most three attempts including the initial call; it does not guarantee all three fit the budget. For the locally checked Microsoft.Extensions.Http.Resilience 10.0.0 profile, the helpers' declaring class is marked experimental with EXTEXP0001; the sample's narrow pragma makes that opt-in explicit. Extension-call syntax alone did not require that diagnostic in the checked build, whereas referring to the declaring class did. This is not a general suppression of compiler diagnostics. Pin and review the package API and actual build diagnostics before adopting it. Default backoff is exponential with jitter. The explicit delay is illustrative and must be tuned. The unsafe-method guard disables retry for POST, PUT, PATCH, DELETE and CONNECT; this is a conservative policy, not a claim that PUT or DELETE lack HTTP idempotent semantics. Without such configuration, standard retry can apply to all methods.

    Retry only safe operations

    Retry only eligible transient failures when replay is safe: selected connection failures, 5xx responses, HTTP 408 or HTTP 429 according to the API contract and budget. Standard handler defaults include HTTP 5xx, 408, 429, HttpRequestException and Polly TimeoutRejectedException; customize predicates where those defaults are too broad, and honor applicable retry hints. Do not retry validation errors, authentication failures, or deterministic business conflicts.

    For writes, a timeout means the outcome is unknown—not that the server did nothing. Use an idempotency key or operation identifier persisted with the result before retrying a payment, email, inventory decrement, or other side effect.

    C#
    public async Task<InventoryItem?> GetAsync(
        string sku,
        CancellationToken cancellationToken)
    {
        using var response = await httpClient.GetAsync(
            $"inventory/{Uri.EscapeDataString(sku)}",
            cancellationToken);
    
        if (response.StatusCode == HttpStatusCode.NotFound)
            return null;
    
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadFromJsonAsync<InventoryItem>(
            cancellationToken: cancellationToken);
    }

    The typed-client method is illustrative and assumes the httpClient field, DTO and System.Net/System.Net.Http.Json imports. Validate sku against the domain format; URI escaping alone is not domain validation. The handler pipeline does not provide an end-to-end deadline for response-body buffering and JSON processing outside it. Pass the caller's remaining-budget token through body reads too, and the standard-handler registration sets HttpClient.Timeout to Timeout.InfiniteTimeSpan so its strategies own timeout handling. If later configuration overrides that, account for the extra competing timeout. Do not treat the three-second handler timeout as a wall-clock guarantee.

    Scope the circuit breaker correctly

    A breaker should represent one dependency boundary. Avoid one global circuit for unrelated services: a failing recommendations endpoint must not block inventory or payments. For multi-tenant systems, consider whether one tenant can poison shared breaker statistics and whether partitions are needed.

    The open state fails fast. After the break duration, a limited probe enters the half-open state. Recovery must be observable; do not silently return stale data unless the product explicitly permits it.

    Avoid retry amplification

    If the client, gateway, application, and SDK each retry twice, a single user action can fan out into many dependency calls. Assign one owner for retries, document downstream behavior, and expose the final attempt count in telemetry.

    Use exponential backoff with jitter. Randomized delay reduces synchronized retry bursts; it does not guarantee that instances never retry together.

    Production telemetry

    Record dependency name, operation, attempt number, final outcome, duration, timeout source, breaker state transition, and whether a fallback was served. Keep recovered retries separate from final failures: a healthy success rate can hide a dependency that succeeds only after repeated attempts.

    Alert on sustained breaker openings, rising retry volume, tail latency, and request cancellation. Never log access tokens, connection strings, or complete sensitive payloads.

    Failure-injection exercise

    Test four cases against a controlled dependency stub:

    • slow success just inside the attempt timeout;
    • a timeout followed by success on a safe read;
    • enough handled failures within the sampling window to meet the configured minimum throughput and failure ratio and open the breaker (a few calls below the 20-attempt threshold should not);
    • caller cancellation while a retry delay is pending.

    For each case, verify the total duration, number of attempts, emitted telemetry, and final HTTP response. For cooperating stubs, assert the intended budget with a defined scheduling/cleanup tolerance. Also test a callback that ignores cancellation and demonstrate that a timeout request cannot forcibly stop it. Record client-observed completion separately from any server-side work that continues.

    Interview drill

    • Why is a timeout not a retry policy?
    • When is retrying a POST safe?
    • How can retries at multiple layers amplify an outage?
    • What should determine a circuit breaker's partition key?
    • Why must cancellation flow through retry delays as well as HTTP calls?
    • Which measurements indicate whether a fallback meets its product contract rather than merely hiding failures?

    Revision checklist

    • I can draw the total deadline and per-attempt budget.
    • I can classify transient versus deterministic failures.
    • I require idempotency before retrying side effects.
    • I keep circuit breakers scoped to meaningful dependency boundaries.
    • I prevent retry multiplication across layers.
    • I test recovery, cancellation, and observability under injected faults.

    Check the boundary

    A custom pipeline adds Retry outside a 10-second Timeout, permits five retries and uses five 2-second delays. No outer deadline is shown. Which is the right review finding?

    A The whole operation is guaranteed to finish in 10 seconds.
    B There can be six attempts; if every attempt consumes 10 seconds and is handled/retried, the illustrative total is about 70 seconds before overhead, unless another budget stops it earlier.
    C Five retries means five attempts in total.
    D The retry predicate always handles every timeout and HTTP status by default.
    Show answer

    Correct answer: B

    Five retries allow six attempts. The inner timeout is per attempt: 6 × 10 + 5 × 2 = 70 seconds under those assumptions. Actual handling, caller/client deadlines, cooperative cancellation and overhead determine the observed outcome.

    Hint: Count the initial attempt and locate the timeout relative to the retry.

    Two-minute interview practice

    Attempt both before comparing. State the assumption, the repair and one limit of your evidence.

    1. Calculate the opening worst-case leaf-call count. Is it a prediction of every real request?
    2. The standard handler disables retries for unsafe methods. Is a timed-out POST therefore proven not to have committed?

    Hint. Revisit the ownership, time, transaction or measurement boundary in the trace table.

    Check your reasoning.

    1. Three layers × three attempts is multiplicative: 3 × 3 × 3 = 27 leaf calls if every inner policy is re-entered and exhausts its allowance. Deadlines, cancellation and predicates can reduce that number.
    2. No. Disabling this retry owner prevents its automatic replay, not the original server effect or retries by a gateway/client. Use durable operation identity and reconciliation for uncertain writes.

    Evidence for the repair

    Use a controllable handler to count actual attempts on a safe GET, an unsafe POST and cancellation during a delay. Record the policy predicate and budget as well as the count; a successful retry test does not prove server-side effects are replay-safe.

    Practice

    Practice test: .NET Debugging Practice 2: Mitigate and Verify the Fix5 questions · 1 mark each, no negative marking
    Take the test
    API Resilience and Incident Diagnosis Production Assessment10 questions · 10 marks
    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 28 Oct 2026 ·