Programming Search⌘K

Patternadvanced

Sequential Convoy

Also called Sequential Convoy pattern, ordered processing per key, message sessions, message groups.

A sequential convoy gives each message a category key, such as an order id, and processes the messages of one category in order, one at a time, while different categories run in parallel.

Family
integration
Intent
Keep the order of related messages and still scale out, by a key on each message that puts it in a group, a lock that gives each group to one consumer at a time, and many consumers for many groups.
Also called
message sessions

Intent

Process the related messages in the order in which they come, and still use many consumers. The Azure page describes the pattern so. It puts related messages into categories and processes each category in sequence, one message at a time. Different categories are processed in parallel.1

Problem

Take a system that tracks orders. A stream of operations comes in: create an order, add a transaction, change an old transaction, delete the order. The operations of one order must be applied in their order, or the state of the order becomes wrong. But the queue mixes the operations of many orders.1

The two simple answers both fail.1

  • One consumer. It keeps the order, because it processes one message at a time, but it cannot scale.
  • Competing Consumers. Many consumers read in parallel and scale, but two of them can take two operations of the same order, and process them at the same time or in the wrong order.

The forces are order inside a group and throughput across all groups.

Solution

Give each message a category key that names its group, for example the order id. The broker uses the key to put the messages into logical groups. Inside a group, it keeps first-in, first-out order: a consumer that locks a group gets its messages in the order in which they were queued. Other consumers can process other groups at the same time.1

                                        +--> consumer 1: A1 A2 A3 A4
  producer --> [ A1 B1 A2 C1 B2 A3 ... ] +--> consumer 2: B1 B2 B3
                  one queue, key = order +--> consumer 3: C1 C2, then D1 D2

The participants are the producer, which sets the key on each message, the queue or broker, which groups the messages by key and locks a group for one consumer, and the consumers.1

Session locks. In Azure Service Bus, a group is a session. A sender sets the session id on each message; at the AMQP level, this is the group-id property.2 A receiver that accepts a session has an exclusive lock on all the messages with that session id, also on those that come later. The lock ends when the receiver closes the session or when the lock expires, and the receiver can renew it.2 While no receiver holds the lock of a session, no messages of that session are delivered.2

The program below sends the operations of 4 orders through one queue. A create takes 3 ticks, and each other operation takes 1 tick. An operation is out of order if it starts before the previous operation of its order is done.

# Operations for four orders arrive interleaved on one queue.
# A "create" takes 3 ticks; any other operation takes 1 tick.
ops = [("A", "create"), ("B", "create"), ("A", "add"), ("C", "create"), ("A", "add"),
       ("B", "add"), ("D", "create"), ("C", "add"), ("A", "delete"), ("B", "modify"),
       ("D", "add"), ("C", "delete")]
COST = {"create": 3}


def cost(op):
    return COST.get(op[1], 1)


def check(runs):
    """runs: (start, end, order, index in its order). Count operations that start before the previous one ends."""
    last_end, bad = {}, 0
    for start, end, order, _ in sorted(runs, key=lambda r: (r[2], r[3])):
        if start < last_end.get(order, 0):
            bad += 1
        last_end[order] = end
    return bad, max(r[1] for r in runs)


def indexed():
    seen = {}
    for op in ops:
        seen[op[0]] = seen.get(op[0], -1) + 1
        yield op, seen[op[0]]


def competing(workers):
    free = [0] * workers
    runs = []
    for op, i in indexed():
        w = free.index(min(free))
        start = free[w]
        free[w] = start + cost(op)
        runs.append((start, free[w], op[0], i))
    return check(runs)


def convoy(workers):
    groups = {}
    for op, i in indexed():
        groups.setdefault(op[0], []).append((op, i))
    free = [0] * workers
    runs = []
    for order in groups:  # a free worker locks the next session and empties it
        w = free.index(min(free))
        for op, i in groups[order]:
            start = free[w]
            free[w] = start + cost(op)
            runs.append((start, free[w], order, i))
    return check(runs)


for label, (bad, done) in [("one consumer", competing(1)),
                           ("3 competing consumers", competing(3)),
                           ("3 consumers, one session at a time", convoy(3))]:
    print("%-35s done at tick %2d, %d out of order" % (label + ":", done, bad))
Output
one consumer:                       done at tick 20, 0 out of order
3 competing consumers:              done at tick  7, 2 out of order
3 consumers, one session at a time: done at tick  9, 0 out of order

One consumer is correct but slow. Three competing consumers are fast, but 2 operations start while the create of their order is still running. With one session at a time for each consumer, nothing is out of order, and the work ends at tick 9. The longest order takes 6 ticks, and the fourth order must wait for a free consumer.

Example

Each example file runs 2 workers on 3 sessions. A worker locks the next free session and keeps it until the session is empty. The second message of session B cannot be processed. While it fails, session B waits, but session A and then session C go on with the other worker. After 3 deliveries, the message goes to the dead letter queue, and session B goes on. The Azure page asks for this. A message that fails again and again blocks all later messages in its session. Thus, count the deliveries, and move the message to a dead-letter queue after a limit.1 Service Bus does this with the maximum delivery count of the queue, which is 10 by default; after that, the receiver gets the next messages of the session.2

PythonGitHub
from collections import deque

# (session id, operation, argument) in the order they arrive on the queue
arrivals = [("A", "create", ""), ("B", "create", ""), ("C", "create", ""), ("A", "add", "10"),
            ("B", "add", "x"), ("A", "add", "5"), ("C", "add", "3"), ("B", "add", "7")]
MAX_DELIVERIES = 3

sessions = {}  # a dict keeps the order in which the sessions first appear
for sid, op, arg in arrivals:
    sessions.setdefault(sid, deque()).append((op, arg))

locks = {}                          # session id -> worker that holds its lock
holding = {"w1": None, "w2": None}  # worker -> session id
deliveries = {}
totals, dead, out_of_order = {}, [], 0
rnd = 0
while any(sessions.values()):
    rnd += 1
    for w in holding:
        if holding[w] is None:
            free = next((s for s, q in sessions.items() if q and s not in locks), None)
            if free is None:
                continue
            locks[free], holding[w] = w, free
            print("%d %s locks %s" % (rnd, w, free))
        sid = holding[w]
        op, arg = sessions[sid][0]
        try:
            if op == "create":
                totals[sid] = 0
            elif sid not in totals:
                out_of_order += 1
            else:
                totals[sid] += int(arg)
            print("%d %s %s %s %s" % (rnd, w, sid, op, arg) if arg else "%d %s %s %s" % (rnd, w, sid, op))
            sessions[sid].popleft()
            deliveries.pop(sid, None)
        except ValueError:
            deliveries[sid] = deliveries.get(sid, 0) + 1
            if deliveries[sid] < MAX_DELIVERIES:
                print("%d %s %s %s %s failed, delivery %d" % (rnd, w, sid, op, arg, deliveries[sid]))
            else:
                print("%d %s %s %s %s failed, delivery %d: to the dead letter queue" % (rnd, w, sid, op, arg, deliveries[sid]))
                dead.append("%s %s %s" % (sid, op, arg))
                sessions[sid].popleft()
                deliveries.pop(sid)
        if not sessions[sid]:
            del locks[sid]
            holding[w] = None

print("totals: " + ", ".join("%s %d" % kv for kv in totals.items())
      + "; dead letter: " + ", ".join(dead) + "; out of order: %d" % out_of_order)
Output
1 w1 locks A
1 w1 A create
1 w2 locks B
1 w2 B create
2 w1 A add 10
2 w2 B add x failed, delivery 1
3 w1 A add 5
3 w2 B add x failed, delivery 2
4 w1 locks C
4 w1 C create
4 w2 B add x failed, delivery 3: to the dead letter queue
5 w1 C add 3
5 w2 B add 7
totals: A 15, B 7, C 3; dead letter: B add x; out of order: 0
  • Verdict: idiom. A dict of deque objects holds the sessions; a dict keeps the order in which its keys were added, so the workers lock the sessions in the order of first arrival.
  • The dict locks maps a session to the worker that holds it, and a worker keeps its session until the session is empty.
  • int("x") raises ValueError, which is the failure; the message stays at the head of its session until the third delivery.
JavaGitHub
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
    record Op(String name, String arg) {
        String label(String sid) {
            return arg.isEmpty() ? sid + " " + name : sid + " " + name + " " + arg;
        }
    }

    static final int MAX_DELIVERIES = 3;

    public static void main(String[] args) {
        String[][] arrivals = {{"A", "create", ""}, {"B", "create", ""}, {"C", "create", ""}, {"A", "add", "10"},
                {"B", "add", "x"}, {"A", "add", "5"}, {"C", "add", "3"}, {"B", "add", "7"}};
        Map<String, ArrayDeque<Op>> sessions = new LinkedHashMap<>(); // keeps the order of first arrival
        for (String[] a : arrivals) {
            sessions.computeIfAbsent(a[0], k -> new ArrayDeque<>()).add(new Op(a[1], a[2]));
        }
        Map<String, String> holding = new LinkedHashMap<>();
        holding.put("w1", null);
        holding.put("w2", null);
        Map<String, String> locks = new HashMap<>();
        Map<String, Integer> deliveries = new HashMap<>();
        Map<String, Integer> totals = new LinkedHashMap<>();
        List<String> dead = new ArrayList<>();
        int outOfOrder = 0;

        for (int rnd = 1; sessions.values().stream().anyMatch(q -> !q.isEmpty()); rnd++) {
            for (String w : holding.keySet()) {
                if (holding.get(w) == null) {
                    String free = sessions.entrySet().stream()
                            .filter(e -> !e.getValue().isEmpty() && !locks.containsKey(e.getKey()))
                            .map(Map.Entry::getKey).findFirst().orElse(null);
                    if (free == null) {
                        continue;
                    }
                    locks.put(free, w);
                    holding.put(w, free);
                    System.out.printf("%d %s locks %s%n", rnd, w, free);
                }
                String sid = holding.get(w);
                Op op = sessions.get(sid).peekFirst();
                try {
                    if (op.name().equals("create")) {
                        totals.put(sid, 0);
                    } else if (!totals.containsKey(sid)) {
                        outOfOrder++;
                    } else {
                        totals.merge(sid, Integer.parseInt(op.arg()), Integer::sum);
                    }
                    System.out.printf("%d %s %s%n", rnd, w, op.label(sid));
                    sessions.get(sid).pollFirst();
                    deliveries.remove(sid);
                } catch (NumberFormatException e) {
                    int n = deliveries.merge(sid, 1, Integer::sum);
                    if (n < MAX_DELIVERIES) {
                        System.out.printf("%d %s %s failed, delivery %d%n", rnd, w, op.label(sid), n);
                    } else {
                        System.out.printf("%d %s %s failed, delivery %d: to the dead letter queue%n", rnd, w, op.label(sid), n);
                        dead.add(op.label(sid));
                        sessions.get(sid).pollFirst();
                        deliveries.remove(sid);
                    }
                }
                if (sessions.get(sid).isEmpty()) {
                    locks.remove(sid);
                    holding.put(w, null);
                }
            }
        }

        var parts = new ArrayList<String>();
        totals.forEach((k, v) -> parts.add(k + " " + v));
        System.out.printf("totals: %s; dead letter: %s; out of order: %d%n",
                String.join(", ", parts), String.join(", ", dead), outOfOrder);
    }
}
Output
1 w1 locks A
1 w1 A create
1 w2 locks B
1 w2 B create
2 w1 A add 10
2 w2 B add x failed, delivery 1
3 w1 A add 5
3 w2 B add x failed, delivery 2
4 w1 locks C
4 w1 C create
4 w2 B add x failed, delivery 3: to the dead letter queue
5 w1 C add 3
5 w2 B add 7
totals: A 15, B 7, C 3; dead letter: B add x; out of order: 0
  • Verdict: idiom. A LinkedHashMap of ArrayDeque objects holds the sessions and keeps the order of first arrival.
  • A record Op is one operation, and computeIfAbsent makes a session when its first message comes.
  • Integer.parseInt throws NumberFormatException for x; the catch block counts the delivery and leaves the message at the head of its session.
using System;
using System.Collections.Generic;
using System.Linq;

const int MaxDeliveries = 3;
var arrivals = new (string Session, string Name, string Arg)[] {
    ("A", "create", ""), ("B", "create", ""), ("C", "create", ""), ("A", "add", "10"),
    ("B", "add", "x"), ("A", "add", "5"), ("C", "add", "3"), ("B", "add", "7") };
var order = new List<string>(); // the sessions in the order they first appear
var sessions = new Dictionary<string, Queue<Op>>();
foreach (var a in arrivals)
{
    if (!sessions.ContainsKey(a.Session))
    {
        order.Add(a.Session);
        sessions[a.Session] = new Queue<Op>();
    }
    sessions[a.Session].Enqueue(new Op(a.Name, a.Arg));
}

string[] workers = { "w1", "w2" };
var holding = new Dictionary<string, string?> { ["w1"] = null, ["w2"] = null };
var locked = new HashSet<string>();
var deliveries = new Dictionary<string, int>();
var totals = new Dictionary<string, int>();
var dead = new List<string>();
int outOfOrder = 0;

for (int rnd = 1; sessions.Values.Any(q => q.Count > 0); rnd++)
{
    foreach (var w in workers)
    {
        if (holding[w] is null)
        {
            var free = order.FirstOrDefault(s => sessions[s].Count > 0 && !locked.Contains(s));
            if (free is null)
            {
                continue;
            }
            locked.Add(free);
            holding[w] = free;
            Console.WriteLine($"{rnd} {w} locks {free}");
        }
        var sid = holding[w]!;
        var op = sessions[sid].Peek();
        var label = op.Arg == "" ? $"{sid} {op.Name}" : $"{sid} {op.Name} {op.Arg}";
        bool ok = true;
        if (op.Name == "create")
        {
            totals[sid] = 0;
        }
        else if (!totals.ContainsKey(sid))
        {
            outOfOrder++;
        }
        else if (int.TryParse(op.Arg, out var n))
        {
            totals[sid] += n;
        }
        else
        {
            ok = false;
        }
        if (ok)
        {
            Console.WriteLine($"{rnd} {w} {label}");
            sessions[sid].Dequeue();
            deliveries.Remove(sid);
        }
        else
        {
            deliveries[sid] = deliveries.GetValueOrDefault(sid) + 1;
            if (deliveries[sid] < MaxDeliveries)
            {
                Console.WriteLine($"{rnd} {w} {label} failed, delivery {deliveries[sid]}");
            }
            else
            {
                Console.WriteLine($"{rnd} {w} {label} failed, delivery {deliveries[sid]}: to the dead letter queue");
                dead.Add(label);
                sessions[sid].Dequeue();
                deliveries.Remove(sid);
            }
        }
        if (sessions[sid].Count == 0)
        {
            locked.Remove(sid);
            holding[w] = null;
        }
    }
}

var parts = order.Select(s => $"{s} {totals[s]}");
Console.WriteLine($"totals: {string.Join(", ", parts)}; dead letter: {string.Join(", ", dead)}; out of order: {outOfOrder}");

record Op(string Name, string Arg);
Output
1 w1 locks A
1 w1 A create
1 w2 locks B
1 w2 B create
2 w1 A add 10
2 w2 B add x failed, delivery 1
3 w1 A add 5
3 w2 B add x failed, delivery 2
4 w1 locks C
4 w1 C create
4 w2 B add x failed, delivery 3: to the dead letter queue
5 w1 C add 3
5 w2 B add 7
totals: A 15, B 7, C 3; dead letter: B add x; out of order: 0
  • Verdict: idiom. A Dictionary of Queue<Op> holds the sessions, and a List keeps the order of first arrival, because the order of a Dictionary is not guaranteed.
  • FirstOrDefault finds the first session that has messages and no lock.
  • int.TryParse returns false for x, so the failure needs no exception; the message stays at the head of its session until the third delivery.
package main

import (
	"fmt"
	"strconv"
	"strings"
)

type Op struct{ Name, Arg string }

const maxDeliveries = 3

func main() {
	arrivals := []struct{ Session, Name, Arg string }{
		{"A", "create", ""}, {"B", "create", ""}, {"C", "create", ""}, {"A", "add", "10"},
		{"B", "add", "x"}, {"A", "add", "5"}, {"C", "add", "3"}, {"B", "add", "7"},
	}
	var order []string // the sessions in the order they first appear
	sessions := map[string][]Op{}
	for _, a := range arrivals {
		if _, ok := sessions[a.Session]; !ok {
			order = append(order, a.Session)
		}
		sessions[a.Session] = append(sessions[a.Session], Op{a.Name, a.Arg})
	}

	workers := []string{"w1", "w2"}
	holding := map[string]string{} // worker -> session id
	locked := map[string]bool{}
	deliveries := map[string]int{}
	totals := map[string]int{}
	var dead []string
	outOfOrder := 0
	pending := func() bool {
		for _, q := range sessions {
			if len(q) > 0 {
				return true
			}
		}
		return false
	}

	for rnd := 1; pending(); rnd++ {
		for _, w := range workers {
			if holding[w] == "" {
				for _, s := range order {
					if len(sessions[s]) > 0 && !locked[s] {
						locked[s], holding[w] = true, s
						fmt.Printf("%d %s locks %s\n", rnd, w, s)
						break
					}
				}
				if holding[w] == "" {
					continue
				}
			}
			sid := holding[w]
			op := sessions[sid][0]
			label := strings.TrimSpace(fmt.Sprintf("%s %s %s", sid, op.Name, op.Arg))
			ok := true
			switch _, created := totals[sid]; {
			case op.Name == "create":
				totals[sid] = 0
			case !created:
				outOfOrder++
			default:
				n, err := strconv.Atoi(op.Arg)
				if err != nil {
					ok = false
				} else {
					totals[sid] += n
				}
			}
			if ok {
				fmt.Printf("%d %s %s\n", rnd, w, label)
				sessions[sid] = sessions[sid][1:]
				delete(deliveries, sid)
			} else {
				deliveries[sid]++
				if deliveries[sid] < maxDeliveries {
					fmt.Printf("%d %s %s failed, delivery %d\n", rnd, w, label, deliveries[sid])
				} else {
					fmt.Printf("%d %s %s failed, delivery %d: to the dead letter queue\n", rnd, w, label, deliveries[sid])
					dead = append(dead, label)
					sessions[sid] = sessions[sid][1:]
					delete(deliveries, sid)
				}
			}
			if len(sessions[sid]) == 0 {
				delete(locked, sid)
				holding[w] = ""
			}
		}
	}

	var parts []string
	for _, s := range order {
		parts = append(parts, fmt.Sprintf("%s %d", s, totals[s]))
	}
	fmt.Printf("totals: %s; dead letter: %s; out of order: %d\n", strings.Join(parts, ", "), strings.Join(dead, ", "), outOfOrder)
}
Output
1 w1 locks A
1 w1 A create
1 w2 locks B
1 w2 B create
2 w1 A add 10
2 w2 B add x failed, delivery 1
3 w1 A add 5
3 w2 B add x failed, delivery 2
4 w1 locks C
4 w1 C create
4 w2 B add x failed, delivery 3: to the dead letter queue
5 w1 C add 3
5 w2 B add 7
totals: A 15, B 7, C 3; dead letter: B add x; out of order: 0
  • Verdict: idiom. A map of slices holds the sessions, and a separate slice order keeps the order of first arrival, because the order of a range over a map is not fixed in Go.
  • The map locked is the session lock; a worker keeps its session until the slice is empty.
  • strconv.Atoi returns an error for x, and the message stays at the head of its session until the third delivery.

Consequences

Benefits.

  • Order inside each group. The messages of one category are processed in sequence, with no race conditions and no workarounds for wrong order.1
  • Scale across groups. Each category is an independent unit of concurrency, so more consumers give more throughput, as long as there are enough active categories.1
  • Loose coupling. The producer does not know which consumer processes a message, or when.1

Liabilities.

  • The choice of the key. The key sets the unit of parallelism. A key that is too coarse, such as one customer id for all orders, limits the parallelism; a key that is too fine gives no useful order.1
  • A limit for each group. The throughput of one category is limited by the time for one message.1
  • Poison messages. A message that always fails blocks its whole session.1
  • Locks. A lock that is too short can expire and cause a message to be processed again; a lock that is too long delays the recovery from a stalled consumer.1
  • Replay breaks the order. If a message from the dead-letter queue is sent back to the original queue, it gets a new sequence number, and its place in the order of the session is lost.2
  • Wrong keys. If a producer sets a wrong key, the message goes into the wrong session and corrupts the state of that group.1
  • Broker support. Not all brokers lock a group or keep order inside a partition. Without such support, the consumers must coordinate themselves, which adds complexity and the risk of copies, lost messages or wrong order.1 In Service Bus, the basic tier has no sessions, and a queue with sessions takes only messages with a session id.2

When not to use it

The Azure page names two cases.1

  • Very high throughput. For millions of messages per minute, the FIFO rule limits how far the system can scale.
  • No need for order. If each message can be processed alone, Competing Consumers scale more simply and need no session locks.

If the throughput must be very high, the Azure page asks whether the strict order is necessary for the whole life of a message. It names two other ways. One is a start message and an end message around a sequence. The other is a sort by time stamp inside a batch window, after which the batch is processed in parallel.1

Serial in, parallel out. In the Azure example, all transactions first go through one ledger queue and one ledger processor. The processor sets the session id of each transaction to its order id and sends it to a second queue, where order processors take one session each. The ledger stage is the main bottleneck.1

Order on arrival. Messages can still come to the broker in the wrong order, because the network delay from each producer differs. The Azure page suggests sequence numbers inside each category, and a flag on the last message of a sequence.1 Service Bus leaves the start and the end of a sequence to the application, for example a label of start, content and end.2

Resequencer. When the order is already lost, a resequencer puts it back. The book asks: "How can we get a stream of related but out-of-sequence messages back into the correct order?" The answer: "Use a stateful filter, a Resequencer", "to collect and re-order messages so that they can be published to the output channel in a specified order."3 Camel has a batch mode, which collects up to 100 messages or waits one second by default and then sorts them, and a stream mode, which finds the gaps between messages.4

With priorities. The Azure page says a convoy can be combined with a priority queue, with one session for each priority, when the order inside each priority level must stay.1

Known uses

  • Azure Service Bus: message sessions, the main Azure mechanism for this pattern. Azure Functions can process one session at a time with the Service Bus trigger, and Logic Apps with the peek-lock connector.12
  • Apache Camel: the Resequence EIP of 4.14.0, which restores an order by an expression, such as a header with a sequence number.4

References

  1. Microsoft, Azure Architecture Center, Sequential Convoy pattern, context and problem; solution; problems and considerations; when to use this pattern; example; related resources
  2. Microsoft, Azure Service Bus documentation, Message sessions, first-in, first out (FIFO) pattern; session features
  3. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Resequencer (problem and solution under CC BY), problem and solution statements; pattern text
  4. Apache Camel 4.14.0 documentation source, Resequence EIP, introduction; batch resequencing

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)
WritingW3 standard
  • a history with a source