What is Hedging strategy in Polly v8 and how to implement it in .NET?

Asked -2 seconds ago Updated 4 hours ago 22 views

1

Hedging executes additional concurrent attempts of an operation before the primary attempt finishes if it takes longer than expected. This decreases tail latency in high-availability systems.

Implementing Hedging with Polly

Hedging is ideal for idempotent operations (such as HTTP GET queries) where receiving the fastest successful response is critical.

Code Example

var pipeline = new ResiliencePipelineBuilder<HttpResponseMessage>()
    .AddHedging(new HedgingStrategyOptions<HttpResponseMessage>
    {
        MaxHedgedAttempts = 3,
        Delay = TimeSpan.FromMilliseconds(200),
        ShouldHandle = new PredicateBuilder<HttpResponseMessage>()
            .Handle<HttpRequestException>()
            .HandleResult(res => !res.IsSuccessStatusCode)
    })
    .Build();

var response = await pipeline.ExecuteAsync(async ct =>
{
    return await httpClient.GetAsync("https://api.example.com/data", ct);
});

0 Answers


Write Your Answer