Wake an agent once per burst of domain events: a quiet window, a maximum wait and a version check at the point of action. A worked replay turns 12 wake-ups into 1 or 2.
One customer, twelve events, twelve model calls
Belgavi's Book Store publishes domain events for its orders: OrderPlaced, ItemBackordered, ShipmentDelayed, AddressChanged, and so on. Hansini connected a help-desk agent to that stream so that it drafts a proactive message to the customer when something goes wrong with an order. The first week was fine. Then a warehouse re-sync published twelve events for one order within ninety seconds: three backorder changes, two shipment updates, an address correction and several status flips. The agent woke up twelve times, read twelve slightly different states of the same order, and drafted four messages, two of which contradicted each other.
The fix is not a smarter prompt. It is an old piece of event-driven plumbing placed between the stream and the agent: a per-entity coalescer that turns a burst of events into one wake-up, hands the agent the latest state, and makes sure the state has not moved again before anything is sent. This guide covers the design, the two timing parameters, the version check, migration steps and when per-event handling is still correct.
What the agent should react to
A domain event says that something changed. For a deterministic consumer, such as a projection that updates a read model, handling every event in order is correct and cheap. For an agent, every event is a model call with latency, cost and a non-deterministic output, and what the agent needs is not each change but the state after the changes have settled.
Martin Fowler's article on event-driven patterns distinguishes event notification, where the event says "this changed, look it up", from event-carried state transfer, where the event carries the new data. Coalescing works best with notification semantics: the coalescer only needs to know which entity changed and the latest version number; the agent reads the current state itself when it wakes.
The coalescer
The coalescer keeps one small record per entity, keyed by order id:
| Field | Meaning |
|---|---|
first_seen | arrival time of the first event in the current burst |
last_seen | arrival time of the most recent event |
latest_version | highest entity version seen in the burst |
count | events folded into this burst |
kinds | set of event types seen, for the agent's context |
Two parameters decide when it wakes the agent:
- Quiet window. Wake when no new event for the entity has arrived for this long. This is the debounce operator familiar from reactive programming libraries: ReactiveX documents
debounceas emitting an item only if a particular timespan has passed without another emission. - Maximum wait. Wake no later than this long after
first_seen, even if events keep arriving. Without a ceiling, an entity that keeps changing would never wake the agent at all.
The wake-up is a task carrying the order id, latest_version, count and kinds. The record is then cleared. Events that arrive while the agent is working start a new burst.
from dataclasses import dataclass, field
@dataclass
class Burst:
first_seen: float
last_seen: float
latest_version: int
count: int = 1
kinds: set = field(default_factory=set)
def on_event(bursts: dict, entity: str, version: int, kind: str, now: float) -> None:
b = bursts.get(entity)
if b is None:
bursts[entity] = Burst(now, now, version, 1, {kind})
else:
b.last_seen, b.count = now, b.count + 1
b.latest_version = max(b.latest_version, version)
b.kinds.add(kind)
def due(bursts: dict, now: float, quiet_s: float, max_wait_s: float) -> list:
ready = [e for e, b in bursts.items()
if now - b.last_seen >= quiet_s or now - b.first_seen >= max_wait_s]
return [(e, bursts.pop(e)) for e in sorted(ready)]The coalescer is deterministic and small enough to test exhaustively with a synthetic clock, which the companion example does.
The version check that closes the loop
Coalescing reduces how often the agent wakes. It does not stop the state from changing while the agent works, which can take tens of seconds. The second half of the design is a version check at the point of action:
- The wake-up task carries
latest_version, say 14. - The agent's read tool returns the order with its current version. If that is already above 14, the agent works from the newer state, and the version it records is the one it read.
- The send tool takes the version the agent based its message on, and refuses if the order's current version is higher. The refusal returns the new version; the task is requeued as a new burst.
This turns a stale message into a cheap, deterministic refusal. Combined with coalescing, it means the agent drafts at most one message per settled state, and never sends a message about a state that no longer exists.
Choosing the two timings
The quiet window should be longer than the typical gap between events inside one burst, and shorter than the delay a customer would notice. The maximum wait bounds the worst-case delay. With the store's re-sync, events for one order arrived 2 to 15 seconds apart over 80 seconds. The companion example replays that burst with a synthetic clock:
| Quiet window | Maximum wait | Agent wake-ups for the 12 events | Delay of first wake-up after the first event |
|---|---|---|---|
| none (per event) | none | 12 | 0 s |
| 10 s | 120 s | 5 | 26 s |
| 20 s | 120 s | 1 | 100 s |
| 20 s | 60 s | 2 | 60 s |
Twelve wake-ups become five, two or one, each carrying the latest version and the count of events it folded. The price is delay: with a 20 s quiet window the only wake-up came 100 s after the first event, because the burst never went quiet for 20 s until it ended, and a 60 s maximum wait cut that to 60 s at the cost of a second wake-up. The right values depend on your stream; measure the gaps between events for one entity before choosing, rather than guessing.
What stays deterministic, and what the agent gets
Everything above the agent stays deterministic: ordering per entity, the burst record, the timing rules, the version check and the requeue. The agent gets a clear input contract: an entity id, the version to start from, how many events were folded and of which kinds. That last field matters. "Twelve events including an address change" is useful context for writing a message; twelve separate wake-ups were not.
Some events should bypass the coalescer. An OrderCancelled or a payment failure may need an immediate response; route those event types straight to a wake-up, or give them a quiet window of zero. Keep that list explicit and in configuration, not in the prompt.
Where to put the state
In a single consumer process, a dictionary and a timer are enough for a demonstration. In production the burst record has to survive restarts and work with several consumer instances:
- partition the stream by entity id, so one consumer owns each entity and order is preserved per entity;
- store burst records in the same database as the consumer's offsets, or use a durable timer from your workflow engine, so a crash does not lose a pending wake-up;
- commit the stream offset only after the burst record is saved; on restart, re-reading a few events only increases
count.
Migrating an existing consumer
- Measure: for each entity type, the distribution of events per entity per minute and the gaps inside bursts.
- Insert the coalescer in front of the agent and keep per-event delivery for deterministic consumers on the same stream. Nothing else in the system should change.
- Add the version field to the agent's read tool and the version precondition to every tool that changes something or contacts a customer.
- Start with a short quiet window and a generous maximum wait, compare wake-ups and refusals for a week, then adjust.
- Keep the bypass list for urgent event types under review.
When this is unnecessary
If events for one entity rarely arrive within seconds of each other, coalescing only adds delay. If every event must be acknowledged individually, for example an audit consumer, per-event handling is the requirement. And if the reaction to a change is deterministic and cheap, such as updating a search index, there is nothing to save by batching; the agent is the expensive consumer, so it is the one that needs the coalescer.
Limits
The timing table comes from the companion example's synthetic burst and clock, not from a production stream. The design assumes per-entity ordering in the event stream and an entity version that increases with every change; streams without either need a sequence number added first.