Channel Fastest Response Wins Race

Launch several workers that race to produce a value, then take the first arrival from a shared channel and cancel nothing because losers simply finish unused.

GoResilience

Code

gosnippet
38 lines
package main

import (
	"fmt"
	"sync"
	"time"
)

// query 模拟不同延迟的上游;最快完成者先进入 winner channel
func query(name string, delay time.Duration, winner chan<- string, wg *sync.WaitGroup) {
	defer wg.Done()
	time.Sleep(delay)
	winner <- name
}

func main() {
	winner := make(chan string, 3) // 缓冲 3:落败者写入也不阻塞
	var wg sync.WaitGroup

	for _, r := range []struct {
		name  string
		delay time.Duration
	}{
		{"primary", 90 * time.Millisecond},
		{"replica", 40 * time.Millisecond},
		{"cache", 15 * time.Millisecond},
	} {
		wg.Add(1)
		go query(r.name, r.delay, winner, &wg)
	}

	// 首个到达者胜出:channel 天然按完成时间交付
	first := <-winner
	fmt.Println("fastest response:", first)

	wg.Wait()
	fmt.Println("all replicas finished; losers drained later")
}

The race to the first response

Everything effective happens in the functions query and main — everything else is wiring.

Iteration happens inside for _, r := range []struct — everything outside it runs once. A goroutine does the work; a channel carries the result back, so the two contexts never share memory directly. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.

Watch out for

  • It is dependency-free in the strict sense — the import list, if any, is empty of packages.

Applying it

Entry signature: func query(name string, delay time.Duration, winner chan<- string, wg *sync.WaitGroup)

Output lines are prefixed (fastest response:, all replicas finished; losers drained later), so each printed result carries the name of its step.

The entry point wires query together — run it once and the whole demo flows.

Statements that matter

func query(name string, delay time.Duration, winner chan<- string, wg *sync.WaitGroup) {
	defer wg.Done()
	time.Sleep(delay)
	winner <- name
}
for _, r := range []struct {
	name  string
	delay time.Duration
}{
	{"primary", 90 * time.Millisecond},
	{"replica", 40 * time.Millisecond},
	{"cache", 15 * time.Millisecond},
} {
	wg.Add(1)
	go query(r.name, r.delay, winner, &wg)
}
winner := make(chan string, 3) // 缓冲 3:落败者写入也不阻塞

Interactive Tools for This Topic

FAQ

What does Channel Fastest Response Wins Race print when run?
Run it as a complete program — the output lines carry labels such as `fastest response:`, `all replicas finished; losers drained later`.