Conceptadvanced
Message ordering
Also called ordered delivery, message order, in-order delivery, ordering key.
Message ordering is the promise that consumers see related messages in the order in which they were sent. Brokers keep it inside a queue, a partition or a key, and rarely across all messages.
- Applies to
- core-languages
Idea
Many messages depend on the messages before them. An order is created before it is paid, and paid before it is shipped. RabbitMQ says that message ordering matters when there are causal dependencies between messages.1 If a consumer sees "shipped" before "created", it can reject the message, or it can store a wrong state.
A messaging system can promise order at three levels.
- No order. The consumers can see the messages in any order.
- Total order. All consumers see all messages in the order in which they were sent.
- Order inside a key. The messages that have the same key, such as an order id or a customer id, keep their order. Messages with different keys have no fixed order between them.
Kafka, Google Cloud Pub/Sub and Amazon SQS FIFO queues give the third level.234 It keeps the order that most applications need, and many consumers can still work in parallel on different keys.
How it works
The queue keeps the order; the consumers break it. In RabbitMQ, a queue is an ordered collection with FIFO semantics. Messages that are published on one channel are enqueued in the order of publication. Messages from several connections or channels are interleaved.1 The broker still delivers in the order of the queue, but other events change the order that the consumers see.1 The program below sends 12 messages with the keys A, B and C, 4 for each key, in the order A1 B1 C1 A2 and so on. Consumer 0 needs 1 tick for a message, and consumer 1 needs 3 ticks. The program counts the pairs of messages with one key that finish in the wrong order.
# 3 keys, 4 messages each, sent in the order A1 B1 C1 A2 B2 C2 ...
# Consumer 0 needs 1 tick for a message, consumer 1 needs 3 ticks.
sent = [(k, n) for n in range(1, 5) for k in "ABC"]
SPEED = [1, 3]
def process(assign):
"""assign(i, message) gives the consumer; each consumer works through its own list in order."""
free = [0] * len(SPEED)
done = []
for i, m in enumerate(sent):
c = assign(i, m)
free[c] += SPEED[c]
done.append((free[c], i, m))
return [m for _, _, m in sorted(done)]
def report(name, order):
per_key = sum(1 for i, a in enumerate(order) for b in order[i + 1:] if a[0] == b[0] and a[1] > b[1])
total = "kept" if order == sent else "lost"
print("%-26s total order %s, %d pairs out of order inside a key" % (name + ":", total, per_key))
report("one consumer", process(lambda i, m: 0))
report("2 consumers, round robin", process(lambda i, m: i % 2))
report("2 consumers, by key", process(lambda i, m: {"A": 0, "B": 1, "C": 0}[m[0]]))
# one consumer, but A2 fails once and goes back to the end of the queue
queue, order = list(sent), []
failed = False
while queue:
m = queue.pop(0)
if m == ("A", 2) and not failed:
failed = True
queue.append(m)
continue
order.append(m)
report("one consumer, A2 requeued", order)
one consumer: total order kept, 0 pairs out of order inside a key
2 consumers, round robin: total order lost, 3 pairs out of order inside a key
2 consumers, by key: total order lost, 0 pairs out of order inside a key
one consumer, A2 requeued: total order lost, 2 pairs out of order inside a key
One consumer keeps the total order. Two consumers that take turns lose the total order, and also the order inside the keys, because the slow consumer finishes its messages late. When all the messages of one key go to the same consumer, the total order is lost but each key keeps its order. A message that fails and goes back to the end of the queue breaks the order of its key, even with one consumer.
Order inside a key. Each broker has a name for the key.
- Kafka. A topic is divided into partitions. Events with the same key go to the same partition, and Kafka guarantees that any consumer of a partition reads its events in exactly the order in which they were written.2 The producer hashes the key to select the partition.5 Each partition is consumed by exactly one consumer in each consumer group at a time.5
- Amazon SQS. In a FIFO queue, the attribute
MessageGroupIdputs messages in groups. The messages of one group are always processed one at a time, in strict order.4 - Google Cloud Pub/Sub. Related messages have the same ordering key, of up to 1 KB. They must be published in the same region, and the subscription must have message ordering enabled. Messages with an empty ordering key are not ordered.3
- Azure Service Bus. A session holds the messages that have one session id. A receiver that accepts a session holds an exclusive lock on all its messages, so one receiver processes them in order.6 The Sequential Convoy page describes this pattern.
- RabbitMQ. A stream is an append-only log, where the offset of a message never changes. Or a queue has Single Active Consumer, so only one consumer receives messages at a time.1
Fix the order at the receiver. If the channel cannot keep the order, the receiver can put the messages back in order. The problem statement of the Resequencer in Enterprise Integration Patterns asks: "How can we get a stream of related but out-of-sequence messages back into the correct order?"7 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."7 Each message carries a key and a sequence number for that key. The resequencer keeps the next number that it expects for each key. It holds a message that comes too early, and it releases the held messages when the missing one arrives. The output channel after it must keep the order.7
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Idiom | Std::map for the next numbers and std::unordered_map for the held messages of each key. Alternative: The Java example. |
| Java | Idiom | |
| C | Idiom | Arrays indexed by key and sequence number when the ranges are small, or a hash table written by hand. Alternative: The Go example. |
| C# | Idiom | |
| JavaScript | Idiom | Map objects hold the next number for each key and the messages that came too early, as in the Python example. Alternative: The Python example. |
| TypeScript | Idiom | As in JavaScript, Map objects with types for the key and the sequence number. Alternative: The Java example. |
| Go | Idiom | |
| Rust | Idiom | A BTreeMap of the next numbers and a HashMap of held messages for each key, from std::collections. Alternative: The Go example. |
| Kotlin | Idiom | SortedMapOf for the next numbers and mutableMapOf with getOrPut for the held messages. Alternative: The Java example. |
| SQL | Idiom | A table of held messages with a key and a sequence column; a query with ORDER BY key and sequence releases the rows up to the first gap. Alternative: The Python example. |
| Bash | Idiom | Associative arrays, declared with declare -A, hold the next numbers and the held messages. Alternative: The Python example. |
| PowerShell | Idiom | Hashtables, or the .NET dictionaries as in C#. Alternative: The C# example. |
| HTML | Does not apply | Markup has no messages. |
| CSS | Does not apply | Style rules have no messages. |
| Regular expressions | Does not apply | A pattern has no messages and no state. |
The example files build a resequencer in memory. Eight messages with the keys A and B arrive out of order, with one copy. The resequencer holds A3 until A2 arrives, and it drops the second A3.
| Language | Verdict | Form |
|---|---|---|
| Python | idiom | a dict of the next number for each key and a dict of held messages |
| Go | idiom | maps, with sort.Strings for a fixed order of the keys in the output |
| Java | idiom | TreeMap and HashMap, with computeIfAbsent for the held messages of a key |
| C# | idiom | SortedDictionary with an ordinal comparer, and Dictionary.Remove(key, out value) |
| JavaScript | idiom | Map objects for the next numbers and the held messages |
| TypeScript | idiom | as JavaScript, with types for the key and the sequence number |
| Rust | idiom | BTreeMap and HashMap from the standard library |
| C | idiom | arrays indexed by key and sequence number, or a hash table written by hand |
| C++ | idiom | std::map and std::unordered_map |
| Kotlin | idiom | sortedMapOf and mutableMapOf, with getOrPut |
| PowerShell | idiom | hashtables, or .NET dictionaries as in C# |
| Bash | idiom | associative arrays, with declare -A |
| SQL | idiom | a table of held messages; a query with ORDER BY key and sequence releases the rows up to the first gap |
| Regex | n/a | a pattern has no messages and no state |
| HTML/CSS | n/a | markup and style rules have no messages |
No language has message order as a feature. Order is a property of the broker and of the code around it. The resequencer is the same small piece of state in each language. One map gives the next number for each key, and one map gives the messages that wait for each key.
# Messages arrive with a key and a sequence number for each key, out of order and with one copy.
arrivals = [("A", 1), ("A", 3), ("B", 1), ("A", 2), ("B", 3), ("A", 3), ("B", 2), ("A", 4)]
expected = {} # key -> next sequence number to deliver
held = {} # key -> {sequence number: message}
for key, seq in arrivals:
nxt = expected.get(key, 1)
name = "%s%d" % (key, seq)
if seq < nxt or seq in held.get(key, {}):
print("%s: copy, dropped" % name)
continue
held.setdefault(key, {})[seq] = name
out = []
while nxt in held[key]:
out.append(held[key].pop(nxt))
nxt += 1
expected[key] = nxt
if out:
print("%s: deliver %s" % (name, " ".join(out)))
else:
print("%s: hold, waiting for %s%d" % (name, key, nxt))
left = sum(len(h) for h in held.values())
print("held at the end: %d; next: %s" % (left, ", ".join("%s%d" % kv for kv in sorted(expected.items()))))
A1: deliver A1
A3: hold, waiting for A2
B1: deliver B1
A2: deliver A2 A3
B3: hold, waiting for B2
A3: copy, dropped
B2: deliver B2 B3
A4: deliver A4
held at the end: 0; next: A5, B4
- Verdict: idiom. Two dicts hold the state:
expectedmaps each key to the next number to deliver, andheldmaps each key to the messages that came too early. setdefaultmakes the dict of held messages for a new key, andpopremoves each message as the loop delivers it.- A message whose number is below the next number, or that is already held, is a copy, so the resequencer also drops duplicates.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.TreeMap;
public class Main {
record Msg(String key, int seq) {
}
public static void main(String[] args) {
// Messages arrive with a key and a sequence number for each key, out of order and with one copy.
List<Msg> arrivals = List.of(new Msg("A", 1), new Msg("A", 3), new Msg("B", 1), new Msg("A", 2),
new Msg("B", 3), new Msg("A", 3), new Msg("B", 2), new Msg("A", 4));
Map<String, Integer> expected = new TreeMap<>(); // key -> next sequence number to deliver
Map<String, Map<Integer, String>> held = new HashMap<>(); // key -> waiting messages
for (Msg m : arrivals) {
int next = expected.getOrDefault(m.key(), 1);
String name = m.key() + m.seq();
Map<Integer, String> h = held.computeIfAbsent(m.key(), k -> new HashMap<>());
if (m.seq() < next || h.containsKey(m.seq())) {
System.out.println(name + ": copy, dropped");
continue;
}
h.put(m.seq(), name);
List<String> out = new ArrayList<>();
while (h.containsKey(next)) {
out.add(h.remove(next));
next++;
}
expected.put(m.key(), next);
if (out.isEmpty()) {
System.out.println(name + ": hold, waiting for " + m.key() + next);
} else {
System.out.println(name + ": deliver " + String.join(" ", out));
}
}
int left = held.values().stream().mapToInt(Map::size).sum();
StringJoiner nexts = new StringJoiner(", ");
expected.forEach((k, v) -> nexts.add(k + v));
System.out.println("held at the end: " + left + "; next: " + nexts);
}
}
A1: deliver A1
A3: hold, waiting for A2
B1: deliver B1
A2: deliver A2 A3
B3: hold, waiting for B2
A3: copy, dropped
B2: deliver B2 B3
A4: deliver A4
held at the end: 0; next: A5, B4
- Verdict: idiom. A
TreeMapholds the next number for each key, so the keys print in sorted order, and aHashMapfor each key holds the early messages. computeIfAbsentmakes the map of held messages the first time that a key arrives.containsKeytests for the next message, andremovereturns it as it takes it out of the map.
// Messages arrive with a key and a sequence number for each key, out of order and with one copy.
(string Key, int Seq)[] arrivals = [("A", 1), ("A", 3), ("B", 1), ("A", 2), ("B", 3), ("A", 3), ("B", 2), ("A", 4)];
var expected = new SortedDictionary<string, int>(StringComparer.Ordinal); // key -> next sequence number
var held = new Dictionary<string, Dictionary<int, string>>(); // key -> waiting messages
foreach (var (key, seq) in arrivals)
{
int next = expected.GetValueOrDefault(key, 1);
string name = $"{key}{seq}";
if (!held.TryGetValue(key, out var h))
{
h = new Dictionary<int, string>();
held[key] = h;
}
if (seq < next || h.ContainsKey(seq))
{
Console.WriteLine($"{name}: copy, dropped");
continue;
}
h[seq] = name;
var output = new List<string>();
while (h.Remove(next, out var v))
{
output.Add(v);
next++;
}
expected[key] = next;
Console.WriteLine(output.Count > 0
? $"{name}: deliver {string.Join(" ", output)}"
: $"{name}: hold, waiting for {key}{next}");
}
int left = held.Values.Sum(d => d.Count);
Console.WriteLine($"held at the end: {left}; next: {string.Join(", ", expected.Select(kv => $"{kv.Key}{kv.Value}"))}");
A1: deliver A1
A3: hold, waiting for A2
B1: deliver B1
A2: deliver A2 A3
B3: hold, waiting for B2
A3: copy, dropped
B2: deliver B2 B3
A4: deliver A4
held at the end: 0; next: A5, B4
- Verdict: idiom. A
SortedDictionarywithStringComparer.Ordinalholds the next number for each key, so the keys print in a fixed order on each platform. Dictionary.Remove(key, out value)tests for the next message and takes it out in one call.GetValueOrDefaultgives 1 as the next number for a key that has not arrived yet.
package main
import (
"fmt"
"sort"
"strings"
)
type msg struct {
key string
seq int
}
func main() {
// Messages arrive with a key and a sequence number for each key, out of order and with one copy.
arrivals := []msg{{"A", 1}, {"A", 3}, {"B", 1}, {"A", 2}, {"B", 3}, {"A", 3}, {"B", 2}, {"A", 4}}
// expected maps a key to the next sequence number to deliver.
expected := map[string]int{}
// held maps a key to the messages that wait, by sequence number.
held := map[string]map[int]string{}
for _, m := range arrivals {
next, ok := expected[m.key]
if !ok {
next = 1
}
name := fmt.Sprintf("%s%d", m.key, m.seq)
if held[m.key] == nil {
held[m.key] = map[int]string{}
}
if _, dup := held[m.key][m.seq]; dup || m.seq < next {
fmt.Printf("%s: copy, dropped\n", name)
continue
}
held[m.key][m.seq] = name
var out []string
for {
v, ok := held[m.key][next]
if !ok {
break
}
out = append(out, v)
delete(held[m.key], next)
next++
}
expected[m.key] = next
if len(out) > 0 {
fmt.Printf("%s: deliver %s\n", name, strings.Join(out, " "))
} else {
fmt.Printf("%s: hold, waiting for %s%d\n", name, m.key, next)
}
}
left := 0
for _, h := range held {
left += len(h)
}
keys := make([]string, 0, len(expected))
for k := range expected {
keys = append(keys, k)
}
sort.Strings(keys)
parts := make([]string, len(keys))
for i, k := range keys {
parts[i] = fmt.Sprintf("%s%d", k, expected[k])
}
fmt.Printf("held at the end: %d; next: %s\n", left, strings.Join(parts, ", "))
}
A1: deliver A1
A3: hold, waiting for A2
B1: deliver B1
A2: deliver A2 A3
B3: hold, waiting for B2
A3: copy, dropped
B2: deliver B2 B3
A4: deliver A4
held at the end: 0; next: A5, B4
- Verdict: idiom. A map of maps holds the early messages for each key; the two-value form
next, ok := expected[key]tells a new key from a key whose next number is stored. - The order of iteration over a Go map is not specified, so the program sorts the keys with
sort.Stringsbefore it prints the next numbers. deleteremoves each held message as the loop delivers it.
Variations and related ideas
Partition by key and scale out. Sometimes messages must be processed in parallel, but in order for each entity, such as each order id. For this case, RabbitMQ suggests the x-modulus-hash exchange, which partitions the messages across several queues, each with a single active consumer.1 Kafka partitions and SQS message groups do the same inside the broker.24
Duplicates. Order and copies are related. Kafka has an idempotent producer: the broker gives each producer an id, and it uses a sequence number that the producer sends with each message to drop copies.5 At the receiver, an Idempotent Receiver drops copies, and the resequencer in the examples drops a copy whose number it has already delivered.
Related patterns. The book relates the Resequencer to the Aggregator, Competing Consumers, the message router and the Splitter.7 A Correlation Identifier connects a reply to its request, but it does not give an order.
Pitfalls
- Redelivery. In RabbitMQ, a message that a consumer negatively acknowledges with requeue, or that is unacknowledged when a channel closes, is delivered again, and this can change the order. The broker flags a redelivered message.1 In Pub/Sub, a redelivery of a message also redelivers all later messages of its key, even the acknowledged ones.3
- The dead letter queue. In Service Bus, a message of a session can be abandoned more often than
MaxDeliveryCount, which is 10 by default. Then it goes to the dead letter queue, and the receiver continues with the later messages. If the message is moved back to the queue, it loses its order, because it gets a new enqueue time and sequence number.6 Pub/Sub forwards messages to a dead letter topic on a best-effort basis, so its redelivery rule might not hold.3 - The consumer side. RabbitMQ also says that consumers that return messages to the queue must return them in the order in which they received them. A quorum queue needs a delivery limit, and AMQP 0-9-1 consumers must not use
basic.get.1 - Priorities. In RabbitMQ, a message of higher priority can be delivered before a message of lower priority, so a priority queue does not keep the order of publication.1
- No order across keys. In Pub/Sub, messages with different ordering keys have no order between them.3 Code that needs two keys in order needs one key for both, or a step that waits for both.
- Hot keys. All messages of one key go to one consumer. In Pub/Sub, a hot key occurs when a key gets more messages each second than the subscriber can process, and a backlog builds on it.3
Cost
Order limits parallel work. One key is processed by one consumer at a time, so the throughput of a key is the speed of one consumer.34 Pub/Sub also limits the publish throughput of each ordering key to 1 MBps.3 Google says that ordered delivery decreases publish availability and increases end-to-end latency, because a failover needs coordination to keep the order.3 A resequencer holds early messages in memory until the missing ones arrive. If a message is lost, the held messages of its key wait for ever, unless the resequencer has a timeout or a limit.
History
Enterprise Integration Patterns by Gregor Hohpe and Bobby Woolf, published in 2003, puts the Resequencer in its chapter on message routing.8 The book explains that a router can send related messages on different routes, so some of them pass the processing steps sooner than others and arrive out of order.7 Kafka builds its design on totally ordered partitions: because each partition has exactly one consumer in a group, the position of the consumer is one number, the offset of the next message. Log compaction never changes the order of the messages; it only removes some.5
References
- RabbitMQ documentation (version 4.4), Queues, message ordering; when messages can be reordered; preserving message order
- Apache Kafka 4.1.0 documentation source, Introduction, main concepts and terminology (topics, partitions and event keys)
- Google Cloud, Pub/Sub documentation, Order messages, ordering keys; considerations when using message ordering
- Amazon Simple Queue Service Developer Guide, Amazon SQS FIFO queue key terms, message group ID
- Apache Kafka 4.1.0 documentation source, Design, load balancing (semantic partitioning); consumer position; message delivery semantics (idempotent producer); log compaction guarantees
- Microsoft, Azure Service Bus documentation, Message sessions, session features; maximum delivery count in sessions
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Resequencer (problem and solution under CC BY), problem and solution statements; pattern text
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Designing, Building, and Deploying Messaging Solutions, Addison-Wesley, 2003, Chapter 7, Message Routing, Resequencer
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 E0WM6P Edit this page History Report an error Markdown