We are going to design a request hedging system for RPC (Remote Procedure Call) that includes speculative retries, budgets, and safeguards.
The idea is to improve the success rate and reduce latency by sending the same request to multiple replicas (speculative retries) and using a budget to limit the number of retries.
We also need safeguards to prevent overloading the system and to handle failures gracefully.
Steps:
- We assume we have a way to get a list of replicas (endpoints) for a given service.
- We will send the request to the first replica and in parallel, if we haven't received a response within a certain timeout, we will send to additional replicas (speculative).
- We set a maximum number of speculative retries (budget) to avoid flooding.
- We will cancel all other requests once we get the first successful response.
- We need to handle failures: if a replica is down, we might want to blacklist it temporarily.
- We might also want to use a backoff strategy for retries.
Implementation considerations:
- We are in an RPC context, so we assume we have a client that can send requests to a given endpoint and get a response or error.
- We want to do this in a non-blocking way, using asynchronous calls or threads.
We'll design a class HedgedRPCClient that wraps around a normal RPC client.
Steps in the client:
- Initialize with a list of replicas, a timeout for the initial request, a speculative timeout (after which we send to next replica if no response), and a maximum number of retries (budget).
- When making a request:
a. Start a timer for the initial request.
b. Send the request to the first replica.
c. If we don't get a response within the speculative timeout, send to the next replica (if we haven't exceeded the budget).
d. Continue until we get a response or run out of replicas/budget.
- We'll use a thread pool or async tasks to manage the concurrent requests.
- We'll have a mechanism to cancel the in-flight requests once we get a successful response.
However, note: we don't want to send too many requests at once. We might want to adjust the speculative timeout dynamically based on past latencies.
But for simplicity, let's assume fixed timeouts and a fixed list of replicas.
We'll also consider:
- If a replica returns an error (like server error), we might want to retry on another replica? Or only on timeout?
- Typically, hedging is done for timeouts, not for errors. But we can also consider errors as a reason to retry on another replica.
Let's define:
- We will retry (hedge) on timeout or on certain errors (like 5xx, or network errors). But we might not want to retry on 4xx (client errors) because they are likely not to succeed on another replica.
Steps for the request:
Let replicas be the list of endpoints.
We'll keep track of:
- in_flight: a dictionary of future/task to the replica index and the start time.
- completed: set of replicas that have completed (success or failure) so we don't retry on them? But we might want to retry on a failed replica after some time? We can have a blacklist.
Algorithm:
Send request to the first replica (index 0) at time 0.
Then, for each subsequent replica (up to budget), we wait for speculative_timeout and if we haven't received a response from any replica, we send to the next one.
But note: we might get a response from the first replica before the speculative timeout, then we cancel the others.
Alternatively, we can send the first request and then set a timer for the speculative timeout. When the timer fires, if we haven't got a response, we send to the next.
However, we want to be able to adjust the speculative timeout based on the observed latencies? Not in this basic version.
We'll do:
Let `current_index = 0`
Let `max_retries = budget` (so total requests = 1 + budget, but note: we start with the first and then up to budget more)
We'll have a loop that:
1. Sends to replica at `current_index`.
2. Waits for either:
a. A response from any in-flight request (then cancel the rest and return)
b. The speculative timeout (then if we haven't got a response and current_index < len(replicas)-1 and we haven't exceeded budget, then current_index++ and go to 1)
3. If we run out of replicas or budget, then we wait for the first in-flight to complete (or all) and then return an error if none succeeded.
But note: we are sending multiple requests in parallel? Actually, we are sending sequentially until we get a response? But we want to have multiple in flight at the same time?
The idea of hedging is to send multiple requests in parallel to reduce tail latency. So we want to send the next request without waiting for the previous to timeout?
Actually, the typical hedging algorithm is:
Send request to the first replica.
After a short delay (speculative timeout), if no response, send to a second replica.
After another short delay, if still no response, send to a third.
But we can also do:
Send to first.
Wait for speculative timeout or response.
If no response, send to second and also set a timer for the next speculative timeout?
However, if we wait for the first speculative timeout and then send the second, then we have two in flight. Then we wait for either to respond? And then if we don't get response from either after the next speculative timeout, we send to third?
Alternatively, we can set a fixed schedule: at time T0 send to first, at T0 + d send to second, at T0 + 2d send to third, etc.
But we want to cancel the ones we don't need once we get a response.
Let's do:
We have a list of replicas. We will send to the first one immediately.
Then, we set a timer for the speculative timeout. When that timer fires, if we haven't got a response, we send to the next replica (and set another timer for the next speculative timeout?).
Actually, we can have a loop that:
current_index = 0
while current_index < len(replicas) and current_index <= budget:
send to replicas[current_index]
if current_index == 0:
wait_time = speculative_timeout
else:
wait_time = speculative_timeout // but note: we might want to adjust?
Wait for either:
- a response from any in-flight request (then break and return)
- wait_time (then current_index++ and continue)
But this is sequential: we send one, then wait, then send next. That's not parallel.
We want to have multiple in flight. So we should send the next without waiting for the previous to timeout?
Actually, the idea is: we send the first, and then after a short time (if we don't have a response) we send the second. So we have two in flight. Then if we still don't have a response after another short time, we send the third.
So we need:
We send the first at time 0.
We set a timer for speculative timeout (say 100ms). At 100ms, if we don't have a response, we send the second.
Then we set another timer for another 100ms? But note: the second was sent at 100ms, so we want to wait 100ms from then? Or wait until 200ms from start?
Typically, we set a fixed interval between hedges. So:
Let `hedge_interval` = speculative_timeout.
We send the first at t0.
At t0 + hedge_interval, if no response, send second.
At t0 + 2*hedge_interval, if no response, send third.
So we can do:
We have a loop that runs for `budget+1` times (including the first). But we want to break early if we get a response.
We can do:
current_index = 0
start_time = now()
while current_index < len(replicas) and current_index <= budget:
send to replicas[current_index]
# Now, we wait until either:
# - we get a response from any in-flight (then break)
# - the time to send the next hedge (if we are going to send more) is reached.
# But note: we might have already sent the next one?
Actually, we can have a separate thread that schedules the next send.
Alternatively, we can use a scheduler:
We schedule the first send at time 0.
Then, if we haven't got a response by time hedge_interval, we schedule the second.
Then, if we haven't got a response by time 2*hedge_interval, we schedule the third.
But we also want to cancel the scheduled sends if we get a response.
We can use a timer for each hedge. But note: we might get a response before the next hedge is scheduled.
Let's design with a loop and a condition variable:
We have a list of in-flight requests (each with a future and the replica index).
We have a variable `response_received` that is set when any request completes.
We start the first request.
Then we set a timer for hedge_interval. When the timer fires, we check if we have a response. If not, we send the next request and set another timer.
But we have to be careful: we might get a response while we are in the process of sending the next request? We need to coordinate.
Alternatively, we can use a state machine:
State:
current_index: the next replica to send to (starting at 0)
in_flight: set of futures that are in flight.
Steps:
1. Send to current_index, add the future to in_flight, and schedule a timer for hedge_interval (if current_index < budget and we haven't got a response).
2. Wait for either:
a. Any future in in_flight to complete (then cancel all others and return)
b. The timer to fire (then if we haven't got a response and current_index < len(replicas)-1 and current_index < budget, then current_index++ and go to 1)
But note: we might get a response from the first request before the timer fires, then we cancel the timer and return.
We can implement this with a condition variable and a loop.
However, we are in an RPC context and we might be using an asynchronous framework (like asyncio) or threads.
Let's assume we are using threads and we have a blocking call to send a request that returns a future or we can wait on it.
We'll design a simple version with threads and a priority queue for timers? Or we can use a single timer that we reset.
Alternatively, we can have a separate thread that manages the hedging:
Thread 1: sends the request and waits for response (or we can have multiple threads for each request?).
But we want to limit the number of threads. So we can use a thread pool and submit tasks for each hedge.
However, we want to cancel tasks that are no longer needed. So we need a way to cancel a future. In Python, we can't cancel a thread, but we can set a flag and have the thread check? Or we can use a timeout on the request and then ignore the response if we already have one.
So we can do:
We send each request with a timeout? But then we might get a response after we already returned? We need to ignore it.
Alternatively, we can use a shared variable done that when set, we ignore any further responses.
Steps:
done = False
responses = [] # list of (replica, response, error, time)
def send_request(replica, request, timeout):
try:
response = rpc_call(replica, request, timeout=timeout)
if not done:
with lock:
responses.append((replica, response, None, time.time()))
done = True # and then we can cancel the other requests? But they are already in flight.
except Exception as e:
if not done:
with lock:
responses.append((replica, None, e, time.time()))
# We don't set done on error? Because we might want to try another.
But note: we are sending multiple requests. We want to return the first successful response.
We can have a thread for each request? But then we need to limit the number of threads.
Alternatively, we can use a thread pool and submit tasks for each hedge. But we don't know in advance how many hedges we will do.
Let's think of a simpler approach:
We send the first request and wait for it for up to `hedge_interval`. If it completes, return.
If not, we send the second request and then wait for either the first or the second (with a timeout of `hedge_interval` from now?).
But then we are waiting for two requests. We can use `concurrent.futures.wait` with `return_when=FIRST_COMPLETED`.
However, if the first request completes after we sent the second, we want to cancel the second? But we can't cancel a running thread easily.
Another idea: we set a deadline for the entire operation (say, overall_timeout) and we send requests until we get a success or until we run out of replicas or until the overall_timeout.
We can do:
start = time.time()
current_index = 0
futures = []
while current_index < len(replicas) and current_index <= budget and time.time() - start < overall_timeout:
# Calculate the time we should wait for this hedge:
# We want to send the first immediately, then after hedge_interval, then after 2*hedge_interval, etc.
# But if we are already past the time for the next hedge, we send immediately.
now = time.time()
next_hedge_time = start + (current_index * hedge_interval)
if now < next_hedge_time:
time.sleep(next_hedge_time - now)
# Send the request to replicas[current_index] with a timeout of (start + overall_timeout - now) so that we don't wait forever.
future = executor.submit(rpc_call, replicas[current_index], request, timeout=start+overall_timeout-now)
futures.append(future)
current_index += 1
# Now, we wait for any of the futures to complete, but with a timeout of (next_hedge_time for the next hedge? or until overall_timeout?)
# Actually, we want to break as soon as one completes successfully.
# We can do a non-blocking check of the futures? Or use wait with a timeout.
# We want to wait until either:
# - any future completes (then break and return the first successful one)
# - the time for the next hedge (if we are going to send more) or the overall timeout.
# But note: we are already in a loop that sends at fixed intervals. We want to break the loop if we get a success.
Then, after the loop, we check the futures for the first successful one.
However, this approach sends requests at fixed intervals, but we might have sent multiple requests and then we break when one completes.
But note: we are not cancelling the other requests. They will run until they complete or timeout. We can try to cancel them if we are using concurrent.futures and the underlying implementation supports cancellation? But if the request is already being processed, we can't cancel.
So we might have to let them run and then ignore their results.
We can do:
We keep a variable `best_response` and `best_error` and when any future completes, we check if it's successful and then set `done` and then we break the loop and then we can try to cancel the other futures? But again, cancellation is not guaranteed.
Given the complexity, let's design a simpler version that uses a fixed number of hedges (budget) and a fixed interval, and we don't cancel the in-flight requests. We just return the first successful response we get, and we wait for the overall timeout.
Steps:
Let `hedge_interval` = 100ms (for example)
Let `budget` = 2 (so we send up to 3 requests: the first and 2 hedges)
Let `overall_timeout` = 500ms.
We send the first request at time 0.
Then at 100ms, if we haven't got a response, we send the second.
Then at 200ms, if we haven't got a response, we send the third.
We then wait until either:
- any of the requests completes successfully (then return that response)
- the overall_timeout (then return an error)
We don't cancel the requests that are in flight, but we will ignore their results if we already have a success.
Implementation:
We can use a thread pool to submit the requests. We'll keep a list of futures.
We'll have a loop that schedules the next send at the appropriate time.
We'll also have a separate thread that waits for any future to complete and sets a flag when one completes.
But we are already in the main thread? We can do:
from concurrent.futures import ThreadPoolExecutor, as_completed
with ThreadPoolExecutor(max_workers=budget+1) as executor:
futures = []
start = time.time()
for i in range(min(budget+1, len(replicas))):
# Schedule send at start + i * hedge_interval
delay = i * hedge_interval
now = time.time()
if now < start + delay:
time.sleep(start + delay - now)
future = executor.submit(rpc_call, replicas[i], request, timeout=overall_timeout - (time.time() - start))
futures.append(future)
# Now, we wait for any future to complete, but with a timeout of (overall_timeout - (time.time() - start))
done, not_done = wait(futures, timeout=overall_timeout - (time.time() - start), return_when=FIRST_COMPLETED)
for future in done:
try:
response = future.result()
# If we get a response, we return it. But note: we might have multiple done? We only need the first.
return response
except Exception as e:
# This future failed, we continue to check others?
# But we are only waiting for the first completed, so we break after the first done?
# Actually, we want the first successful one. So we have to check all the done futures until we find a success?
# But wait returns when at least one is done. So we have to check all done futures for success.
pass
# If we get here, none of the done futures were successful, or we timed out.
# Then we wait for the remaining futures? Or we just return an error?
# We can wait for the remaining with a short timeout? Or just return an error.
# But note: we might have some futures that are not done yet. We can let them run? But we are exiting the context manager, which will wait for all futures? Actually, the ThreadPoolExecutor will wait for all submitted tasks to complete when we exit the context? But we don't want to wait for all if we already timed out.
We can try to cancel the not_done futures? But again, they might be running.
This is getting complex.
Let's change the design: we want to return the first successful response, and we don't care about the rest. We are willing to let the other requests continue in the background? But that might waste resources.
Alternatively, we can use a single thread and non-blocking I/O? But that's more complex.
Given the constraints, let's assume we are using an asynchronous framework (like asyncio) which can handle multiple concurrent requests and cancellation.
But the problem says "in RPC", and we are to design the hedging logic. We can leave the implementation details to the RPC framework.
So let's design the algorithm in pseudocode:
function hedged_rpc(request, replicas, hedge_interval, budget, overall_timeout):
start = current_time()
current_index = 0
in_flight = [] # list of (future, replica_index)
done = False
best_response = None
best_error = None
while current_index < len(replicas) and current_index <= budget and not done and (current_time() - start) < overall_timeout:
# Calculate the time we should send this request
scheduled_time = start + current_index * hedge_interval
now = current_time()
if now < scheduled_time:
sleep(scheduled_time - now)
# Send the request to replicas[current_index] with a timeout of (start + overall_timeout - now)
try:
future = async_rpc_call(replicas[current_index], request, timeout=start+overall_timeout-now)
in_flight.append((future, current_index))
except Exception as e:
# This replica is down? We skip and move to next?
current_index += 1
continue
# Now, we wait for any of the in_flight futures to complete, but with a timeout until the next hedge or overall_timeout.
# We want to break the loop if any future completes (success or failure) but we only break on success? Actually, we want to break on any completion and then check if it's successful?
# But we might have multiple futures in flight. We want to wait until one of them completes (either success or failure) and then if it's a success, we set done and break. If it's a failure, we continue? But note: we might have other in_flight that will complete later.
# We can wait for the first future to complete (with a timeout of min(hedge_interval, overall_timeout - (time.time()-start))) and then check.
# But note: we are in a loop that sends at fixed intervals. We don't want to wait too long because we might need to send the next hedge.
# So we wait for either:
# - the next hedge time (if we are going to send more) or overall_timeout
# - any future to complete.
wait_timeout = min(hedge_interval, overall_timeout - (current_time() - start))
if wait_timeout <= 0:
break
# Wait for any future to complete, but with a timeout of wait_timeout.
done_futures, not_done_futures = wait([f for f, _ in in_flight], timeout=wait_timeout, return_when=FIRST_COMPLETED)
for future in done_futures:
try:
response = future.result()
best_response = response
done = True
break # break out of the for loop, then we break the while loop
except Exception as e:
# This future failed, we record the error? But we might have another in flight.
best_error = e
# We don't break, because we want to wait for another future? But note: we are only waiting for the first completed. So we break the for loop and then continue the while loop?
# Actually, we break the for loop and then we will check the condition of the while loop. We might have more in_flight that are not done? We don't remove them?
# We should remove the done futures from in_flight?
pass
# Remove the done futures from in_flight?
in_flight = [(f, idx) for f, idx in in_flight if f not in done_futures]
# If we got a success (done=True), then break the while loop.
if done:
break
current_index += 1
# After the loop, if we have a best_response, return it.
if best_response is not None:
# Cancel all in_flight futures? We can try to cancel them if they are still running.
for future, _ in in_flight:
future.cancel()
return best_response
else:
# If we have an error from the last completed future, we can raise it, or if we timed out, raise a timeout error.
if best_error:
raise best_error
else:
raise TimeoutError("All hedged requests timed out")
But note: we are only waiting for the first completed future in each wait, but we might have multiple done_futures? Actually, wait returns a set of done futures. We are iterating over all done_futures and if any of them is successful, we break and return. But what if the first done future is an error and then the next one in the set is a success? We break on the first success, but we are iterating in an arbitrary order? We should check all done_futures for success and take the first success? But note: the set of done_futures might contain multiple, and we want to return the first successful one (in time? but they completed at the same time?).
Actually, we are using wait with FIRST_COMPLETED, so it returns as soon as at least one future is done. Then we check that one future? But there might be more than one done? The wait function returns two sets: done and not_done. The done set may contain more than one if multiple completed within the timeout? But with FIRST_COMPLETED, it returns when at least one is done, so the done set may have one or more.
So we should check all done futures and if any is successful, we break and return that one. If none are successful, we continue.
But note: we are removing the done futures from in_flight. Then we wait again for the remaining in_flight? But our loop will send the next hedge after the hedge_interval? Actually, we are in the while loop and we are incrementing current_index and then waiting for the next hedge? But we are also waiting for the existing in_flight.
This is getting very complex.
Given the time, let's simplify:
We are going to send up to budget+1 requests at fixed intervals of hedge_interval. We will wait for the first successful response. We will not cancel the in-flight requests, but we will return as soon as we get a success.
We can do:
futures = []
start = time.time()
for i in range(min(budget+1, len(replicas))):
# Schedule the send at start + i * hedge_interval
delay = i * hedge_interval
now = time.time()
if now < start + delay:
time.sleep(start + delay - now)
# We set the timeout for the individual request to be (overall_timeout - (time.time() - start))
future = executor.submit(rpc_call, replicas[i], request, timeout=overall_timeout - (time.time() - start))
futures.append(future)
# Now, we wait for any of the futures to complete successfully, but we don't want to wait for the ones that will fail? We can wait for any to complete and then check.
# We'll use as_completed, which yields futures as they complete.
for future in as_completed(futures, timeout=overall_timeout - (time.time() - start)):
try:
response = future.result()
# We got a success, return it.
# But note: we might have other futures still running. We can't cancel them easily.
return response
except Exception as e:
# This future failed, continue to the next.
pass
# If we get here, we timed out or all futures raised an exception.
raise TimeoutError("All hedged requests failed or timed out")
But note: the as_completed will wait for the first future to complete (success or failure) and then we check. If it's a success, we return. If it's a failure, we continue to wait for the next? Actually, the as_completed iterator will yield each future as it completes. So if the first one fails, we catch the exception and then the loop continues to wait for the next.
However, we are setting a timeout for the entire as_completed? Actually, the timeout in as_completed is the maximum time to wait for any future to complete? But we already set a timeout for each individual request? And we also have an overall timeout.
We can do:
overall_deadline = start + overall_timeout
for future in as_completed(futures, timeout=overall_timeout):
...
But note: the as_completed timeout is the time to wait for the first future? Actually, the timeout in as_completed is the maximum number of seconds to wait for any future to complete. If none of the futures complete within that timeout, it raises TimeoutError.
So we can do:
try:
for future in as_completed(futures, timeout=overall_timeout):
try:
response = future.result()
return response
except Exception:
pass
# If we get here, the as_completed timed out (no future completed in time) or we iterated through all and all failed?
# Actually, if all futures fail, the as_completed will still yield them? Then we catch the exception and continue until all are done? But if we have 3 futures and all fail, we will get 3 exceptions and then the loop ends. Then we raise an error.
raise TimeoutError("All hedged requests failed")
except TimeoutError:
# This is from as_completed timeout: no future completed in the given time.
raise TimeoutError("Hedged requests timed out")
But note: the as_completed timeout is the maximum time to wait for any future to complete. If we have set individual timeouts, then the futures might complete within that time? But if we have an overall timeout of 500ms and hedge_interval=100ms, we send at 0, 100, 200. The last request has a timeout of 500-200=300ms. So if the last request takes 400ms, then the future will raise a timeout? And then as_completed will get that future and we catch the exception? But then we might have already waited for 500ms?
This is messy.
Given the complexity, and since this is a design question, we can describe the algorithm at a high level and note that the implementation details depend on the RPC framework.
High-level algorithm:
1. Determine the number of hedges (speculative retries) we are going to do: min(budget, len(replicas)-1) because we already have the first.
2. Schedule the first request immediately to the first replica.
3. For each subsequent hedge (up to budget), schedule a request to the next replica after `hedge_interval` from the start, but only if we haven't received a successful response yet.
4. Wait for the first successful response from any of the in-flight requests, but no longer than `overall_timeout`.
5. If a successful response is received, cancel all other in-flight requests (if possible) and return the response.
6. If no successful response is received within the timeout, raise an error.
We can implement this with a timer that fires at each hedge interval to send the next request, and a mechanism to wait for any response.
But note: we might get a response from a later hedge before an earlier one? That's possible because the later hedge might go to a faster replica. So we want to return the first successful response, regardless of which replica.
So we need to monitor all in-flight requests.
Given the complexity of the implementation and the fact that we are in an RPC system that might already have async support, we can assume we have:
async def hedged_rpc(request, replicas, hedge_interval, budget, overall_timeout):
start = time.time()
tasks = []
for i in range(min(budget+1, len(replicas))):
# Schedule the task to run at start + i * hedge_interval
delay = i * hedge_interval
await asyncio.sleep(delay)
# Create a task for this request with a timeout of (overall_timeout - (time.time()-start))
try:
task = asyncio.create_task(rpc_call(replicas[i], request, timeout=overall_timeout - (time.time()-start)))
tasks.append(task)
except Exception:
# If we cannot create the task (maybe the replica is down?), skip.
continue
# Now, we wait for the first task that completes successfully.
while tasks:
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
for task in done:
try:
response = await task
# Cancel all pending tasks
for p in pending:
p.cancel()
return response
except Exception:
# This task failed, remove it from tasks and continue?
tasks.remove(task)
continue
# If we get here, all tasks failed.
raise Exception("All hedged requests failed")
But note: the asyncio.wait will return when at least one task is done. Then we check that task. If it's successful, we cancel the rest and return. If it fails, we remove it from the tasks list and then wait again? But we are in a while loop that will call asyncio.wait again on the remaining tasks.
However, we are already waiting for the tasks in the asyncio.wait and then we remove the done ones. But note: the asyncio.wait returns the done and pending sets. We are only processing the done ones. Then we loop and wait again for the remaining.
But we have to be careful: the asyncio.wait in the next iteration will wait for the remaining tasks. And we are removing the failed ones from tasks so we don't wait for them again.
Also, we are setting a timeout for each individual rpc_call? We set the timeout when creating the task? Actually, the rpc_call function should respect the timeout. We are passing the timeout as overall_timeout - (time.time()-start), which is the remaining time until the overall deadline.
But note: the asyncio.wait does not have a timeout? We are waiting indefinitely for one of the tasks to complete? But we have set a timeout on each individual rpc_call, so each task will eventually complete (with success or exception) within the overall_timeout? Not necessarily: if the overall_timeout is 500ms and we send the last request at 200ms with a timeout of 300ms, then it will complete by 500ms. So by the time we finish the loop, we should have all tasks completed? But we are waiting for the first successful one, and if none are successful, we will wait until all tasks are done (because we keep waiting until tasks is empty).
However, if we have a task that times out, it will raise an exception and we remove it. Then we wait for the next. So we will eventually wait for all tasks to complete (or until the overall_timeout? but each task has a timeout that ensures it completes by the overall deadline?).
But what if the overall_timeout is 500ms and we send the first task at 0ms with a timeout of 500ms, then it will complete at 500ms at the latest. So by the time we finish the loop, we will have all tasks completed? Not exactly: if we get a successful response at 100ms, we cancel the others. But if we don't get any success, we will wait for each task to complete (which will be by 500ms at the latest). So the total time should not exceed overall_timeout.
This seems reasonable.
However, we are not accounting for the time we spend in the loop? But note: we are using asyncio.sleep to schedule the next send, and then we wait for tasks. The time spent in the loop is negligible.
But what if the hedge_interval is 100ms and we have 3 hedges (so 0ms, 100ms, 200ms). Then we wait for the first task to complete. If the first task takes 400ms, then at 100ms we send the second, at 200ms we send the third. Then we wait for any task to complete. The second might complete at 150ms? Then we return that. But note: the first task is still running and we cancel it? We cancel the pending tasks, but the first task is already done? We only cancel the pending ones. So we cancel the third and the first is already done? Actually, when we get a done task, we cancel the pending ones. The first task might be in the done set? Then we don't cancel it.
So the above asyncio version seems to work.
But note: we are creating tasks for each hedge, and we are waiting for them. We are also using asyncio.sleep to schedule the next hedge. This is fine.
However, we are not limiting the number of concurrent requests? We are sending up to budget+1 requests in parallel. That's the point of hedging.
Now, let's add safeguards:
- We don't want to hedge to too many replicas? We are limited by the budget and the number of replicas.
- We want to avoid sending requests to replicas that are known to be down? We can have a blacklist.
We can modify the algorithm to skip replicas that are blacklisted.
Also, we might want to adjust the hedge_interval based on past latencies? That's an advanced feature.
For simplicity, we assume fixed hedge_interval and budget.
Also, we might want to have a minimum time between hedges? We are using fixed interval.
So the asyncio version is a good starting point.
But note: the problem says "Build a request hedging in RPC", and we are using asyncio. What if the RPC framework is not asyncio? We can do a similar thing with threads and conditions.
Given the complexity of the threaded version, and since the problem is about the algorithm, we can present the asyncio version as an example.
However, the problem does not specify the language or framework.
Let's write the algorithm in a language-agnostic way:
Algorithm HedgedRPC(request, replicas, hedge_interval, budget, overall_timeout):
start = current_time()
tasks = [] // list of pending requests (each with a future or promise)
for i from 0 to min(budget, len(replicas)-1):
// Schedule the i-th hedge (the first hedge is i=0, which is the initial request)
delay = i * hedge_interval
wait until start + delay (or until we get a response, whichever comes first)
if we already have a successful response, break
else:
send request to replicas[i] with a timeout of (start + overall_timeout - current_time())
add the future to tasks
// Now, wait for the first successful response from any of the tasks, but no longer than overall_timeout
while tasks is not empty:
wait for any task to complete (with a timeout of (start + overall_timeout - current_time()))
if a task completed successfully:
cancel all other tasks
return the response
else:
remove the task from tasks (it failed)
if we get here, all tasks failed, raise an error
But note: the above algorithm does not account for the fact that we might have sent the first request and then we are waiting for the next hedge interval to send the next? Actually, we are sending the first request immediately, then waiting for hedge_interval, then sending the second, etc. But we are also waiting for any task to complete at each step? Actually, we are not waiting in between sends? We are sending at fixed intervals and then at the end we wait for any task? That might not be what we want.
We want to send the next hedge only if we haven't received a successful response by the time the hedge interval has passed. So we need to check after each hedge interval.
Revised:
start = current_time()
tasks = []
for i in range(0, min(budget+1, len(replicas))):
// Wait until it's time to send the i-th request, or until we have a success.
now = current_time()
scheduled_time = start + i * hedge_interval
if now < scheduled_time and not have_success:
wait until scheduled_time or until we have a success (with a timeout of scheduled_time - now)
if have_success:
break
// Send the i-th request
try:
future = send_request(replicas[i], timeout=start+overall_timeout-now)
tasks.append(future)
except Exception:
// Failed to send? skip this replica.
continue
// Now, we wait for any task to complete, but only until the next hedge time or overall_timeout.
// But note: we might have just sent a request and we want to give it some time? Actually, we want to break as soon as any task completes (success or failure) and then if it's a success, we break the loop.
// We wait for any task to complete, but with a timeout of min(hedge_interval, overall_timeout - (current_time()-start))
timeout = min(hedge_interval, overall_timeout - (current_time()-start))
if timeout <= 0:
break
done_tasks = wait_for_any(tasks, timeout=timeout)
for task in done_tasks:
if task completed successfully:
have_success = True
best_response = task.result()
// We break out of the for loop and then break the outer loop.
break
else:
// Remove the failed task from tasks?
tasks.remove(task)
// If we have a success, break the outer loop.
if have_success:
break
// After the loop, if we have a best_response, cancel all remaining tasks and return best_response.
// Otherwise, raise an error.
This is similar to the asyncio version but in a more generic way.
Given the complexity, I think the asyncio version is clearer.
Now, let's write the code in Python using asyncio, but note: the rpc_call function might be synchronous? We assume we have an async rpc_call.
If we don't have async, we can run the synchronous rpc_call in a thread pool.
But to keep it simple, let's assume async.
Code:
import asyncio
async def hedged_rpc(request, replicas, hedge_interval=0.1, budget=2, overall_timeout=0.5):
start = asyncio.get_event_loop().time()
tasks = []
num_hedges = min(budget+1, len(replicas))
for i in range(num_hedges):
# Wait until it's time to send this hedge, or until we have a success (but we check after each wait)
scheduled_time = start + i * hedge_interval
now = asyncio.get_event_loop().time()
if now < scheduled_time:
await asyncio.sleep(scheduled_time - now)
# After sleeping, check if we already have a success? But we break only when we get a success in the wait below.
# Actually, we break the loop when we get a success, so we don't send more.
# Send the request
try:
# We assume rpc_call is an async function that takes a replica, request, and timeout.
# The timeout is the time from now until the overall deadline.
timeout = overall_timeout - (asyncio.get_event_loop().time() - start)
if timeout <= 0:
break
task = asyncio.create_task(rpc_call(replicas[i], request, timeout=timeout))
tasks.append(task)
except Exception:
# Skip this replica if we cannot create the task (maybe the replica is down?)
continue
# Wait for any task to complete, but with a timeout of hedge_interval or remaining time?
# We want to wait until either:
# - any task completes (so we can check for success)
# - the next hedge time (if we are going to send another) or the overall timeout.
# But note: we are in a loop that will send the next hedge after hedge_interval. So we wait for at most hedge_interval?
wait_timeout = min(hedge_interval, overall_timeout - (asyncio.get_event_loop().time() - start))
if wait_timeout <= 0:
break
done, pending = await asyncio.wait(tasks, timeout=wait_timeout, return_when=asyncio.FIRST_COMPLETED)
for task in done:
try:
response = await task
# We got a success, cancel the rest and return.
for p in pending:
p.cancel()
return response
except Exception:
# This task failed, remove it from tasks.
tasks.remove(task)
continue
# If we get here, no task completed successfully in the wait_timeout, so we continue to the next hedge.
# If we exit the loop without returning, then we have no success.
# We might have some tasks still running? We should wait for them? But we are at the end of the loop and we might have exceeded the overall_timeout?
# We can wait for the remaining tasks with the remaining time?
if tasks:
try:
done, pending = await asyncio.wait(tasks, timeout=overall_timeout - (asyncio.get_event_loop().time() - start))
for task in done:
try:
response = await task
return response
except Exception:
continue
except asyncio.TimeoutError:
pass
raise Exception("Hedged RPC failed: no successful response")
However, this is still complex and might have issues.
Given the time, I think we should present a high-level design and note that the implementation can vary.
Let's summarize:
We are building a request hedging mechanism that:
- Sends the same request to multiple replicas (speculative retries) to reduce tail latency.
- Uses a budget to limit the number of hedges (so we don't send too many requests).
- Uses a fixed interval (hedge_interval) between sending to the next replica.
- Has an overall timeout for the entire operation.
- Returns the first successful response.
- Cancels the remaining in-flight requests once a success is received (if possible).
Safeguards:
- We limit the number of hedges by the budget and the number of available replicas.
- We set timeouts on each individual request to ensure they don't run forever.
- We have an overall timeout to bound the total time.
Additional safeguards (not implemented above):
- Blacklisting replicas that are down or consistently failing.
- Dynamically adjusting the hedge_interval based on observed latencies.
- Limiting the total number of concurrent hedged requests across the system to avoid overloading.
We can also consider:
- Only hedging for read-only requests? Because hedging might cause duplicate writes? So we must ensure that the request is idempotent.
This is a basic design. In practice, systems like Google's gRPC have hedging built-in.
Given the complexity of the implementation, we might choose to use an existing library if available.
But for the purpose of this exercise, we have designed the algorithm.
Note: The above code is not tested and might have race conditions or logical errors.
We can simplify the asyncio version by not doing the intermediate waits? We can schedule all the tasks at the beginning (with delays) and then wait for the first success? But then we are not breaking the loop early? We are scheduling all tasks up front? That's okay because we are using asyncio.sleep to delay the start of each task. Then we wait for any task to complete? But then we are not cancelling the ones that haven't started? We can cancel them.
Alternatively, we can schedule each task with a delay and then wait for the first success with a timeout of overall_timeout.
Let's try:
async def hedged_rpc(request, replicas, hedge_interval=0.1, budget=2, overall_timeout=0.5):
start = asyncio.get_event_loop().time()
tasks = []
num_hedges = min(budget+1, len(replicas))
for i in range(num_hedges):
delay = i * hedge_interval
async def delayed_request(replica, request, timeout):
await asyncio.sleep(delay)
return await rpc_call(replica, request, timeout=timeout)
timeout = overall_timeout - (asyncio.get_event_loop().time() - start) # but note: this timeout is for the rpc_call, not for the delayed_request?
# Actually, the delayed_request will sleep for delay and then call rpc_call. The timeout for rpc_call should be the remaining time after the sleep.
# We can pass the overall deadline and then in delayed_request, we compute the remaining time after sleep.
# Alternatively, we can set a timeout for the entire delayed_request? But then we might cancel the sleep? Not easily.
# We can do:
async def delayed_request(replica, request, deadline):
now = asyncio.get_event_loop().time()
if now >= deadline:
raise TimeoutError("Overall timeout")
await asyncio.sleep(min(delay, deadline - now))
if asyncio.get_event_loop().time() >= deadline:
raise TimeoutError("Overall timeout")
return await rpc_call(replica, request, timeout=deadline - asyncio.get_event_loop().time())
task = asyncio.create_task(delayed_request(replicas[i], request, start+overall_timeout))
tasks.append(task)
# Now wait for the first successful task.
for task in asyncio.as_completed(tasks, timeout=overall_timeout):
try:
response = await task
# Cancel the rest
for t in tasks:
t.cancel()
return response
except Exception:
continue
raise TimeoutError("Hedged RPC failed")
This version schedules all the tasks with delays, and then we wait for the first one to complete. The delayed_request function will sleep for the required delay and then make the RPC call with the remaining time.
But note: the asyncio.as_completed returns an iterator that yields tasks as they complete. We are using a timeout for the entire as_completed? Actually, the timeout in as_completed is the time to wait for the first task to complete? But we have already set a deadline for each task, so they will all complete by the overall deadline? Not necessarily: if the last task starts at 200ms and has a timeout of 300ms, it will complete by 500ms. So we will wait until 500ms for the first task? But if the first task completes at 100ms, we return early.
This seems simpler.
However, we are creating tasks for all hedges up front, even if we get a success early. But we are cancelling the remaining tasks when we get a success. But the tasks that haven't started yet? They are sleeping. When we cancel them, the sleep will be cancelled? Yes, in asyncio, cancelling a task that is sleeping will raise a CancelledError in the sleep.
So this version is simpler and does the same.
But note: we are creating tasks for all hedges, even if we don't need them? We are creating up to budget+1 tasks. That's acceptable.
So we can use this version.
However, we must be cautious: if we have a large budget and many replicas, we might create too many tasks? But the budget is usually small (like 2 or 3).
Let's adjust: we are creating tasks for all hedges, but we are delaying the start of each by hedge_interval. So the first task starts at 0, the second at hedge_interval, etc.
This matches the hedging strategy.
Now, what about the blacklist? We can skip replicas that are blacklisted. We can have a set of blacklisted replicas and skip them in the loop.
Also, we might want to adjust the hedge_interval based on past latencies? That's an advanced feature.
So the final design:
- We have a list of replicas (possibly filtered by blacklist).
- We set a hedge_interval (e.g., 100ms) and a budget (e.g., 2).
- We set an overall timeout (e.g., 500ms).
- We schedule up to budget+1 requests (or until we run out of replicas) at intervals of hedge_interval.
- We wait for the first successful response and cancel the rest.
This is a basic hedging mechanism.
Let's write the final code with blacklist:
async def hedged_rpc(request, replicas, hedge_interval=0.1, budget=2, overall_timeout=0.5, blacklist=None):
if blacklist is None:
blacklist = set()
start = asyncio.get_event_loop().time()
tasks = []
# Filter out blacklisted replicas
available_replicas = [r for r in replicas if r not in blacklist]
num_hedges = min(budget+1, len(available_replicas))
for i in range(num_hedges):
delay = i * hedge_interval
async def delayed_request(replica, request, deadline):
now = asyncio.get_event_loop().time()
if now >= deadline:
raise TimeoutError("Overall timeout")
# Sleep for the required delay, but not beyond the deadline.
sleep_time = min(delay, deadline - now)
await asyncio.sleep(sleep_time)
if asyncio.get_event_loop().time() >= deadline:
raise TimeoutError("Overall timeout")
return await rpc_call(replica, request, timeout=deadline - asyncio.get_event_loop().time())
task = asyncio.create_task(delayed_request(available_replicas[i], request, start+overall_timeout))
tasks.append(task)
try:
for task in asyncio.as_completed(tasks, timeout=overall_timeout):
try:
response = await task
# Cancel the rest
for t in tasks:
t.cancel()
return response
except Exception:
continue
except asyncio.TimeoutError:
pass
finally:
# Cancel any remaining tasks
for t in tasks:
t.cancel()
raise Exception("Hedged RPC failed: no successful response")
This code has an issue: the delayed_request function is defined inside the loop and uses the loop variable i and delay. But because of the way Python closures work, it will capture the variable i and delay by reference, so when the function runs, i and delay might have changed? Actually, we are creating a new function for each iteration, but the i and delay are the ones at the time of the function definition? In Python, the closure captures the variable, not the value. So if we do:
for i in range(3):
def f():
print(i)
tasks.append(f)
Then when we run f, it will print 2 for all because i is 2 at the end.
So we need to bind the current values of i and delay. We can do:
async def delayed_request(replica, request, deadline, delay_value):
... use delay_value ...
task = asyncio.create_task(delayed_request(available_replicas[i], request, start+overall_timeout, delay))
But note: we are also using i to index available_replicas. We are passing available_replicas[i] as an argument, so that's bound.
Let's fix:
for i in range(num_hedges):
delay_value = i * hedge_interval
replica = available_replicas[i]
async def delayed_request(replica, request, deadline, delay_value):
now = asyncio.get_event_loop().time()
if now >= deadline:
raise TimeoutError("Overall timeout")
sleep_time = min(delay_value, deadline - now)
await asyncio.sleep(sleep_time)
if asyncio.get_event_loop().time() >= deadline:
raise TimeoutError("Overall timeout")
return await rpc_call(replica, request, timeout=deadline - asyncio.get_event_loop().time())
task = asyncio.create_task(delayed_request(replica, request, start+overall_timeout, delay_value))
tasks.append(task)
This should work.
However, note that the rpc_call function might be synchronous. If it is, we should run it in a thread pool. We can do:
return await asyncio.to_thread(rpc_call, replica, request, timeout=deadline - asyncio.get_event_loop().time())
But then the timeout for the thread? We are passing a timeout to the synchronous rpc_call? We assume the synchronous rpc_call has a timeout parameter.
Alternatively, we can use asyncio.wait_for around the rpc_call? But if rpc_call is synchronous, we run it in a thread and then use asyncio.wait_for on the thread task? But then we are setting a timeout twice? We are already passing a timeout to rpc_call and also using asyncio.wait_for? That's redundant.
We assume the rpc_call function respects the timeout.
Given the complexity, we'll leave it as is.
This is a basic implementation. In production, we would need more error handling and logging.
Also, we might want to adjust the hedge_interval based on the observed latencies of the replicas. We can keep a moving average of the latency for each replica and then set the hedge_interval to be, say, the 50th percentile of the latencies? Or a multiple of the average? That's an advanced topic.
We have built a request hedging mechanism with speculative retries, budgets (limiting the number of hedges), and safeguards (timeouts, blacklist, cancellation).
We return the first successful response and cancel the rest.
This should improve the tail latency of RPC calls.
I'll design a comprehensive request hedging system for RPC with speculative retries, budgets, and safeguards. This is a sophisticated pattern used in distributed systems to improve latency and reliability.
Core Hedging Strategy
1. Speculative Retries (Hedging)
class HedgedRPCClient:
def __init__(self, endpoints, config):
self.endpoints = endpoints # List of replica addresses
self.config = config
self.stats = {} # Per-replica stats
self.circuit_breakers = {} # Per-replica circuit breakers
self.budget_token_bucket = TokenBucket(
capacity=config.max_concurrent_hedges,
refill_rate=config.hedge_budget_per_second
)
async def hedged_call(self, method, request, timeout=None):
"""
Execute RPC with speculative retries to multiple replicas.
Returns first successful response.
"""
deadline = time.time() + (timeout or self.config.default_timeout)
hedge_deadline = time.time() + self.config.hedge_interval
# 1. Initial request to primary
primary = self.select_primary()
primary_task = asyncio.create_task(
self.call_with_circuit_breaker(primary, method, request, deadline)
)
# 2. Schedule speculative hedges
hedge_tasks = [primary_task]
active_hedges = 1
while (time.time() < hedge_deadline and
active_hedges < self.config.max_hedges and
self.budget_token_bucket.try_consume()):
# Select next replica (round-robin with scoring)
replica = self.select_next_replica(exclude=[primary])
if not replica:
break
# Check circuit breaker
if self.circuit_breakers.get(replica) == CircuitState.OPEN:
continue
task = asyncio.create_task(
self.call_with_circuit_breaker(replica, method, request, deadline)
)
hedge_tasks.append(task)
active_hedges += 1
# Small stagger to avoid thundering herd
await asyncio.sleep(self.config.hedge_stagger)
# 3. Wait for first success
try:
done, pending = await asyncio.wait(
hedge_tasks,
return_when=asyncio.FIRST_COMPLETED
)
# Cancel remaining tasks
for task in pending:
task.cancel()
# Get result from first successful task
for task in done:
try:
result = task.result()
self.on_success(primary if task == primary_task else replica)
return result
except RPCError as e:
self.on_failure(replica, e)
continue
raise AllHedgesFailedError("All hedged requests failed")
except asyncio.TimeoutError:
self.cancel_all(hedge_tasks)
raise
2. Budget Management System
class TokenBucket:
"""Distributed budget limiter for hedged requests"""
def __init__(self, capacity, refill_rate):
self.capacity = capacity
self.tokens = capacity
self.refill_rate = refill_rate # tokens/second
self.last_refill = time.time()
self.lock = asyncio.Lock()
async def try_consume(self, tokens=1):
async with self.lock:
now = time.time()
# Refill tokens based on elapsed time
delta = now - self.last_refill
self.tokens = min(
self.capacity,
self.tokens + delta * self.refill_rate
)
self.last_refill = now
if self.tokens >= tokens:
self.tokens -= tokens
return True
return False
class AdaptiveBudgetManager:
"""Dynamically adjusts hedge budget based on system load"""
def __init__(self):
self.global_budget = 100 # tokens per second
self.load_metrics = LoadMonitor()
async def can_hedge(self, priority=Priority.NORMAL):
"""Check if budget allows hedging"""
base_cost = 1
priority_multiplier = {
Priority.CRITICAL: 1.0,
Priority.HIGH: 0.8,
Priority.NORMAL: 0.5,
Priority.LOW: 0.2
}[priority]
cost = base_cost * priority_multiplier
# Adjust based on system load
load_factor = await self.load_metrics.get_load_factor()
effective_cost = cost * load_factor
return await token_bucket.try_consume(effective_cost)
3. Safeguards & Circuit Breakers
class CircuitBreaker:
"""Per-replica circuit breaker with exponential backoff"""
def __init__(self, failure_threshold=5, recovery_timeout=30):
self.state = CircuitState.CLOSED
self.failure_count = 0
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self.last_failure_time = None
self.success_streak = 0
async def allow_request(self):
if self.state == CircuitState.OPEN:
if time.time() - self.last_failure_time > self.recovery_timeout:
self.state = CircuitState.HALF_OPEN
return True
return False
return True
def on_success(self):
if self.state == CircuitState.HALF_OPEN:
self.success_streak += 1
if self.success_streak >= 3:
self.state = CircuitState.CLOSED
self.failure_count = 0
elif self.state == CircuitState.CLOSED:
self.failure_count = max(0, self.failure_count - 1)
def on_failure(self, error):
self.last_failure_time = time.time()
if self.state == CircuitState.CLOSED:
self.failure_count += 1
if self.failure_count >= self.failure_threshold:
self.state = CircuitState.OPEN
self.success_streak = 0
elif self.state == CircuitState.HALF_OPEN:
self.state = CircuitState.OPEN
self.success_streak = 0
class HedgingSafeguards:
"""Global system safeguards"""
def __init__(self):
self.global_rate_limiter = RateLimiter(
max_requests_per_second=1000,
burst_size=100
)
self.quota_manager = QuotaManager()
self.anomaly_detector = AnomalyDetector()
async def validate_hedge(self, request, current_hedge_count):
"""Validate if hedging is allowed"""
# 1. Check global rate limit
if not await self.global_rate_limiter.try_acquire():
raise HedgeBudgetExhaustedError("Global rate limit exceeded")
# 2. Check per-client quota
if not await self.quota_manager.check_quota(request.client_id):
raise QuotaExceededError("Client quota exceeded")
# 3. Check for anomalies (sudden spike in errors/latency)
if await self.anomaly_detector.is_anomalous():
raise SystemStressError("System under abnormal load")
# 4. Check hedge depth limit
if current_hedge_count >= MAX_HEDGE_DEPTH:
raise HedgeDepthExceededError("Maximum hedge depth reached")
return True
4. Intelligent Replica Selection
class ReplicaSelector:
"""Smart replica selection with multiple strategies"""
def __init__(self, endpoints):
self.endpoints = endpoints
self.latency_history = {ep: [] for ep in endpoints}
self.error_rates = {ep: 0.0 for ep in endpoints}
self.load_scores = {ep: 0.0 for ep in endpoints}
def select_primary(self):
"""Select best primary based on composite score"""
return min(
self.endpoints,
key=lambda ep: self.composite_score(ep)
)
def select_next_replica(self, exclude=None, count=1):
"""Select next best replicas for hedging"""
exclude = exclude or []
candidates = [ep for ep in self.endpoints if ep not in exclude]
# Sort by score (lower is better)
scored = sorted(
candidates,
key=lambda ep: (
self.latency_percentile(ep, 95), # P95 latency
self.error_rates[ep], # Error rate
self.load_scores[ep] # Current load
)
)
return scored[:count]
def composite_score(self, endpoint):
"""Calculate composite score (lower is better)"""
p95 = self.latency_percentile(endpoint, 95) or 1000
error_rate = self.error_rates[endpoint]
load = self.load_scores[endpoint]
return (
0.4 * p95 +
0.3 * (error_rate * 1000) + # Scale error rate
0.3 * load
)
def update_metrics(self, endpoint, latency, success):
"""Update endpoint metrics"""
# Update latency history (keep last 100 samples)
self.latency_history[endpoint].append(latency)
if len(self.latency_history[endpoint]) > 100:
self.latency_history[endpoint].pop(0)
# Update error rate (exponential moving average)
alpha = 0.1
current_error = 0.0 if success else 1.0
self.error_rates[endpoint] = (
alpha * current_error +
(1 - alpha) * self.error_rates[endpoint]
)
5. Configuration & Tuning
hedging:
enabled: true
# Speculative retry parameters
max_hedges: 3 # Maximum concurrent hedges (including primary)
hedge_interval: 50ms # Time before sending next hedge
hedge_stagger: 10ms # Stagger between hedge sends
# Budget management
hedge_budget_per_second: 100 # Max hedges per second globally
max_concurrent_hedges: 10 # Max concurrent hedges per client
# Timeouts
default_timeout: 500ms
hedge_timeout_adjustment: true # Adjust based on historical latency
# Selection strategy
selection_strategy: "composite_score" # latency_p95, error_rate, load
exclude_blacklisted: true
min_healthy_replicas: 2 # Minimum healthy replicas required
# Safeguards
circuit_breaker:
failure_threshold: 5
recovery_timeout: 30s
half_open_max_calls: 3
anomaly_detection:
enabled: true
error_rate_threshold: 0.1 # 10% error rate
latency_spike_factor: 2.0 # 2x normal latency
window_size: 60s
6. Integration Example
# Usage with gRPC-style client
class SmartGRPCClient:
def __init__(self, service_config):
self.hedger = HedgedRPCClient(
endpoints=service_config.endpoints,
config=service_config.hedging_config
)
async def call(self, method, request, timeout=None, priority=Priority.NORMAL):
# Validate request
if not await self.hedger.safeguards.validate_hedge(
request,
current_hedge_count=0
):
# Fallback to non-hedged call or reject
return await self.non_hedged_call(method, request, timeout)
try:
# Execute hedged call
response = await self.hedger.hedged_call(
method,
request,
timeout=timeout
)
return response
except HedgeBudgetExhaustedError:
# Budget exceeded, try single replica with backoff
return await self.backoff_call(method, request, timeout)
except AllHedgesFailedError:
# Circuit breaker likely opened, try alternative service
return await self.fallback_call(method, request, timeout)
7. Monitoring & Metrics
class HedgingMetrics:
"""Collect metrics for hedging behavior"""
METRICS = {
"hedge_attempts_total": "Counter",
"hedge_success_total": "Counter",
"hedge_failure_total": "Counter",
"hedge_latency_ms": "Histogram",
"hedges_per_request": "Histogram",
"budget_utilization": "Gauge",
"circuit_breaker_state": "Gauge",
"replica_latency": "Histogram"
}
def record_hedge(self, num_hedges, latency, success, replica):
metrics.hedge_attempts_total.inc()
metrics.hedge_latency_ms.observe(latency * 1000)
metrics.hedges_per_request.observe(num_hedges)
if success:
metrics.hedge_success_total.inc()
else:
metrics.hedge_failure_total.inc()
# Record per-replica metrics
tags = {"replica": replica}
metrics.replica_latency.labels(**tags).observe(latency * 1000)
Key Design Principles
- Progressive Disclosure: Start with 1 request, add hedges only after
hedge_interval
- Budget Awareness: Global and per-client budgets prevent system overload
- Fast Failure: Cancel all pending hedges on first success
- Circuit Protection: Per-replica circuit breakers prevent cascading failures
- Adaptive Selection: Use real-time metrics for replica selection
- Graceful Degradation: Fallback to non-hedged calls when budgets exhausted
- Observability: Comprehensive metrics for all hedging decisions
When to Hedge
- Read-heavy operations (idempotent)
- Low QPS requests where tail latency matters
- Geo-distributed services with variable network latency
- Cache misses where backend latency is unpredictable
When NOT to Hedge
- Write operations (unless idempotent with deduplication)
- Already overloaded systems (budget will prevent this)
- Strong consistency requirements (hedging can cause duplicates)
- High QPS services (budget will limit hedging)
This design provides robust hedging with multiple layers of protection against system overload while optimizing for tail latency reduction. The token bucket budget system ensures hedging doesn't destabilize the system, and the circuit breakers provide fast failure isolation.