Patterncore
Aggregator
Also called Aggregator pattern, message aggregator, aggregate EIP, gatherer.
An aggregator collects related messages, such as the replies for the parts of one order, until the set is complete or a timeout comes, and then publishes one message made from them.
- Family
- integration
- Intent
- Combine related messages into one, by a stateful filter that groups the messages by a correlation key, tests a completion condition, and then publishes one message from the group.
- Also called
- message aggregator
Intent
Put the results of related messages together, so that a later step can work on them as one. The book asks: "How do we combine the results of individual, but related messages so that they can be processed as a whole?"12 The answer: "Use a stateful filter, an Aggregator", whose task is "to collect and store individual messages until a complete set of related messages has been received. Then, the Aggregator publishes a single message distilled from the individual messages."1
Problem
A Splitter sends each line of an order to its warehouse, and each warehouse replies. Or a request goes to many suppliers, and each one sends a quote. The next step needs all the replies: the shop can bill an order only when all its items are taken from the warehouses, and it can choose the best quote only when it has the quotes.1
The replies come as separate messages, maybe in a different order, maybe with replies for other orders between them, and some can be late or never come.
The forces are these. The aggregator must know which messages belong together. It must know when a group is ready. And it must not wait for ever for a message that is lost.
Solution
Put an aggregator on the channel of the replies. It keeps one group for each correlation key. When a message comes, the aggregator adds it to its group and tests the completion condition. When the condition is true, it makes one message from the group and publishes it.1
[ A 2/3 ] [ B 1/2 ] [ A 1/3 ] [ B 2/2 ] [ A 3/3 ]
\ | | | /
+--> aggregator: group A {1, 2, 3} ---> [ A complete ]
(store) group B {1, 2} ---> [ B complete ]
The participants are the input channel, the aggregator with its store of groups, and the output channel. The book names three decisions for each aggregator: the correlation, which decides which messages belong together; the completeness condition, which decides when to publish; and the aggregation algorithm, which decides how to make one message from the group.1
Correlation. The key is often a Correlation Identifier. Spring Integration groups messages by the CORRELATION_ID header by default, and a CorrelationStrategy can change this.3 In Apache Camel, the messages with the same correlation key go into one bucket.4
Completeness. The book lists strategies. Wait for all waits for all the replies, so it has the most data for the choice, but one missing message stops the whole group. Time Out waits for a fixed time and then uses the replies that came. First Best uses the first reply and ignores the others. Time Out with Override stops early when a very good reply comes. External Event waits for a business event, such as the end of the trading day.1 Spring Integration releases a group by default when all messages of a sequence are present, by the SEQUENCE_SIZE header.3 Camel has completionSize, completionTimeout, completionInterval and completionPredicate, and "It's basically the first that triggers that wins."4
Timeouts and late messages. The program below runs three aggregators on the same messages. Part 2 of order A comes late, at tick 12, and part 2 of order B never comes.
# Each order has 3 parts. Part 2 of A comes late, at tick 12. Part 2 of B never comes.
arrivals = {1: ("A", 1), 2: ("B", 1), 3: ("A", 3), 4: ("B", 3), 12: ("A", 2)}
SIZE, END = 3, 20
def run(name, timeout, keep_closed):
print(name + ":")
groups = {} # correlation key -> [parts, tick of the last part]
closed = set()
for tick in range(1, END + 1):
if tick in arrivals:
key, part = arrivals[tick]
if key in closed:
print(f" tick {tick:2}: part {part} of {key} is late, discard it")
else:
g = groups.setdefault(key, [[], tick])
g[0].append(part)
g[1] = tick
if len(g[0]) == SIZE:
print(f" tick {tick:2}: {key} complete {sorted(g[0])}")
del groups[key]
for key, (parts, last) in list(groups.items()):
if timeout and tick - last >= timeout:
print(f" tick {tick:2}: {key} timed out, publish {len(parts)} of {SIZE} {sorted(parts)}")
del groups[key]
if keep_closed:
closed.add(key)
for key, (parts, _) in groups.items():
print(f" tick {END}: {key} still waits with {len(parts)} of {SIZE}")
run("no timeout", 0, False)
run("timeout 5, forget the key", 5, False)
run("timeout 5, keep the key closed", 5, True)
no timeout:
tick 12: A complete [1, 2, 3]
tick 20: B still waits with 2 of 3
timeout 5, forget the key:
tick 8: A timed out, publish 2 of 3 [1, 3]
tick 9: B timed out, publish 2 of 3 [1, 3]
tick 17: A timed out, publish 1 of 3 [2]
timeout 5, keep the key closed:
tick 8: A timed out, publish 2 of 3 [1, 3]
tick 9: B timed out, publish 2 of 3 [1, 3]
tick 12: part 2 of A is late, discard it
With no timeout, A completes when the late part comes, but B waits for ever, and its group stays in memory. With a timeout that forgets the key, the late part of A starts a new group, which times out and publishes a second, wrong result for A. With the key kept closed, the late part is found and discarded. Camel does this when the option closeCorrelationKeyOnCompletion is set: it gives a ClosedCorrelationKeyException to a message for a closed key.56 In Spring Integration, a completed group stays as an empty group, and late messages go to the discard channel.3 So a timeout needs a rule for late messages too.
Example
Each example file aggregates seven messages from a splitter, for orders A and B, in a mixed order. A group is complete when it has all the sequence numbers up to its size, and the items are joined in the order of the sequence numbers. A second copy of part 2 of A, as at-least-once delivery can give, is ignored. A copy of a part of B that comes after B is complete is discarded, because the key of B is closed.
# Messages from a splitter: (correlation id, sequence number, sequence size, item).
incoming = [
("A", 2, 3, "gadget"),
("B", 1, 2, "widget"),
("A", 1, 3, "widget"),
("B", 2, 2, "gizmo"),
("A", 2, 3, "gadget"), # a second copy, as at-least-once delivery can give
("A", 3, 3, "widget"),
("B", 1, 2, "widget"), # a copy that comes after B is complete
]
groups = {} # correlation id -> {sequence number: item}
closed = set()
for cid, seq, size, item in incoming:
if cid in closed:
print(f"late: {cid} {seq}/{size} discarded, the group is closed")
continue
parts = groups.setdefault(cid, {})
if seq in parts:
print(f"duplicate: {cid} {seq}/{size} ignored")
continue
parts[seq] = item
if len(parts) == size: # the completion condition: all parts are here
items = [parts[n] for n in sorted(parts)]
print(f"{cid} complete: {', '.join(items)}")
del groups[cid]
closed.add(cid)
print(f"still open: {len(groups)}")
B complete: widget, gizmo
duplicate: A 2/3 ignored
A complete: widget, gadget, widget
late: B 1/2 discarded, the group is closed
still open: 0
- Verdict: idiom. A dict from the correlation id to a dict of the parts is the store of groups, and
setdefaultmakes a group on the first part. - The parts are kept by sequence number, so a second copy of a part does not count twice, and
sorted(parts)gives the items in order. - The set
closedkeeps the ids of the complete groups, so a late copy is discarded and does not start a new group; in a long-running process, this set needs a limit or a time to live.
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class Main {
// A message from a splitter.
record Msg(String cid, int seq, int size, String item) {}
public static void main(String[] args) {
List<Msg> incoming = List.of(
new Msg("A", 2, 3, "gadget"),
new Msg("B", 1, 2, "widget"),
new Msg("A", 1, 3, "widget"),
new Msg("B", 2, 2, "gizmo"),
new Msg("A", 2, 3, "gadget"), // a second copy, as at-least-once delivery can give
new Msg("A", 3, 3, "widget"),
new Msg("B", 1, 2, "widget")); // a copy that comes after B is complete
Map<String, TreeMap<Integer, String>> groups = new HashMap<>();
Set<String> closed = new HashSet<>();
for (Msg m : incoming) {
if (closed.contains(m.cid())) {
System.out.printf("late: %s %d/%d discarded, the group is closed%n", m.cid(), m.seq(), m.size());
continue;
}
TreeMap<Integer, String> parts = groups.computeIfAbsent(m.cid(), k -> new TreeMap<>());
if (parts.putIfAbsent(m.seq(), m.item()) != null) {
System.out.printf("duplicate: %s %d/%d ignored%n", m.cid(), m.seq(), m.size());
continue;
}
if (parts.size() == m.size()) { // the completion condition: all parts are here
System.out.printf("%s complete: %s%n", m.cid(), String.join(", ", parts.values()));
groups.remove(m.cid());
closed.add(m.cid());
}
}
System.out.printf("still open: %d%n", groups.size());
}
}
B complete: widget, gizmo
duplicate: A 2/3 ignored
A complete: widget, gadget, widget
late: B 1/2 discarded, the group is closed
still open: 0
- Verdict: idiom. A
HashMapfrom the correlation id to aTreeMapof the parts is the store; theTreeMapkeeps the parts in the order of their sequence numbers. putIfAbsentreturns the old value for a second copy, so the test for a duplicate and the insert are one call.- Apache Camel and Spring Integration give the same parts as options: a correlation expression, a completion size or a release strategy, and a store of groups.
using System;
using System.Collections.Generic;
var incoming = new (string Cid, int Seq, int Size, string Item)[]
{
("A", 2, 3, "gadget"),
("B", 1, 2, "widget"),
("A", 1, 3, "widget"),
("B", 2, 2, "gizmo"),
("A", 2, 3, "gadget"), // a second copy, as at-least-once delivery can give
("A", 3, 3, "widget"),
("B", 1, 2, "widget"), // a copy that comes after B is complete
};
var groups = new Dictionary<string, SortedDictionary<int, string>>();
var closed = new HashSet<string>();
foreach (var (cid, seq, size, item) in incoming)
{
if (closed.Contains(cid))
{
Console.WriteLine($"late: {cid} {seq}/{size} discarded, the group is closed");
continue;
}
if (!groups.TryGetValue(cid, out var parts))
{
parts = new SortedDictionary<int, string>();
groups[cid] = parts;
}
if (!parts.TryAdd(seq, item))
{
Console.WriteLine($"duplicate: {cid} {seq}/{size} ignored");
continue;
}
if (parts.Count == size) // the completion condition: all parts are here
{
Console.WriteLine($"{cid} complete: {string.Join(", ", parts.Values)}");
groups.Remove(cid);
closed.Add(cid);
}
}
Console.WriteLine($"still open: {groups.Count}");
B complete: widget, gizmo
duplicate: A 2/3 ignored
A complete: widget, gadget, widget
late: B 1/2 discarded, the group is closed
still open: 0
- Verdict: idiom. A
Dictionaryfrom the correlation id to aSortedDictionaryof the parts is the store, andTryAddreturns false for a second copy of a part. string.Joinon the values of theSortedDictionarygives the items in the order of their sequence numbers.- The
HashSetof closed ids discards late copies; in a long-running service, it needs a limit, as the LRU cache of closed keys in Apache Camel has.
package main
import (
"fmt"
"sort"
"strings"
)
// Msg is a message from a splitter.
type Msg struct {
CID string
Seq, Size int
Item string
}
func main() {
incoming := []Msg{
{"A", 2, 3, "gadget"},
{"B", 1, 2, "widget"},
{"A", 1, 3, "widget"},
{"B", 2, 2, "gizmo"},
{"A", 2, 3, "gadget"}, // a second copy, as at-least-once delivery can give
{"A", 3, 3, "widget"},
{"B", 1, 2, "widget"}, // a copy that comes after B is complete
}
groups := map[string]map[int]string{}
closed := map[string]bool{}
for _, m := range incoming {
if closed[m.CID] {
fmt.Printf("late: %s %d/%d discarded, the group is closed\n", m.CID, m.Seq, m.Size)
continue
}
parts, ok := groups[m.CID]
if !ok {
parts = map[int]string{}
groups[m.CID] = parts
}
if _, dup := parts[m.Seq]; dup {
fmt.Printf("duplicate: %s %d/%d ignored\n", m.CID, m.Seq, m.Size)
continue
}
parts[m.Seq] = m.Item
if len(parts) == m.Size { // the completion condition: all parts are here
seqs := make([]int, 0, len(parts))
for s := range parts {
seqs = append(seqs, s)
}
sort.Ints(seqs)
items := make([]string, 0, len(seqs))
for _, s := range seqs {
items = append(items, parts[s])
}
fmt.Printf("%s complete: %s\n", m.CID, strings.Join(items, ", "))
delete(groups, m.CID)
closed[m.CID] = true
}
}
fmt.Printf("still open: %d\n", len(groups))
}
B complete: widget, gizmo
duplicate: A 2/3 ignored
A complete: widget, gadget, widget
late: B 1/2 discarded, the group is closed
still open: 0
- Verdict: idiom. A
map[string]map[int]stringis the store of groups, and the form_, dup := parts[m.Seq]finds a second copy of a part. - The sequence numbers are sorted with
sort.Intsbefore the join, because the order of a Go map is not defined. - A real aggregator reads from a channel in a loop with
select, so that a timer can also close a group that does not complete.
Consequences
Benefits.
- One message for the next step. The next step gets a whole order or the best quote, and does not need to know about the parts.
- Parallel work before it. The parts can be processed in parallel, and the aggregator puts the results together.
- A place for the rules. The rules for missing and late parts are in one component.
Liabilities.
- State. The aggregator is stateful. Spring Integration says that it "must hold the messages to be aggregated" in a message store.3 If the process stops, an in-memory store loses the groups. Camel has a pluggable
AggregationRepositoryfor a persistent store.4 - A group that never completes. With Wait for all and no timeout, one lost message keeps a group open for ever. Camel refuses to start an aggregator with no completion option: the message is "At least one of the completions options" and the list of the options "must be set".5
- Memory for closed keys. To discard late messages, the aggregator must keep data about a group after the release. Spring Integration warns: "This can eventually cause out-of-memory conditions."3 Camel can keep the closed keys in an LRU cache with a fixed capacity.5
- Partial results. After a timeout, the next step gets a group with missing parts and must handle it.
When not to use it
When each reply is useful alone. If each part can be processed by itself, the aggregator only adds state and delay.
When the parts come from one request and one reply. A Request-Reply with one reply does not need a group.
When the whole result must be all or nothing over many systems. A timeout gives a partial group; a business process that must undo the work of the other parts needs a process manager or a saga, not only an aggregator.
Variants and related patterns
Splitter. The step before it, which makes the parts and their sequence headers. See Splitter.
Scatter-Gather. A request goes to many receivers, and an aggregator collects their replies. See Scatter-Gather.
Resequencer. Also a stateful filter that keeps messages. It answers the question "How can we get a stream of related but out-of-sequence messages back into the correct order?" and it publishes the messages in order, usually with no change to their content.7
Known uses
- Apache Camel: the Aggregate EIP, with an
AggregationStrategyand the completion options; the check at the start of AggregateProcessor in 4.14.0 makes a completion option mandatory.5 - Spring Integration:
AggregatingMessageHandlerwith aCorrelationStrategy, aReleaseStrategyand aMessageStore.3 - The Serverless Loan Broker of the EIP site: on AWS, a Lambda function with DynamoDB is the aggregator, with a completeness condition of a minimum number of answers, and AWS Step Functions adds the timeout.1
References
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Aggregator (problem and solution under CC BY), problem and solution statements; pattern text; Example, Serverless Loan Broker on AWS
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Designing, Building, and Deploying Messaging Solutions, Addison-Wesley, 2003, Chapter 7, Message Routing, Aggregator
- Spring Integration 7.1.1 reference source, Aggregator, introduction; Functionality; the release of groups; Expiring Groups
- Apache Camel 4.14.0 documentation source, Aggregate EIP, introduction; Aggregate with persistent repository; Completion
- Apache Camel 4.14.0 source, AggregateProcessor.java, the check of the completion options, lines 1525 to 1546
- Apache Camel 4.14.0 source, AggregateProcessor.java, the check of the closed correlation keys, lines 353 to 358
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Resequencer (problem and solution under CC BY), problem and solution statements
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag M5QTGV Edit this page History Report an error Markdown