Most LLM calls in a given feature finish in a predictable window, and then a few take three or four times as long for no reason you can find in the request. The slow ones aren't errors, so retries never fire, and a timeout loose enough to avoid false failures does nothing for the user staring at a spinner. If that feature sits inside a pipeline of several calls, each one's slow tail compounds into the end-to-end latency.
A hedged request attacks that tail directly: send the call, and if it hasn't answered within a delay you chose from your own latency data, send a second identical call and take whichever finishes first. The idea comes from distributed systems (Jeff Dean and Luiz André Barroso described it in "The Tail at Scale"), and it transfers to LLM APIs with real differences in cost and side effects. Below: how to pick the delay, how to cancel the loser, how to budget the spend, and when hedging makes things worse.
Hedging is not a retry, and the difference matters
A retry happens after a failure. A hedge happens while the first attempt is still running, on the bet that the first attempt landed somewhere slow (a busy replica, a long queue, an unlucky batch) and a fresh attempt will land somewhere faster. Both attempts are live at once, and the first acceptable result wins.
That has three consequences:
- It only helps when slowness is independent between attempts. If the call is slow because the prompt is 80,000 tokens or because you asked for 2,000 output tokens, a second copy will be just as slow. Hedging fixes variance in the serving path, not in the work you asked for.
- It costs money even when it doesn't help. Every hedge you send is billed for its input tokens, and for whatever output it produced before you cancelled it. Retries only cost money when something already failed.
- It runs the request more than once. If the call has side effects, such as an agent step that executes a tool, both copies may execute. The gRPC hedging design spells this out: hedged RPCs may run several times on the server, so hedging should only be enabled for methods that are safe to execute more than once.
So hedge only calls that are pure (text in, text out, nothing happens in the world), latency-sensitive, and cheap enough to duplicate.
Choosing the hedge delay from your own latency distribution
The delay is the whole design. The rule Dean and Barroso proposed is to defer the second request until the first has been outstanding longer than the 95th-percentile latency for that class of request. By construction, only about 5% of requests ever reach that point, so you send at most about 5% more calls, and those calls are aimed at exactly the requests that make up your tail.
Two details make this work for LLM calls:
Measure the right latency. For a streamed response, the user perceives time to first token, and total duration is dominated by output length. Hedge on TTFT: no token by your p95 TTFT, send the second request. For non-streamed calls with bounded output (classifiers, extractors, short rewrites), total latency is fine, but bucket it by request class. A "short classification" p95 and a "long summary" p95 are different numbers, and a single global delay will either hedge every long summary or never hedge a short classification.
Recompute it. Model and provider latency shifts over weeks. Compute the per-class p95 from the last day or week of traces and load it as config rather than hard-coding a number. Clamp it between a floor and ceiling so one bad hour of data can't set it to 50 ms.
A worked implementation
The sketch below uses Python's asyncio. call_model stands for whatever async client call you already make; it must be cancellable, which async HTTP clients typically are: cancelling the task aborts the request.
import asyncio
class HedgeBudget:
"""Caps hedges to a fraction of primary calls over a rolling window."""
def __init__(self, max_ratio=0.05, window=1000):
self.max_ratio, self.window = max_ratio, window
self.primaries = 0
self.hedges = 0
def record_primary(self):
self.primaries += 1
if self.primaries >= self.window: # crude rolling reset
self.primaries, self.hedges = 0, 0
def try_spend(self) -> bool:
if self.hedges < max(1, self.primaries * self.max_ratio):
self.hedges += 1
return True
return False
async def hedged_call(request, hedge_delay_s, budget, deadline_s, metrics):
loop = asyncio.get_running_loop()
deadline = loop.time() + deadline_s
budget.record_primary()
first = asyncio.create_task(call_model(request))
tasks = {first}
try:
done, _ = await asyncio.wait(tasks, timeout=hedge_delay_s)
if not done and budget.try_spend():
tasks.add(asyncio.create_task(call_model(request)))
metrics.incr("hedge.sent")
while tasks:
done, _ = await asyncio.wait(
tasks, timeout=max(0, deadline - loop.time()),
return_when=asyncio.FIRST_COMPLETED)
if not done:
raise TimeoutError("deadline exceeded")
for t in done:
tasks.discard(t)
if t.exception() is None:
metrics.incr("hedge.won" if t is not first else "primary.won")
return t.result()
# a finished task failed; keep waiting on the other one, if any
raise RuntimeError("all attempts failed")
finally:
for t in tasks:
t.cancel() # stop paying for the loserWhy each piece is there:
- The `finally` block cancels the loser. Without it, the slower call keeps streaming tokens you'll never read and keeps a connection and a slot in your rate limit occupied. Whether a provider bills for output generated before the cancel lands varies, so check its documentation and measure rather than assume it's free.
- One hedge, not several. gRPC caps hedging at five attempts by default, but LLM attempts are billed by the token. Start with one hedge and add another only if measurements show it pays.
- A budget caps the spend. If the provider slows down across the board, every request crosses the p95 delay, and an unbudgeted hedger doubles your traffic at the moment the provider is least able to absorb it. That turns a slowdown into a rate-limit outage. gRPC handles this with retry throttling that stops sending hedges when the failure ratio is too high; the
HedgeBudgetabove is a cruder version of the same idea. Use a proper sliding window or token bucket in production. - One attempt's failure doesn't end the call while the other is still in flight. (If the primary fails before the delay, this sketch raises; your normal retry policy handles that case.)
- The overall deadline still applies. Hedging is a latency optimization inside a deadline, not a replacement for one.
Interactions that bite
Rate limits. Hedges count against request and token limits like any other call. Near your limits, hedges can produce 429s, which look like slow requests and trigger more hedges. Keep a margin, and never hedge in response to a 429.
Prompt caching. With provider-side prompt caching, the first request may still be writing the cache entry when the hedge arrives, so the hedge can miss the cache and pay full input price. Measure cache hit rates on hedged calls separately.
Non-determinism. At non-zero temperature the two attempts produce different text. That's fine for most pure calls, but log the winner's request ID, not the primary's, or replay and debugging will point at the wrong response.
Streaming to a user. Never start streaming one attempt to the user and then switch to the other. Pick the winner at first token and commit to it: the first attempt to emit a token wins, and the other is cancelled immediately.
Agent steps with tool calls. A model response that proposes a tool call is pure; executing the tool is not. You can hedge the model call that decides the next step as long as only the winning response's tool call gets executed. Never hedge a wrapper that both calls the model and runs the tool.
Measuring whether it worked
Record a baseline, ship hedging behind a flag to a slice of traffic, and track:
- Tail latency at p99 for hedged versus unhedged traffic. p50 barely moving is expected.
- Hedge rate: hedges sent divided by primary calls. It should sit near the percentile you chose. A hedge rate climbing well past it means the latency distribution shifted and your delay is stale.
- Hedge win rate: of hedges sent, how often the hedge finished first. If hedges rarely win, the slowness isn't independent between attempts (long inputs, long outputs, or a provider-wide slowdown) and you're paying for nothing.
- Cost delta in tokens per request, from your cost attribution.
A low win rate means the tail comes from the work itself, and the fix is elsewhere: shorter context, a bounded max_tokens, or a smaller model for that class.
Checklist
- [ ] The call is pure: no tool execution, writes or messages happen inside it.
- [ ] Latency is bucketed by request class, and the hedge delay is that class's p95 (TTFT for streamed calls), loaded from config with a floor and ceiling.
- [ ] At most one hedge per call.
- [ ] The losing attempt is cancelled in a
finallyblock. - [ ] A hedge budget caps hedges at a small fraction of traffic; 429s and provider-wide slowdowns don't trigger more hedges.
- [ ] The overall deadline still bounds the call.
- [ ] Dashboards track p99, hedge rate, hedge win rate and token cost per request, with a flag to turn hedging off.
Further reading
- Jeffrey Dean and Luiz André Barroso, "The Tail at Scale," Communications of the ACM 56(2), 2013: https://research.google/pubs/the-tail-at-scale/
- gRPC proposal A6, Client Retries (includes the hedging policy, throttling and idempotency guidance): https://github.com/grpc/proposal/blob/master/A6-client-retries.md
- Python documentation,
asyncio.waitand task cancellation: https://docs.python.org/3/library/asyncio-task.html
Comments (0)
No comments yet — be the first.
Sign in to leave a comment.