How-To Guide

How to Cut Tail Latency with Hedged Requests

Reduce p99 latency by issuing a second request when the first is slow, taking the first response and cancelling the loser.

On this page

  1. Introduction
  2. Why the Tail Dominates
  3. How Hedging Works
  4. Hedging Without Doubling Load
  5. Idempotency Is a Prerequisite
  6. Choosing the Delay and the Number of Hedges
  7. When Not to Hedge
  8. Conclusion

Introduction

A service whose median latency is ten milliseconds can still have a p99 of a second. That tail is what users notice, because the slowest responses are the ones they wait on. Often the delay is not uniform: a small fraction of requests hit a slow instance, a garbage collection pause, or a transient network stall while the rest are fast. A hedged request exploits that: issue the request, and if it has not returned after a short timeout, issue a second one to a different replica, taking whichever returns first. This article explains when hedging helps, how to do it without doubling load, and how it interacts with idempotency and cancellation.

Why the Tail Dominates

If a client waits on a page that needs twenty backend calls, and each call has a one-in-a-hundred chance of being slow, the chance that the page hits at least one slow call is much higher than one in a hundred. Tail latency compounds across fan-out, so the p99 of a composite request is driven by the p99 of its parts. Reducing the tail of each dependency, even if the median is unchanged, visibly improves the experience.

The tail is usually caused by a small number of stragglers rather than by a uniformly slow service: one instance under a GC pause, one overloaded node, one packet lost and retransmitted. Because the cause is a subset of requests and often random, a second attempt to a different replica frequently succeeds quickly. That is the opportunity hedging exploits.

How Hedging Works

Send the first request, start a timer, and if the response has not arrived by the timer, send a second copy to another replica. Take the first to complete and cancel the other. The timer should be set near a high percentile of the normal latency, so that most requests complete before any hedge is sent and only the slow tail triggers a second attempt. Set it too low and you hedge almost every request, doubling load; set it too high and the tail is not improved.

async function hedgedFetch<T>(urls: string[], delayMs: number): Promise<T> {
  const controllers = urls.map(() => new AbortController());
  const attempts = urls.map((url, i) => {
    const start = () => fetch(url, { signal: controllers[i].signal }).then((r) => {
      if (!r.ok) throw new Error('upstream: ' + r.status);
      return r.json() as Promise<T>;
    });
    // Subsequent requests are only started after the delay, if the first is slow.
    return i === 0
      ? start()
      : new Promise<T>((resolve, reject) => setTimeout(() => start().then(resolve, reject), delayMs));
  });
  try {
    return await Promise.any(attempts);        // first success wins
  } finally {
    controllers.forEach((c) => c.abort());      // cancel the losers
  }
}

Hedging Without Doubling Load

The danger of hedging is that in the worst case it doubles the requests to a dependency. The mitigations are to hedge only a small fraction of calls and to cancel the loser. Because the hedge is sent only after the delay, and the delay is near the p95 or p99, only a few percent of requests ever send a second copy, so the extra load is small. Cancelling the loser ensures the abandoned request does not continue consuming capacity on the server side.

A more economical variant hedges only when the request fits a specific pattern, such as a read that is idempotent and cheap, and never for a write. Another uses a budget: allow a limited number of hedges per second, so under a broad slowdown the hedge rate is capped and the load cannot run away. Without a cap, a dependency that slows down for everyone triggers hedges everywhere and makes its overload worse.

Idempotency Is a Prerequisite

Hedging sends the same request twice, so the request must be idempotent or you risk doing the work twice. A read is safe. A write is not, unless it carries an idempotency key so the server deduplicates the second copy. Never hedge a non-idempotent write, because the two copies may both take effect even if you cancel one at the client.

Cancellation must actually stop the server-side work, not just ignore the response. If the dependency does not honour cancellation, the loser keeps running and the hedge has not saved the capacity. Propagating a deadline that the dependency respects is what makes cancellation real, and it is the same requirement as any distributed cancellation.

Choosing the Delay and the Number of Hedges

Set the hedge delay from the observed latency distribution: a value near the 95th or 99th percentile means most requests finish before a second is sent, so the hedge fires only on the slow tail. Measure the distribution rather than guessing, and revisit the value when the service changes, because a delay tuned for a slow service is too high for a fast one and vice versa.

Hedge once, not repeatedly. A single hedge halves the effective tail by catching the case where one replica is slow; hedging more than once adds load for diminishing benefit and risks a fan-out of retries. If the first hedge is also slow, that points to a systemic slowdown rather than a straggler, and the right response is to shed load or fail fast, not to send a third copy.

// Derive the hedge delay from a latency histogram instead of guessing.
function hedgeDelayMs(buckets: number[], targetQuantile = 0.95): number {
  const total = buckets.reduce((a, b) => a + b, 0);
  let seen = 0;
  for (let i = 0; i < buckets.length; i++) {
    seen += buckets[i];
    if (seen / total >= targetQuantile) return i * 10; // bucket width 10ms
  }
  return buckets.length * 10;
}

// Cap the hedge rate so a broad slowdown cannot double the load.
const maxHedgesPerSecond = 50;
let hedgesThisSecond = 0;
setInterval(() => { hedgesThisSecond = 0; }, 1000);
function canHedge(): boolean {
  return hedgesThisSecond < maxHedgesPerSecond && ++hedgesThisSecond > 0;
}

When Not to Hedge

Do not hedge when the dependency is centralized rather than replicated: if there is one instance, the second request hits the same overloaded box and adds load without improving latency. Do not hedge writes without an idempotency key, or when the operation is expensive enough that doubling it is worse than the tail. Do not hedge when the tail is caused by a shared resource you cannot escape, such as a single leader, because the second request contends for the same resource.

Hedging is a latency optimization with a cost in load, so use it where the tail hurts users and the dependency is replicated enough that a second copy can succeed. An alternative for the same goal is a request-level timeout with a retry to a different replica, which is similar but reacts after a failure rather than in parallel. Choose based on whether you prefer bounded extra load or bounded extra latency.

Conclusion

Hedged requests cut the tail of a latency distribution by sending a second request when the first is slow and taking whichever returns first. Set the delay near a high percentile so only the tail hedges, cancel the loser so the abandoned work stops, cap the hedge rate so a broad slowdown cannot double the load, and hedge only idempotent requests. Propagate a deadline so cancellation is real. Benchmark the effect before and after to confirm that the tail improved and the median did not regress, and verify that cancellation actually stops the loser’s work. Hedging trades a small amount of extra load for a large improvement in the latency users notice, and it is worth it precisely when the tail, not the median, is the problem.

Sources: The Tail at Scale (Dean & Barroso), gRPC: request hedging, Tail latency.

FAQ

Is hedging safe for write requests?
Only if the write is idempotent, for example by carrying an idempotency key so the server deduplicates the second copy. Otherwise the two copies can both take effect even if you cancel one at the client, causing a duplicate write.
How do I avoid hedging every request and doubling load?
Set the hedge delay near a high percentile of latency, such as p95 or p99, so most requests finish before a second is sent and only the slow tail hedges. Also cap the hedge rate per second so a broad slowdown cannot cause a runaway increase in load.

Related Examples