Architecture

Request Hedging: Cutting Tail Latency by Sending a Backup Request

By NileVPS Team · Published · 4 min read

اقرأ المقال بالعربي

Most requests to a healthy service finish quickly, but a small fraction take far longer than the rest. A garbage collection pause, a cold cache, a busy disk or a brief network hiccup can turn a 20 ms call into a 500 ms one. When a page depends on many backend calls, even rare slow calls become common at the page level. Request hedging is a technique for cutting this tail: if a request has not answered within a short delay, send a second copy to another replica and use whichever response arrives first. This article explains how it works, when it is safe, and how to keep it from becoming a source of overload.

Why Tail Latency Matters

Averages hide the problem. A service can have a low median latency while its 99th percentile (p99) is many times higher. If a single user action fans out to ten backend calls and each call has a 1% chance of being slow, the chance that at least one is slow is close to 10%. The slowest dependency sets the speed of the whole request.

You can attack tail latency at its source by fixing pauses and contention, and you should. Hedging is a complementary technique for the variability that remains.

How Hedging Works

  1. Send the request to replica A.
  2. Wait for a hedge delay, for example the observed p95 latency.
  3. If A has not responded, send the same request to replica B.
  4. Use the first successful response and cancel the other request if possible.

Because the second request is only sent for the slowest few percent of calls, the extra load is small, while the tail often improves dramatically: the chance that both replicas are slow at the same moment is much lower than the chance that one is.

Hedging vs Retries vs Timeouts

TechniqueWhen the second attempt startsMain purpose
Timeoutnever; the call is abandonedbound the wait
Retryafter the first attempt fails or times outrecover from errors
Hedgeafter a short delay, while the first is still runningreduce tail latency
Parallel (send to all at once)immediatelylowest latency, highest cost

Sending every request to two replicas from the start also cuts latency, but it doubles load. Hedging after a delay gets most of the benefit for a fraction of the cost.

When Hedging Is Safe

Hedging means the server may process the same request twice. That is acceptable only when duplicates are harmless:

  • Safe: reads, searches, cache lookups, idempotent GET requests, and writes protected by an idempotency key.
  • Unsafe: payments, order creation, sending messages, or any non-idempotent write without deduplication.

If you hedge writes, the server must recognize the duplicate and return the original result instead of performing the action again. Idempotency keys are the standard tool for this.

Choosing the Hedge Delay

The delay controls the trade-off between latency gain and extra load:

  • Set it near a high percentile of normal latency, such as p95. Then only about 5% of requests trigger a hedge.
  • Compute it from recent measurements rather than hardcoding it, because latency changes with traffic and time of day.
  • Never set it below typical latency, or you will double load for no benefit.

Avoiding Self-Inflicted Overload

Hedging adds work, and adding work to a struggling system can make things worse. Protect against this:

  1. Budget hedges. Allow hedges for at most a small percentage of requests, for example 5-10%, and skip hedging when the budget is spent.
  2. Disable under overload. If error rates or latency across all replicas rise, the problem is load, not one slow replica; hedging only adds more.
  3. Cancel losers. Propagate cancellation so the slower request stops consuming resources once the winner arrives.
  4. Use different replicas. Hedging to the same overloaded server rarely helps.
  5. Combine with admission control. Servers should still reject excess work quickly.

Hedging in Practice

gRPC supports hedging through its service config. A hedging policy might look like this:

{
  "methodConfig": [{
    "name": [{ "service": "search.SearchService" }],
    "hedgingPolicy": {
      "maxAttempts": 2,
      "hedgingDelay": "0.05s",
      "nonFatalStatusCodes": ["UNAVAILABLE"]
    }
  }]
}

Client support varies by language and version, so check your gRPC library's documentation before relying on it. Some service proxies, including Envoy, also offer hedging options at the route level.

In application code, the pattern is short. A Python asyncio sketch:

import asyncio

async def hedged(call_a, call_b, delay=0.05):
    first = asyncio.create_task(call_a())
    done, _ = await asyncio.wait({first}, timeout=delay)
    if done:
        return first.result()
    second = asyncio.create_task(call_b())
    done, pending = await asyncio.wait({first, second},
                                       return_when=asyncio.FIRST_COMPLETED)
    for task in pending:
        task.cancel()
    return done.pop().result()

A production version would also handle errors from the first finisher, track the hedge budget and record metrics.

Hedging pairs naturally with admission control, which keeps servers from accepting more than they can handle. To test hedging across replicas in different regions, you can create servers from the deploy page.

FAQ

Does request hedging double server load?

No, not when it is configured with a delay. Only requests slower than the hedge delay trigger a second copy, so with a delay near p95 the extra load is roughly 5%, plus some wasted work if cancellation is not propagated.

Can I hedge database writes?

Only if duplicates are safe. Use idempotency keys or unique constraints so a repeated write returns the original result. Without that protection, hedge only reads.

Is hedging useful with a single server?

Rarely. Hedging works because independent replicas are unlikely to be slow at the same moment. Sending a duplicate to the same server usually meets the same pause or contention.

Related guides