skip to content

In ASP.NET Core, how does AddStandardHedgingHandler differ from AddStandardResilienceHandler, and why does it keep a circuit breaker per authority?

level: seniorimportance: nice to knowfreq 24%

answer

  1. parallel copies instead of waiting
  2. Delay 2 s, MaxHedgedAttempts 1
  3. first non-transient answer wins
  4. limiter, breaker, timeout per endpoint
  5. ConfigureOrderedGroups for other hosts

basics

~20 s

AddStandardHedgingHandler sends an extra copy of a request when the first is still running after 2 seconds or failed transiently, and keeps the first good answer. Its limiter, breaker and attempt timeout run per authority, so an unhealthy host is skipped.

solid answer

~50 s

The standard resilience handler retries **sequentially**: a new attempt starts only after the previous one failed. `AddStandardHedgingHandler()` runs attempts **concurrently**: if the first has not finished after `Hedging.Delay` (2 s), or returns a transient outcome, it sends a hedged copy, keeps the first outcome that is not transient and cancels the rest. `MaxHedgedAttempts` defaults to 1, so at most two copies, all inside a 30-second total timeout. The handler is split in two: an outer pipeline with the total timeout and hedging, and an inner per-endpoint pipeline with a rate limiter, a circuit breaker and a 10-second attempt timeout, selected by authority (scheme, host and port). Each host therefore has its own breaker, and an open one surfaces as `BrokenCircuitException`, which hedging treats as transient and routes around. Without `ConfigureOrderedGroups` or `ConfigureWeightedGroups`, copies go to the same URL. Hedge idempotent reads only, such as a payment-status lookup.

code

csharp · 13 lines
csharp
builder.Services.AddHttpClient<PaymentStatusClient>(c => c.BaseAddress = new Uri("https://eu.gateway.example.com/"))
    .AddStandardHedgingHandler(routing => routing.ConfigureOrderedGroups(o =>
    {
        o.Groups.Add(new UriEndpointGroup
        {
            Endpoints = { new WeightedUriEndpoint { Uri = new Uri("https://eu.gateway.example.com/") } }
        });
        o.Groups.Add(new UriEndpointGroup
        {
            Endpoints = { new WeightedUriEndpoint { Uri = new Uri("https://us.gateway.example.com/") } }
        });
    }))
    .Configure(o => o.Hedging.Delay = TimeSpan.FromMilliseconds(800));

go deeper

for a junior

Recall that hedging sends a parallel copy of a slow request and keeps the first good answer, unlike a retry that waits for failure.

for a middle

Explain the 2-second delay, the single hedged copy by default, the outer and per-endpoint pipelines, and what routing groups change.

for a senior

Show when hedging beats retries, why breakers are per authority, how to keep writes out of it and how to size Delay from latency data.

for a principal

Weigh the extra load hedging puts on a provider against tail-latency goals, and decide which read paths justify multi-region routing.

## Retrying versus hedging Both handlers come from **`Microsoft.Extensions.Http.Resilience`** and are chained on an `IHttpClientBuilder`. They answer different failures: | | `AddStandardResilienceHandler()` | `AddStandardHedgingHandler()` | |---|---|---| | Extra attempts | sequential retries after a failure | concurrent copies while the first is still running | | Trigger | a transient outcome | `Delay` elapsed (2 s) **or** a transient outcome | | Default extra attempts | 3 retries | 1 hedged copy (`MaxHedgedAttempts`, range 1-10) | | Circuit breaker | one per pipeline, shared by all hosts | one per endpoint authority | | Best against | short outages and blips | slow tails and one bad replica or region | In a shop that reads payment status from a card-payment gateway with an EU and a US endpoint, retries help when the gateway briefly returns 503; hedging helps when the EU endpoint is merely slow and the US one would answer in time. ## What the handler builds `AddStandardHedgingHandler()` registers **two** resilience handlers on the client: 1. An **outer** pipeline: a routing step, a snapshot of the request so it can be cloned, a **total request timeout** (30 s) and the **hedging** strategy. 2. An **inner, per-endpoint** pipeline: a **rate limiter** (1,000 concurrent requests, no queue), a **circuit breaker** (10% failure ratio, 100 calls minimum, 30 s sampling, 5 s break) and an **attempt timeout** (10 s). Like the standard resilience handler, it also sets `HttpClient.Timeout` to `Timeout.InfiniteTimeSpan` so the pipeline's own timeouts govern, and its options are validated when the host starts. ## When a hedged copy starts - The first attempt has not completed after `Hedging.Delay`, 2 seconds by default. `TimeSpan.Zero` would launch every copy at once. - The first attempt completed with a **transient** outcome: status 500 or above, 408, 429, `HttpRequestException`, `TimeoutRejectedException` or `BrokenCircuitException`. Then the next copy starts without waiting for the delay. - The first outcome that is **not** transient is accepted; the other attempts are cancelled. - Hedging stops when `MaxHedgedAttempts` is used up or, with routing configured, when no routes are left. A startup validator rejects a configuration whose cumulative hedging delay (`MaxHedgedAttempts` x `Delay`) exceeds the total timeout, alongside the familiar rules that the attempt timeout must not exceed the total and the breaker's sampling duration must be at least twice the attempt timeout. ## Why one breaker per authority Hedging exists to escape an unhealthy endpoint. A single shared breaker would open when one host fails and then block the healthy one too. So the inner pipeline is chosen per **authority** by default (the request URI's scheme, host and port), giving each endpoint its own limiter, breaker and attempt timeout. When the EU host's breaker is open, its attempt fails at once with `BrokenCircuitException`; the hedging predicate counts that as transient and moves on to the next route. The same selection is available elsewhere: - `.SelectPipelineByAuthority()` on the builder returned by `AddStandardResilienceHandler()` or `AddResilienceHandler(...)`, which otherwise build **one** pipeline per client; - `.SelectPipelineBy(sp => request => key)` for a custom key; the key appears in metrics and logs, so it must not carry sensitive values. ## Routing copies to other endpoints Without routing, every copy goes to the URL of the original request, which still helps against a slow replica behind one host name. To spread copies across hosts, pass a routing callback: `ConfigureOrderedGroups` tries groups in order (EU first, then US), and `ConfigureWeightedGroups` picks by weight, for example to send a small share of traffic to a new endpoint. The request's path and query are kept; only the scheme, host and port change. ## Limits and traps - **Every copy is a duplicate request.** Hedging suits reads and other idempotent calls; a card-charge `POST` must never go through it. `DisableForUnsafeHttpMethods()` extends `HttpRetryStrategyOptions` only, so the hedging handler has no such switch. - **The request must be cloneable.** A request whose content is `StreamContent` cannot be snapshotted, and the handler throws `InvalidOperationException`. - **Load goes up.** With a 2-second delay, every call slower than 2 seconds costs at least two requests; tune `Delay` from the endpoint's latency percentiles rather than guessing. - **One handler per client.** Do not stack hedging on top of the standard resilience handler; pick the one that matches the failure you expect.

  • What happens at startup if you set MaxHedgedAttempts to 3 and Delay to 15 seconds, leaving the total timeout at 30 seconds?
    The app fails to start. The hedging options are registered with validate-on-start, and the custom validator computes the cumulative hedging delay, 3 x 15 s = 45 s, which exceeds the 30-second total request timeout. Either shorten `Delay`, lower `MaxHedgedAttempts` or raise `TotalRequestTimeout`.
  • Why does an open circuit breaker on the EU endpoint not fail the whole status lookup?
    The breaker sits in the per-endpoint pipeline, so only EU calls are rejected, with `BrokenCircuitException`. The hedging predicate treats that exception as transient, so it launches the next attempt at once, and with ordered groups configured that attempt goes to the US endpoint.

Booking a ride home: if the first taxi firm has not confirmed within a couple of minutes, you also ring a second firm, take whichever car arrives first and cancel the other; a firm whose phone is dead you skip at once.

  • Hedges card-charge POSTs, sending duplicate charges by design
  • Believes hedging waits for the first attempt to fail before sending another
  • Expects hedged copies to reach another host without configuring routing
  • Assumes one circuit breaker covers every host in the hedging handler
  • Thinks the default sends up to ten hedged copies
  • Assumes any request body, including StreamContent, can be hedged