Hedged Requests Race Replicas
Start a backup replica after a short tail delay and race it against the primary, keeping the first answer so slow replicas stop dominating latency.
Code
// Hedging: if the primary replica is still in flight after a short tail
// delay, start a second replica and keep whichever answers first
function fakeReplica(name, ms) {
return () => new Promise((resolve) => setTimeout(() => resolve(name + ' data'), ms));
}
function hedge(primaryTask, backupTask, tailMs) {
const primary = primaryTask();
const backup = new Promise((resolve) => {
setTimeout(() => resolve(backupTask()), tailMs);
});
return Promise.race([primary, backup]);
}
async function main() {
// replicaA is slow (90ms), replicaB fast (40ms): the hedge fires at 25ms
const winner = await hedge(fakeReplica('replicaA', 90), fakeReplica('replicaB', 40), 25);
console.log('first answer:', winner);
console.log('winner is backup:', winner.startsWith('replicaB'));
// replicaA answers in 15ms, before the tail: the backup never launches
const quick = await hedge(fakeReplica('replicaA', 15), fakeReplica('replicaB', 40), 25);
console.log('primary kept:', quick);
console.log('no backup needed:', quick.startsWith('replicaA'));
}
main();Output
Captured from a sandboxed run of this snippet in the build pipeline.
first answer: replicaB data
winner is backup: true
primary kept: replicaA data
no backup needed: trueBehavior at a glance
Hedged Requests Race Replicas comes down to the functions fakeReplica, hedge and main.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Points of care
- Nothing to vet in a supply-chain review — the file pulls in no packages.
Using it
Entry signature: function fakeReplica(name, ms)
The run prints first answer:, winner is backup:, primary kept: — each prefix names the step that produced it.
Running the file executes main, which drives hedge and fakeReplica in order.
Key statements
return () => new Promise((resolve) => setTimeout(() => resolve(name + ' data'), ms));
const backup = new Promise((resolve) => {
setTimeout(() => resolve(backupTask()), tailMs);
});
return Promise.race([primary, backup]);
Interactive Tools for This Topic
FAQ
- What does Hedged Requests Race Replicas print when run?
- Invoke the file as-is — the `first answer:`, `winner is backup:`, `primary kept:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.