Hedged Requests First Response Wins
Race two replica calls through select and keep the first response, then cancel the derived context so the losing goroutine exits instead of leaking.
Code
package main
import (
"context"
"fmt"
"time"
)
// 对冲请求:向多个副本同时发起,返回带缓冲的结果通道
func replica(ctx context.Context, name string, delay time.Duration) <-chan string {
ch := make(chan string, 1)
go func() {
select {
case <-time.After(delay):
ch <- name + " answered"
case <-ctx.Done():
}
}()
return ch
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
first := replica(ctx, "replica-a", 30*time.Millisecond)
second := replica(ctx, "replica-b", 80*time.Millisecond)
// first-wins:谁先到用谁,慢副本不再等待
select {
case res := <-first:
fmt.Println("winner:", res)
case res := <-second:
fmt.Println("winner:", res)
}
// 胜者已定:cancel 让慢 goroutine 从 ctx.Done 退出;缓冲为 1
// 即使它已完成发送也不会阻塞泄漏
cancel()
time.Sleep(10 * time.Millisecond)
fmt.Println("loser drained via context")
}A walk over the statements
Hedged Requests First Response Wins keeps everything in the functions replica and main.
The goroutine/channel pair splits producer and consumer while keeping the handoff race-free. Cleanup is attached with defer, so it runs on every exit path of the function.
Using it
The main signature takes this shape: func replica(ctx context.Context, name string, delay time.Duration) <-chan string
Output lines are prefixed (winner:, loser drained via context), making the effect of each step easy to trace.
The entry point wires replica together — run it once and the whole demo flows.
Key statements
func replica(ctx context.Context, name string, delay time.Duration) <-chan string {
ch := make(chan string, 1)
go func() {
select {
case <-time.After(delay):
ch <- name + " answered"
case <-ctx.Done():
}
}()
return ch
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
Interactive Tools for This Topic
FAQ
- What does Hedged Requests First Response Wins print when run?
- No setup needed: run the file and look for labeled lines like `winner:`, `loser drained via context` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.