Scatter-gather under a deadline
A price aggregator that fans out to unreliable vendors and always answers on time: partial results as a normal outcome, no goroutine leaks, and cancellation that reaches the remote side.
The question#
How do you query many services at once and still give a bounded answer when some of them are slow or broken? The usual failure is a fan-out whose latency is set by its worst dependency, or one that leaks work after it has replied.
The setup#
+--> vendor acme (fast) --+
client --> aggregator +--> vendor globex (variable) --+--> best of what arrived in 300 ms
+--> vendor initech (fails 50%) --+
+--> vendor umbrella (always too slow) --+
The pattern itself is a generic Gather function of about 40 lines; the pricing use case sits on top of it.
What it shows#
- The deadline is the only timer. The gather loop selects on results and
ctx.Done(), so the response returns at 300 ms even while a vendor is still hanging. - Partial results are a normal outcome. Each vendor’s result carries a value or an error; a timeout is recorded per vendor, not as a failure of the request.
- No leaks. The results channel is buffered to the number of targets, so a late goroutine can still send and exit.
- Cancellation reaches the vendor. When
Gatherreturns it cancels the context; in-flight HTTP requests are aborted and the vendor handler stops working. - Deterministic output. Results are returned in target order, whatever order they arrived in.
A response with one vendor failed and one too slow still arrives at the deadline:
{
"best": { "vendor": "globex", "price": 3925.96, "currency": "INR" },
"failures": [
{ "vendor": "initech", "error": "vendor returned 503 Service Unavailable", "latency_ms": 87 },
{ "vendor": "umbrella", "error": "no response before deadline", "latency_ms": 301 }
],
"elapsed_ms": 301
}
Reproduce it#
git clone https://github.com/caelus-engineering-labs/scatter-gather-pattern.git
cd scatter-gather-pattern
./demo.sh
go test -race ./...
Variations worth testing#
Quorum (return after N answers), hedged requests to a second replica, a semaphore for hundreds of targets, and per-target deadlines inside the overall window.
Repository
- caelus-engineering-labs/scatter-gather-pattern ↗Go standard library only; ./demo.sh starts four vendors and the aggregator