Parallel steps finish in the wrong order
An agent at Belgavi's Book Store handles a return case, CASE-4107. It plans four steps: confirm the order, check the return window, calculate the refund and write the customer reply. The planner numbers the steps 1 to 4 and dispatches the lookups in parallel because none of them depends on the others. The results land on a queue in the order the workers finish, not in the order the plan was written. Step 3 often arrives before step 2 because the refund calculator answers faster than the return-window service.
Most consumers of those results care about order. A case timeline shown to Geetha on the help desk should read in plan order. A ledger projection must apply a refund only after the eligibility check it depends on. An audit export must reproduce the sequence a reviewer approved. When results are applied as they arrive, each of those consumers sees a history that never happened.
The Enterprise Integration Patterns catalogue names the component that fixes this: a Resequencer, a stateful filter that collects out-of-sequence messages and publishes them in a defined order. The pattern is decades older than language-model agents. What changes with agents is how often the sequence has holes. A model may decide to skip a step, a tool call may time out with an unknown outcome, and a retried step may report twice. A resequencer that only sorts will wait forever for a step that was never going to arrive.
The mechanism in four rules
A resequencer needs a sequence number assigned by the producer, never inferred by the consumer. The planner or orchestrator stamps each step with a case identifier and a step number before dispatch. The resequencer then follows four rules for each case:
- Keep
next, the step number it expects to release. - When a message with
nextarrives, release it and every buffered successor that is now contiguous. - When a message with a higher number arrives, buffer it and remember when the gap opened.
- When the gap has stayed open for the gap timeout, or the buffer exceeds its capacity, declare the missing numbers lost, move
nextto the lowest buffered number and release.
A message that arrives with a number lower than next is late. Either it was already released, so it is a duplicate, or its gap was given up, so it arrives after the consumer was told it would never come. The resequencer must choose a policy for late messages explicitly. Apache Camel's stream resequencer exposes the same decision: a gap-detection algorithm with a timeout, a capacity limit whose default is 1,000 messages, and an option to reject old messages instead of delivering them out of order.
A worked timeline
The table follows CASE-4107 with eight numbered steps arriving one per tick. Step 3 arrives at tick 6. The buffer capacity is 5 and the gap timeout is 4 ticks.
| Tick | Arrives | Buffer after arrival | Released | Next expected |
|---|---|---|---|---|
| 1 | 1 | empty | 1 | 2 |
| 2 | 2 | empty | 2 | 3 |
| 3 | 4 | 4 | none | 3 |
| 4 | 5 | 4, 5 | none | 3 |
| 5 | 6 | 4, 5, 6 | none | 3 |
| 6 | 3 | empty | 3, 4, 5, 6 | 7 |
| 7 | 7 | empty | 7 | 8 |
| 8 | 8 | empty | 8 | 9 |
All eight steps leave in order. Step 4 waited three ticks, from tick 3 to tick 6. Now shorten the gap timeout to 2. At tick 5 the gap opened at tick 3 has been open for two ticks, so the resequencer declares step 3 lost and releases 4, 5 and 6. When step 3 arrives at tick 6, it is late. With a reject policy it goes to a late-message channel; with a deliver policy it reaches the consumer after step 6. A capacity of 2 has the same effect one way: at tick 5 the buffer holds three messages, so capacity forces the skip.
If step 3 never arrives, timeout and capacity are the only reasons the case ever moves. With timeout 4 and capacity 5, steps 4 to 8 are released at tick 7, step 3 is recorded as lost, and the consumer knows that the gap was an explicit decision rather than an accident.
A small implementation
The core state per case is the next number, a heap of buffered messages and the tick at which each was buffered. The code below is the deterministic part. It has no model in it.
import heapq
class Resequencer:
def __init__(self, capacity, gap_timeout, late_policy="reject"):
self.capacity, self.gap_timeout, self.late_policy = capacity, gap_timeout, late_policy
self.next, self.heap, self.delivered = 1, [], set()
def offer(self, seq, payload, tick):
out = []
if seq < self.next:
kind = "duplicate" if seq in self.delivered else "late"
return [(kind if self.late_policy == "reject" or kind == "duplicate" else "out_of_order", seq, payload)]
heapq.heappush(self.heap, (seq, tick, payload))
return self._release(out) + self.expire(tick)
def expire(self, tick):
out = []
while self.heap and (len(self.heap) > self.capacity or tick - min(t for _, t, _ in self.heap) >= self.gap_timeout):
lowest = self.heap[0][0]
out += [("lost", s, None) for s in range(self.next, lowest)]
self.next = lowest
self._release(out)
return out
def _release(self, out):
while self.heap and self.heap[0][0] == self.next:
seq, _, payload = heapq.heappop(self.heap)
out.append(("deliver", seq, payload)); self.delivered.add(seq); self.next += 1
return outThe caller must also invoke expire on a timer when nothing arrives; otherwise a case whose last message is missing never times out. The companion example drives both arrival and timer ticks from synthetic fixtures and asserts every row of the timeline above.
What stays deterministic
The model may decide which steps to run, but it must not decide ordering at the consumer. The deterministic parts are the sequence assignment at dispatch, the buffer, the timeout clock, the late-message policy and the record of which numbers were declared lost. If the planner later skips a step, it should emit an explicit skip message carrying that number. That turns a slow timeout into an immediate release, and it gives the audit trail a reason instead of a gap.
Keep the sequence scope narrow. A resequencer orders messages within one case, one conversation or one aggregate, not across the whole queue. Global ordering forces one slow case to hold every other case behind it. The key is usually the same key the queue uses for partitioning, so the resequencer state for a case lives on one consumer.
Migrating an existing consumer
A team that already applies results as they arrive can adopt the pattern in stages:
- Add a producer-assigned step number and a case key to every result message. Reject messages without them at the consumer boundary.
- Measure the arrival disorder first: log, per case, the largest distance between a message's number and the next expected number. That distribution sets a realistic buffer capacity.
- Measure gap durations: how long a missing number stays missing before it arrives. Choose the gap timeout from that distribution and from how long the consumer can tolerate stale state.
- Introduce the resequencer in shadow, computing the release order without applying it, and compare with today's arrival order.
- Switch the consumer to the resequenced stream, route late messages to their own channel, and alert when lost-number counts rise.
The resequencer state must survive a consumer restart, or a restart releases nothing until new messages arrive and the buffered ones are lost. Store next and the buffer with the consumer offset, or rebuild them by replaying the case from the log.
Failure modes
A missing timer. Expiry checked only on arrival means the last gap in a case never expires. Drive expiry from a clock as well.
Buffer memory. A slow dependency that holds many cases open multiplies buffer size by case count. Capacity per case limits one case; a global limit with shedding protects the process.
Late messages applied silently. Delivering a late refund result after the reply step can produce a reply that contradicts the ledger. Prefer rejecting late messages to a review channel unless the consumer is commutative.
Duplicates mistaken for late data. A retried step reports the same number twice. Track released numbers so the second copy is dropped as a duplicate instead of being treated as new.
Sequence assigned at the consumer. Numbering by arrival makes the buffer useless. The producer that knows the plan must stamp the number.
When a resequencer is unnecessary
If the consumer's operations commute, order does not matter. Counting completed steps, collecting independent search results or summing token usage can be applied in any order. If each result carries the full state it depends on, as an event-carried state transfer, a consumer can apply the newest version per key and ignore older ones. If the steps truly depend on each other, run them sequentially instead of in parallel; a resequencer cannot repair a refund calculated before the eligibility check it needed. And if the case has only one producer and one ordered partition, the transport already preserves order.
Verification checklist
- Property test: for any permutation of 1..n with no losses and a timeout longer than the largest gap, the output is 1..n.
- Boundary tests at timeout minus one, timeout and timeout plus one, and at capacity and capacity plus one.
- Restart test: stop the consumer with a non-empty buffer, restart it and confirm the same release order.
- Late and duplicate tests with both policies, checking where each message goes.
- A dashboard of lost numbers, late messages and buffer occupancy per case key.
The interactive lab replays these timelines with adjustable capacity, timeout and late policy, and shows each decision in a trace.
Interactive experiment
Resequencer: gaps, buffer limits and release order. Adjustable synthetic fixtures, decision traces, reset and JSON export.