Programming Search⌘K

Patterncore

Splitter

Also called Splitter pattern, message splitter, split EIP, debatching.

A splitter takes one message that holds a list of items, such as the lines of an order, and sends one new message for each item, so that each item can go its own way.

Family
integration
Intent
Process each element of a composite message on its own, by a step that reads the message and publishes one message for each element, with headers that link the parts to the whole.
Also called
message splitter, debatching

Intent

Handle each item of a large message as a message of its own. The book asks: "How can we process a message if it contains multiple elements, each of which may have to be processed in a different way?"12 The answer: "Use a Splitter to break out the composite message into a series of individual messages, each containing data related to one item."1

Problem

An order from a customer has more than one line. Each line can need a different system: widgets are in one warehouse and gadgets in another. The shop wants to process the whole order, but it must check each line in the right system.1

A Content-Based Router sends a whole message to one channel. It cannot send the first line of an order to one warehouse and the second line to another. A receiver that gets the whole order must know about all the lines and all the systems.

The forces are these. Each item must be processed alone, maybe in parallel. The parts must keep a link to the whole, so that a later step can put the results together. And a very large message must not fill the memory.

Solution

Put a splitter after the channel of the composite messages. For each message, it finds the repeated elements and publishes one new message for each element, or for each group of elements.1 Each new message carries the data of its item and, as needed, data from the whole, such as the order number.

                                       +--> [ A7 1/3 widget x2 ] --+--> inventory.widgets
  [ orders ] ---> splitter ---> items -+--> [ A7 2/3 gadget x1 ] --+--> inventory.gadgets
                                       +--> [ A7 3/3 widget x5 ] --+--> inventory.widgets

The participants are the input channel, the splitter, the output channel and the receivers of the items. Often a router follows the splitter, and an Aggregator collects the results.

Headers for the way back. The book's Aggregator can know how many parts to expect when each part carries the total count.3 Spring Integration puts three headers on each part: CORRELATION_ID, SEQUENCE_SIZE and SEQUENCE_NUMBER.4 The Correlation Identifier is the id of the whole, and the number and the size tell the aggregator which part this is and when it has all of them.

Two modes. Apache Camel splits in a default mode and in a streaming mode. In the default mode, it can know the total size, but it keeps all the sub messages in memory. In the streaming mode, it splits on demand and does not keep them in memory, but "the total size cannot be known ahead of time."5 The program below shows the difference with a generator that reads the lines of an order one at a time.

def lines():
    """The lines of an order, read one at a time, as from a file or a socket."""
    for n, text in enumerate(["widget x2", "gadget x1", "widget x5"], 1):
        print(f"  read line {n}")
        yield text


def split_list(order_id, source):
    items = list(source)  # all items are in memory before the first message
    for i, item in enumerate(items):
        yield {"order": order_id, "index": i, "size": len(items), "item": item}


def split_stream(order_id, source):
    it = iter(source)
    item, i = next(it, None), 0
    while item is not None:
        following = next(it, None)  # look ahead one item to know if this is the last
        msg = {"order": order_id, "index": i, "item": item, "complete": following is None}
        msg["size"] = i + 1 if following is None else "?"
        yield msg
        item, i = following, i + 1


for name, split in [("list mode", split_list), ("streaming mode", split_stream)]:
    print(name + ":")
    for m in split("A7", lines()):
        print(f"  send {m['order']} item {m['index'] + 1} of {m['size']}: {m['item']}")
Output
list mode:
  read line 1
  read line 2
  read line 3
  send A7 item 1 of 3: widget x2
  send A7 item 2 of 3: gadget x1
  send A7 item 3 of 3: widget x5
streaming mode:
  read line 1
  read line 2
  send A7 item 1 of ?: widget x2
  read line 3
  send A7 item 2 of ?: gadget x1
  send A7 item 3 of 3: widget x5

In list mode, all three lines are read before the first message goes out. In streaming mode, the splitter reads one line ahead, so it knows when an item is the last. Camel does the same: in updateNewExchange, a split from a collection sets the size at once, and in streaming mode the size is set on the last part, to index + 1.6

Example

Each example file splits two orders. Order A7 has three lines, and each line becomes a message with the order id, the sequence number and the size, and goes to the channel of its warehouse. Order B9 has no lines. A splitter that sends no message for it leaves a later aggregator with nothing to complete, so the examples send one message with size 0 to an orders.empty channel. This is a choice of the design, not a rule of the pattern.

PythonGitHub
from dataclasses import dataclass


@dataclass
class Line:
    kind: str
    qty: int


orders = {"A7": [Line("widget", 2), Line("gadget", 1), Line("widget", 5)], "B9": []}
channel = {"widget": "inventory.widgets", "gadget": "inventory.gadgets"}


def split(order_id, lines):
    """One message for each line, with the headers that an aggregator needs."""
    if not lines:
        # One message with size 0, so that a later aggregator is not left waiting.
        return [{"correlation_id": order_id, "seq": 0, "size": 0, "line": None}]
    return [{"correlation_id": order_id, "seq": n, "size": len(lines), "line": line}
            for n, line in enumerate(lines, 1)]


for order_id, lines in orders.items():
    print(f"order {order_id} has {len(lines)} lines")
    for m in split(order_id, lines):
        if m["line"] is None:
            print(f"  {order_id} 0/0 empty order -> orders.empty")
            continue
        line = m["line"]
        print(f"  {order_id} {m['seq']}/{m['size']} {line.kind} x{line.qty} -> {channel[line.kind]}")
Output
order A7 has 3 lines
  A7 1/3 widget x2 -> inventory.widgets
  A7 2/3 gadget x1 -> inventory.gadgets
  A7 3/3 widget x5 -> inventory.widgets
order B9 has 0 lines
  B9 0/0 empty order -> orders.empty
  • Verdict: idiom. A list comprehension with enumerate(lines, 1) makes one message for each line, with the sequence number from 1 and the size of the list.
  • The order id is the correlation id of each part, so that an aggregator can find all the parts of one order.
  • For a large order, a generator with yield sends the parts one at a time, but then the size is not known until the end.
JavaGitHub
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
    record Line(String kind, int qty) {}

    // One message from the splitter, with the headers that an aggregator needs.
    record Msg(String correlationId, int seq, int size, Line line) {}

    static List<Msg> split(String orderId, List<Line> lines) {
        if (lines.isEmpty()) {
            // One message with size 0, so that a later aggregator is not left waiting.
            return List.of(new Msg(orderId, 0, 0, null));
        }
        List<Msg> out = new ArrayList<>();
        for (int i = 0; i < lines.size(); i++) {
            out.add(new Msg(orderId, i + 1, lines.size(), lines.get(i)));
        }
        return out;
    }

    public static void main(String[] args) {
        Map<String, List<Line>> orders = new LinkedHashMap<>();
        orders.put("A7", List.of(new Line("widget", 2), new Line("gadget", 1), new Line("widget", 5)));
        orders.put("B9", List.of());
        Map<String, String> channel = Map.of("widget", "inventory.widgets", "gadget", "inventory.gadgets");
        orders.forEach((id, lines) -> {
            System.out.printf("order %s has %d lines%n", id, lines.size());
            for (Msg m : split(id, lines)) {
                if (m.line() == null) {
                    System.out.printf("  %s 0/0 empty order -> orders.empty%n", id);
                    continue;
                }
                System.out.printf("  %s %d/%d %s x%d -> %s%n", id, m.seq(), m.size(),
                    m.line().kind(), m.line().qty(), channel.get(m.line().kind()));
            }
        });
    }
}
Output
order A7 has 3 lines
  A7 1/3 widget x2 -> inventory.widgets
  A7 2/3 gadget x1 -> inventory.gadgets
  A7 3/3 widget x5 -> inventory.widgets
order B9 has 0 lines
  B9 0/0 empty order -> orders.empty
  • Verdict: idiom. A loop over the List of lines makes one record for each line, with the correlation id, the sequence number and the size.
  • A LinkedHashMap keeps the order in which the orders were added, so the output has a fixed order.
  • In Apache Camel, the same step is split(body()) in a route, and Camel adds the split index and size as properties of each part.
using System;
using System.Collections.Generic;
using System.Linq;

var orders = new List<(string Id, Line[] Lines)>
{
    ("A7", new[] { new Line("widget", 2), new Line("gadget", 1), new Line("widget", 5) }),
    ("B9", Array.Empty<Line>()),
};
var channel = new Dictionary<string, string> { ["widget"] = "inventory.widgets", ["gadget"] = "inventory.gadgets" };

foreach (var (id, lines) in orders)
{
    Console.WriteLine($"order {id} has {lines.Length} lines");
    foreach (var m in Splitter.Split(id, lines))
    {
        if (m.Line is null)
        {
            Console.WriteLine($"  {id} 0/0 empty order -> orders.empty");
            continue;
        }
        Console.WriteLine($"  {id} {m.Seq}/{m.Size} {m.Line.Kind} x{m.Line.Qty} -> {channel[m.Line.Kind]}");
    }
}

record Line(string Kind, int Qty);

// One message from the splitter, with the headers that an aggregator needs.
record Msg(string CorrelationId, int Seq, int Size, Line? Line);

static class Splitter
{
    public static IEnumerable<Msg> Split(string orderId, Line[] lines)
    {
        if (lines.Length == 0)
        {
            // One message with size 0, so that a later aggregator is not left waiting.
            return new[] { new Msg(orderId, 0, 0, null) };
        }
        return lines.Select((line, i) => new Msg(orderId, i + 1, lines.Length, line));
    }
}
Output
order A7 has 3 lines
  A7 1/3 widget x2 -> inventory.widgets
  A7 2/3 gadget x1 -> inventory.gadgets
  A7 3/3 widget x5 -> inventory.widgets
order B9 has 0 lines
  B9 0/0 empty order -> orders.empty
  • Verdict: idiom. The overload of Select with an index makes one record for each line, with the sequence number i + 1.
  • Select is lazy, so the parts are made as the loop reads them; the size is known here because the input is an array.
  • The nullable Line? in the record marks the message for an empty order.
package main

import "fmt"

// Line is one line of an order.
type Line struct {
	Kind string
	Qty  int
}

// Msg is one message from the splitter, with the headers that an aggregator needs.
type Msg struct {
	CorrelationID string
	Seq, Size     int
	Line          *Line
}

func split(orderID string, lines []Line) []Msg {
	if len(lines) == 0 {
		// One message with size 0, so that a later aggregator is not left waiting.
		return []Msg{{CorrelationID: orderID}}
	}
	out := make([]Msg, 0, len(lines))
	for i := range lines {
		out = append(out, Msg{CorrelationID: orderID, Seq: i + 1, Size: len(lines), Line: &lines[i]})
	}
	return out
}

func main() {
	ids := []string{"A7", "B9"}
	orders := map[string][]Line{
		"A7": {{"widget", 2}, {"gadget", 1}, {"widget", 5}},
		"B9": {},
	}
	channel := map[string]string{"widget": "inventory.widgets", "gadget": "inventory.gadgets"}
	for _, id := range ids {
		fmt.Printf("order %s has %d lines\n", id, len(orders[id]))
		for _, m := range split(id, orders[id]) {
			if m.Line == nil {
				fmt.Printf("  %s 0/0 empty order -> orders.empty\n", id)
				continue
			}
			fmt.Printf("  %s %d/%d %s x%d -> %s\n", id, m.Seq, m.Size, m.Line.Kind, m.Line.Qty, channel[m.Line.Kind])
		}
	}
}
Output
order A7 has 3 lines
  A7 1/3 widget x2 -> inventory.widgets
  A7 2/3 gadget x1 -> inventory.gadgets
  A7 3/3 widget x5 -> inventory.widgets
order B9 has 0 lines
  B9 0/0 empty order -> orders.empty
  • Verdict: idiom. A loop over the slice of lines appends one Msg for each line; make with the capacity len(lines) sizes the result once.
  • Line is a pointer in Msg, so the message for an empty order has a nil line and is easy to test.
  • The slice ids gives a fixed order for the output, because the order of a Go map is not defined.

Consequences

Benefits.

  • Simple receivers. Each receiver gets one item and does not need to know the structure of the whole message.
  • Parallel work. The parts can go to different systems or threads. Camel can process each split message on its own thread.5
  • Fit with other patterns. Splitter, router and aggregator together make the Composed Message Processor of the book, which splits a message, routes the parts and puts the replies together again.7

Liabilities.

  • The parts can fail alone. By default, the Camel splitter goes on with the other parts when one part fails. Its example has an error on row 17 of 1000 rows, and Camel processes the other 983.5 An option stopOnException changes this.
  • The size can be unknown. In streaming mode, or when the splitter returns an iterator, the size is not known in advance. In Spring Integration, SEQUENCE_SIZE is then 0, and the default release strategy of an aggregator does not release the group.4
  • More messages. One message becomes many, each with its own headers and its own cost on the broker.
  • Order. The parts can arrive in a different order from the order of the items.

When not to use it

When all items go to the same place and the receiver can take the whole message. One message is cheaper than many.

When the items must be changed as one unit. If the order must be accepted or refused as a whole, a split needs an aggregator and a rule for a partial failure. Keep the message whole if there is no need to split it.

When the receiver wants batches. A splitter can publish one message for a subset of the elements, not only for each element.1

Aggregator. The reverse step: it collects related messages into one. Spring Integration says that splitters are very often "upstream producers in a pipeline that includes an aggregator".4 See Aggregator.

Composed Message Processor. A splitter, a router and an aggregator in one unit, for a message with many elements, each of which needs different processing.7

Scatter-Gather. It sends one request to many receivers, where the splitter sends a different part to each receiver. See Scatter-Gather.

Iterator. In one program, the Iterator pattern gives the elements of a collection one at a time; the streaming mode of a splitter uses an iterator to do the same for a message.5

Known uses

  • Apache Camel: the Split EIP, with the default and the streaming modes; the method updateNewExchange of Splitter.java at 4.14.0 sets the split index, the split size and a flag for the last part.6 By default, the result of the Split EIP is the original input message.5
  • Spring Integration: AbstractMessageSplitter fills in the correlation, the sequence number and the sequence size on each part.4
  • AWS Step Functions: the Map state runs "a set of workflow steps for each item in a dataset." Its inline mode allows up to 40 concurrent iterations, and its distributed mode up to 10,000 parallel child workflow executions.8

References

  1. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Splitter (problem and solution under CC BY), problem and solution statements; pattern text
  2. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Designing, Building, and Deploying Messaging Solutions, Addison-Wesley, 2003, Chapter 7, Message Routing, Splitter
  3. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Aggregator (problem and solution under CC BY), pattern text, completeness condition
  4. Spring Integration 7.1.1 reference source, Splitter, introduction; Programming Model
  5. Apache Camel 4.14.0 documentation source, Split EIP, Splitting with parallel processing; What is returned from Split EIP when its complete; Splitting modes; Stop processing in case of exception
  6. Apache Camel 4.14.0 source, Splitter.java, method updateNewExchange, lines 290 to 303
  7. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Composed Message Processor (problem and solution under CC BY), problem and solution statements
  8. AWS Step Functions Developer Guide, Map workflow state, introduction; Map state processing modes

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/A019X3/text.yaml