Programming Search⌘K

Patterncore

Scatter-Gather

Also called Scatter-Gather pattern, scatter gather, fan-out fan-in, fan out and fan in, best quote.

Scatter-gather sends one request to many receivers, such as a request for a price to all suppliers, and then collects their replies into one message, for example the best price.

Family
integration
Intent
Get one answer from many receivers, by sending a request to all of them through a recipient list or a publish-subscribe channel, and by an aggregator that combines the replies under a completion rule.
Also called
fan-out fan-in, best quote

Intent

Ask many receivers the same question and get one answer from their replies. The book asks: "How do you maintain the overall message flow when a message needs to be sent to multiple recipients, each of which may send a reply?"12 The answer: "Use a Scatter-Gather that broadcasts a message to multiple recipients and re-aggregates the responses back into a single message".1

Problem

An item of an order is not in stock, and many outside suppliers can deliver it. Each supplier can have the item or not, with a different price and a different date. To get the best terms, the shop must ask all the suppliers and then choose.1

One Request-Reply for each supplier, one after the other, makes the total time the sum of all the waits. And the caller must then keep the state of all the requests itself.

The forces are these. The requests must go out in parallel. The caller wants one result, not many replies. Some suppliers reply slowly or never, and the caller must not wait for ever.

Solution

Make one component that sends the request to all receivers, and an Aggregator that collects the replies into one message. The book describes it as a router for the request and an aggregator for the responses.1

                        +--> [ alpha ] --+
  request ---> scatter -+--> [ beta  ] --+--> [ replies ] ---> gather ---> best quote
                        +--> [ gamma ] --+        (correlation id, timeout)

The participants are the requester, the scatter step, the receivers, the channel of the replies and the gather step, which is an aggregator. Each reply carries a Correlation Identifier, so that the gatherer can find the request of each reply.

Two ways to scatter. The book gives two variants. In the distribution variant, a recipient list sends the request to the channel of each known receiver; the scatter-gather controls the list, but it must know the channel of each receiver. In the auction variant, a Publish-Subscribe Channel sends the request to any receiver that listens; there is one channel, but the scatter-gather does not control who answers.1 The book's question for the recipient list is: "How do we route a message to a list of dynamically specified recipients?"3

When to stop gathering. The gatherer uses the completeness strategies of the aggregator.4 With the auction variant, the gatherer does not know how many replies to expect, so it needs a timeout. The program below gathers the same four replies with five strategies. Delta is down and never replies.

# The time in ms after which each supplier replies, and its price in cents. Delta is down.
replies = {"alpha": (30, 1250), "beta": (80, 1190), "gamma": (400, 1100), "delta": (None, None)}
arrived = sorted((t, name, price) for name, (t, price) in replies.items() if t is not None)


def gather(name, done, deadline=None):
    """Collect replies in the order of arrival until done() is true or the deadline comes."""
    got = []
    for t, supplier, price in arrived:
        if deadline is not None and t > deadline:
            ready = deadline
            break
        got.append((price, supplier))
        if done(got):
            ready = t
            break
    else:
        if deadline is None:
            print(f"{name:30}: no result, it waits for delta for ever")
            return
        ready = deadline
    price, supplier = min(got)
    print(f"{name:30}: {supplier} {price}, ready at {ready} ms, {len(got)} of {len(replies)} replies")


gather("wait for all", lambda got: len(got) == len(replies))
gather("wait for all, timeout 500 ms", lambda got: len(got) == len(replies), deadline=500)
gather("timeout 200 ms", lambda got: False, deadline=200)
gather("first reply", lambda got: len(got) == 1)
gather("200 ms, or 1200 or less", lambda got: any(p <= 1200 for p, _ in got), deadline=200)
Output
wait for all                  : no result, it waits for delta for ever
wait for all, timeout 500 ms  : gamma 1100, ready at 500 ms, 3 of 4 replies
timeout 200 ms                : beta 1190, ready at 200 ms, 2 of 4 replies
first reply                   : alpha 1250, ready at 30 ms, 1 of 4 replies
200 ms, or 1200 or less       : beta 1190, ready at 80 ms, 2 of 4 replies

To wait for all the replies with no timeout gives no result at all. A timeout of 500 ms finds the lowest price, from gamma, but the caller waits 500 ms. A timeout of 200 ms is faster and misses gamma. The first reply is fastest and the most expensive. A rule that stops at a price of 1200 or less, or at 200 ms, gets beta at 80 ms.

Example

Each example file asks three suppliers for a price, with real concurrency: Python uses a thread pool and wait with a timeout, Go uses goroutines, a buffered channel and select on a timer, Java uses CompletableFuture with completeOnTimeout, and C# uses Task.WhenAny on all the tasks and a delay. Each supplier waits for a fixed time before it replies. Gamma takes 1 second, so with a limit of 400 ms, the result has only alpha and beta, and beta has the best price.

PythonGitHub
import time
from concurrent.futures import ThreadPoolExecutor, wait

# Each supplier replies after some time with a price in cents.
suppliers = {"alpha": (0.02, 1250), "beta": (0.08, 1190), "gamma": (1.0, 1100)}


def ask(name):
    delay, price = suppliers[name]
    time.sleep(delay)  # a stand-in for a request on the channel of the supplier
    return price


print(f"asked {len(suppliers)} suppliers, wait at most 400 ms")
pool = ThreadPoolExecutor(max_workers=len(suppliers))
futures = {pool.submit(ask, name): name for name in suppliers}  # scatter
done, _ = wait(futures, timeout=0.4)                              # gather, with a timeout
quotes = {futures[f]: f.result() for f in done}
pool.shutdown(wait=False, cancel_futures=True)

for name in sorted(suppliers):
    if name in quotes:
        print(f"reply from {name}: {quotes[name]}")
    else:
        print(f"no reply from {name} in time")
best = min(quotes, key=quotes.get)
print(f"best: {best} at {quotes[best]}")
Output
asked 3 suppliers, wait at most 400 ms
reply from alpha: 1250
reply from beta: 1190
no reply from gamma in time
best: beta at 1190
  • Verdict: idiom. ThreadPoolExecutor.submit scatters the requests, and concurrent.futures.wait with a timeout gathers the futures that are done in time.
  • shutdown(wait=False, cancel_futures=True) does not wait for gamma, but its thread still runs to the end before the interpreter exits.
  • With asyncio, the same form is asyncio.wait on the tasks with a timeout.
JavaGitHub
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class Main {
    record Offer(long delayMs, int price) {}

    static int ask(Offer o) {
        try {
            Thread.sleep(o.delayMs()); // a stand-in for a request on the channel of the supplier
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return o.price();
    }

    public static void main(String[] args) {
        // Each supplier replies after some time with a price in cents.
        Map<String, Offer> suppliers = new TreeMap<>(Map.of(
            "alpha", new Offer(20, 1250), "beta", new Offer(80, 1190), "gamma", new Offer(1000, 1100)));
        System.out.printf("asked %d suppliers, wait at most 400 ms%n", suppliers.size());

        Map<String, CompletableFuture<Integer>> futures = new TreeMap<>();
        suppliers.forEach((name, offer) -> futures.put(name,
            CompletableFuture.supplyAsync(() -> ask(offer))        // scatter
                .completeOnTimeout(null, 400, TimeUnit.MILLISECONDS))); // null means no reply in time

        String best = null;
        int bestPrice = Integer.MAX_VALUE;
        for (var e : futures.entrySet()) {                         // gather
            Integer price = e.getValue().join();
            if (price == null) {
                System.out.printf("no reply from %s in time%n", e.getKey());
                continue;
            }
            System.out.printf("reply from %s: %d%n", e.getKey(), price);
            if (price < bestPrice) {
                best = e.getKey();
                bestPrice = price;
            }
        }
        System.out.printf("best: %s at %d%n", best, bestPrice);
    }
}
Output
asked 3 suppliers, wait at most 400 ms
reply from alpha: 1250
reply from beta: 1190
no reply from gamma in time
best: beta at 1190
  • Verdict: idiom. CompletableFuture.supplyAsync scatters the requests, and completeOnTimeout(null, 400, TimeUnit.MILLISECONDS) gives each future a value when the time is over.
  • join on each future then waits at most about 400 ms in total, because all the timers start at the same time.
  • The common pool has daemon threads, so the program ends while gamma still sleeps.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

// Each supplier replies after some time with a price in cents.
var suppliers = new SortedDictionary<string, (int DelayMs, int Price)>
{
    ["alpha"] = (20, 1250),
    ["beta"] = (80, 1190),
    ["gamma"] = (1000, 1100),
};
Console.WriteLine($"asked {suppliers.Count} suppliers, wait at most 400 ms");

var tasks = suppliers.ToDictionary(s => s.Key, s => Ask(s.Value.DelayMs, s.Value.Price)); // scatter
await Task.WhenAny(Task.WhenAll(tasks.Values), Task.Delay(400));                          // gather, with a timeout

var quotes = tasks.Where(t => t.Value.IsCompletedSuccessfully).ToDictionary(t => t.Key, t => t.Value.Result);
foreach (var name in suppliers.Keys)
{
    Console.WriteLine(quotes.TryGetValue(name, out var price) ? $"reply from {name}: {price}" : $"no reply from {name} in time");
}
var best = quotes.MinBy(q => q.Value);
Console.WriteLine($"best: {best.Key} at {best.Value}");

static async Task<int> Ask(int delayMs, int price)
{
    await Task.Delay(delayMs); // a stand-in for a request on the channel of the supplier
    return price;
}
Output
asked 3 suppliers, wait at most 400 ms
reply from alpha: 1250
reply from beta: 1190
no reply from gamma in time
best: beta at 1190
  • Verdict: idiom. One Task for each supplier scatters the requests, and Task.WhenAny(Task.WhenAll(tasks), Task.Delay(400)) waits for all of them or for the limit.
  • IsCompletedSuccessfully selects the tasks that replied in time, and MinBy finds the best price.
  • In a service, a CancellationToken with a timeout also tells the slow requests to stop.
package main

import (
	"fmt"
	"sort"
	"time"
)

type quote struct {
	supplier string
	price    int
}

func main() {
	// Each supplier replies after some time with a price in cents.
	delays := map[string]time.Duration{"alpha": 20 * time.Millisecond, "beta": 80 * time.Millisecond, "gamma": time.Second}
	prices := map[string]int{"alpha": 1250, "beta": 1190, "gamma": 1100}

	replies := make(chan quote, len(delays)) // buffered, so a late sender does not block
	for name := range delays {               // scatter
		go func(name string) {
			time.Sleep(delays[name]) // a stand-in for a request on the channel of the supplier
			replies <- quote{name, prices[name]}
		}(name)
	}

	fmt.Printf("asked %d suppliers, wait at most 400 ms\n", len(delays))
	got := map[string]int{}
	deadline := time.After(400 * time.Millisecond)
gather:
	for len(got) < len(delays) {
		select {
		case q := <-replies:
			got[q.supplier] = q.price
		case <-deadline:
			break gather
		}
	}

	names := make([]string, 0, len(delays))
	for name := range delays {
		names = append(names, name)
	}
	sort.Strings(names)
	best := ""
	for _, name := range names {
		price, ok := got[name]
		if !ok {
			fmt.Printf("no reply from %s in time\n", name)
			continue
		}
		fmt.Printf("reply from %s: %d\n", name, price)
		if best == "" || price < got[best] {
			best = name
		}
	}
	fmt.Printf("best: %s at %d\n", best, got[best])
}
Output
asked 3 suppliers, wait at most 400 ms
reply from alpha: 1250
reply from beta: 1190
no reply from gamma in time
best: beta at 1190
  • Verdict: idiom. One goroutine for each supplier scatters the requests, and a select on the channel of the replies and on time.After gathers them until the deadline.
  • The channel has a buffer for all the replies, so a goroutine that replies after the deadline does not block for ever.
  • In a server, a context.WithTimeout gives the same deadline and also tells the goroutines to stop.

Consequences

Benefits.

  • Parallel requests. The total time is about the time of the slowest reply that the gatherer waits for, not the sum.
  • One result for the caller. Spring Integration describes its scatter-gather as "a compound endpoint for which the goal is to send a message to the recipients and aggregate the results."5
  • Free choice of the receivers. In the auction variant, a new receiver subscribes and takes part with no change to the requester.1

Liabilities.

  • Slow and lost replies. Without a limit, one slow receiver holds the whole result. Spring Integration waits 30 seconds by default, and returns null on a timeout.5
  • Work that goes on after the timeout. In Camel, a timeout ends the wait, but "certain tasks for which it is challenging for Camel to shut down in a graceful manner may continue to run."6 The examples show the same: gamma still runs after the gatherer is done.
  • More load. Each request becomes many requests, and each receiver does the work even if its reply is not used.
  • Partial results. The caller must handle a result with fewer replies, or with none.

When not to use it

When one receiver is enough. If one known receiver can answer, use a Request-Reply.

When the parts of the request are different. If each receiver must get a different part of a message, a Splitter and an aggregator, the Composed Message Processor of the book, fit better.

When all the replies must be correct together. If the result must include all receivers or fail, the timeout and the partial result do not fit; the caller needs Wait for all and an error path for a missing reply.

Distribution and auction. The two ways to scatter, by a recipient list or by a publish-subscribe channel.1

Fork-join. In one program, Fork/Join starts tasks in parallel and waits for them all; scatter-gather does the same with messages between systems, and it can stop before all replies come.

Futures. The examples use Futures and promises: one future for each request, and a wait on all of them with a limit.

Known uses

  • Spring Integration: the ScatterGatherHandler combines a PublishSubscribeChannel or a RecipientListRouter with an AggregatingMessageHandler, as the Scatter-Gather page at 7.1.1 says.5
  • Apache Camel: the Recipient List EIP sends the same message to many endpoints, in parallel with parallelProcessing, with a total timeout, and with an AggregationStrategy that makes one reply.6
  • Azure Durable Functions: the EIP site shows the fan-out and fan-in form, and names Task.WhenAll for wait for all, Task.WhenAny for first best, and Task.WaitAll for a fixed timeout.1

References

  1. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Scatter-Gather (problem and solution under CC BY), problem and solution statements; pattern text; Examples
  2. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Designing, Building, and Deploying Messaging Solutions, Addison-Wesley, 2003, Chapter 7, Message Routing, Scatter-Gather
  3. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Recipient List (problem and solution under CC BY), problem and solution statements; pattern text
  4. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Aggregator (problem and solution under CC BY), pattern text, completeness strategies
  5. Spring Integration 7.1.1 reference source, Scatter-Gather, introduction, lines 4 to 13; Functionality; Configuring a Scatter-Gather Endpoint
  6. Apache Camel 4.14.0 documentation source, Recipient List EIP, Using Recipient List; Using parallel processing; Using timeout

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/CDA0NF/text.yaml