Sub topic 15
Tracing, Monitoring and Testing Event Flows
This chapter assumes you know what producers, consumers and brokers are. It also assumes you know at-least-once delivery, idempotent consumers, and dead-letter queues (DLQs) from earlier chapters. Here the focus is on seeing what an event-driven system is doing, and on checking that it does what you intend.
Why event flows are hard to observe
In a request/response system, a failed call returns an error to the caller. A stack trace or a single request log usually shows the whole story. In an event-driven system, the producer publishes an event and moves on. Consumers run later, in other processes, sometimes minutes later. If one consumer fails, the producer never learns about it.
Three properties make this harder:
- No single call stack. One business action, such as placing an order, can fan out into many handlers across many services.
- Time gaps. An event can wait in a broker before anyone processes it.
- Silent failure. A consumer that stops reading produces no errors. It produces nothing at all.
Observability for events therefore rests on three tools: traces that link related work, metrics that show health over time, and logs that explain individual failures.
Correlation IDs and trace context
A correlation ID is an identifier copied from event to event so that all work caused by one original action can be found together. A trace is a structured version of the same idea. It is a tree of spans, where each span is one unit of work, such as "publish order.placed" or "handle order.placed in the inventory service".
The event id in the envelope identifies one event. It does not identify the whole flow. You need extra fields:
correlationId: the same value for every event and handler in one flow.causationId: theidof the event that directly caused this one. FollowingcausationIdlinks lets you rebuild the chain.- Trace context: for example the W3C
traceparentvalue, which tracing tools such as OpenTelemetry understand.
Put these in event metadata, separate from the business data. With a broker that supports message headers, use headers for trace context. Otherwise add a metadata object to the envelope.
{
"id": "6f1c2d9e-3b7a-4c55-9d0e-1a2b3c4d5e6f",
"type": "order.placed",
"version": 1,
"occurredAt": "2026-11-26T11:00:00Z",
"metadata": {
"correlationId": "req-7731",
"causationId": null,
"traceparent": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
},
"data": {
"orderId": "o-1",
"customerId": "c-9",
"totalCents": 4599
}
}When a consumer handles this event and publishes stock.reserved, it copies correlationId, sets causationId to 6f1c2d9e-..., and continues the trace.
The following runnable sketch shows the propagation rule using only the standard library:
import uuid
from collections import defaultdict
class EventBus:
def __init__(self):
self._handlers = defaultdict(list)
def subscribe(self, event_type, handler):
self._handlers[event_type].append(handler)
def publish(self, event):
for handler in self._handlers[event["type"]]:
handler(event)
def new_event(event_type, data, cause=None):
"""Build an event; inherit the correlation ID from the causing event."""
event_id = str(uuid.uuid4())
return {
"id": event_id,
"type": event_type,
"data": data,
"metadata": {
"correlationId": cause["metadata"]["correlationId"] if cause else event_id,
"causationId": cause["id"] if cause else None,
},
}
bus = EventBus()
log = []
def reserve_stock(event):
log.append((event["type"], event["metadata"]["correlationId"]))
bus.publish(new_event("stock.reserved", {"orderId": event["data"]["orderId"]}, cause=event))
def on_reserved(event):
log.append((event["type"], event["metadata"]["correlationId"]))
bus.subscribe("order.placed", reserve_stock)
bus.subscribe("stock.reserved", on_reserved)
bus.publish(new_event("order.placed", {"orderId": "o-1"}))
for entry in log:
print(entry) # both lines show the same correlation IDBoth log lines print the same correlation ID, so a log search for that value returns the whole flow.
What to monitor
Broker and consumer metrics tell you whether the system is healthy. The most useful ones are below.
| Metric | What it shows | Typical alert |
|---|---|---|
| Consumer lag (or queue depth) | How far a consumer is behind the newest event | Lag grows steadily for several minutes |
| Age of oldest message | How long the oldest unprocessed event has waited | Exceeds the freshness target of the business flow |
| Processing duration | Time per event in the handler | p95 or p99 rises sharply |
| Error and retry rate | Handlers failing or retrying | Sustained rise above baseline |
| DLQ depth | Events that exhausted retries | Any non-zero value, for flows that must not lose data |
| Publish failure rate | Producers unable to reach the broker | Any sustained failures |
| Outbox backlog | Unpublished rows in the outbox table | Oldest unpublished row older than a threshold |
| Duplicate rate | Events skipped by idempotency checks | Sudden jump |
Some of these deserve explanation.
Consumer lag is the main health signal. A constant small lag is normal. Lag that keeps growing means consumers are slower than producers, or have stopped. Age of the oldest message is often better than raw depth, because it maps directly to a user-visible delay such as "receipts arrive 40 minutes late".
DLQ depth should be treated as an alarm, not a statistic. Every event in a DLQ is a business fact that was not processed. Alert on arrival, and keep enough context (error message, original headers, attempt count) to diagnose it.
Outbox backlog matters because a stalled relay looks healthy from the database side. Orders are saved and nothing fails, but no events leave. Measure the age of the oldest row where published_at is null.
Duplicate rate is a useful signal in both directions. Some duplicates are normal under at-least-once delivery. A sudden spike suggests a consumer that is timing out before acknowledging, so the broker keeps redelivering.
Watch the flow, not only the parts
Per-component metrics can all look fine while a business flow is broken. Add business-level metrics, such as "orders placed in the last hour with no payment.captured event yet". These are sometimes called end-to-end or synthetic checks. A scheduled check that publishes a test event and waits for the expected result also catches silent consumer failures.
Logging
Use structured logs (JSON key-value pairs) rather than free text. Include at least eventId, eventType, correlationId, the consumer name, the attempt number, and the outcome (processed, skipped as duplicate, retried, dead-lettered). Do not log full payloads if they contain personal data. Log identifiers and look up the payload where access is controlled.
Testing event flows
Event-driven code can be tested at several levels. Each level catches different mistakes.
- Unit tests for handlers. A handler is a function from an event (and current state) to state changes and new events. Test it directly, with no broker.
- Idempotency tests. Deliver the same event twice and assert that the state is the same as after one delivery.
- Contract tests. Check that producers and consumers agree on the event schema.
- Integration tests with a real broker. Run the broker in a container and test publish, consume, retry, and DLQ behavior.
- End-to-end and flow tests. Trigger one action and assert that the eventual outcome appears.
Unit and idempotency tests
Because handlers are plain functions, the checks are short. This example tests the deposit handler from the idempotency chapter, including redelivery and out-of-order behavior for a different account:
import unittest
balances = {}
processed_ids = set()
def handle_deposit(event):
if event["event_id"] in processed_ids:
return
balances[event["account"]] = balances.get(event["account"], 0) + event["amount"]
processed_ids.add(event["event_id"])
class DepositHandlerTest(unittest.TestCase):
def setUp(self):
balances.clear()
balances["acct-1"] = 100
processed_ids.clear()
def test_applies_deposit_once(self):
handle_deposit({"event_id": "e-1", "account": "acct-1", "amount": 25})
self.assertEqual(balances["acct-1"], 125)
def test_duplicate_delivery_is_ignored(self):
event = {"event_id": "e-2", "account": "acct-1", "amount": 25}
handle_deposit(event)
handle_deposit(event)
self.assertEqual(balances["acct-1"], 125)
def test_different_events_both_apply(self):
handle_deposit({"event_id": "e-3", "account": "acct-1", "amount": 10})
handle_deposit({"event_id": "e-4", "account": "acct-1", "amount": 10})
self.assertEqual(balances["acct-1"], 120)
if __name__ == "__main__":
unittest.main()Also test failure paths. A handler that raises an exception should leave state unchanged, so that a retry can succeed. A malformed event should go to the DLQ rather than retry forever.
Contract tests
In an event-driven system, services deploy independently, so integration failures often appear only in production. A contract test captures what a consumer needs from an event (required fields and types) and verifies the producer's output against it. Tools such as Pact (with message support) or a schema registry's compatibility check automate this. At minimum, store example events in the repository and validate them against the JSON Schema in both the producer's and consumers' test suites. Also include old versions: a consumer should still pass tests with version 1 events after version 2 exists.
Integration and flow tests
Mocks do not reproduce broker behavior such as redelivery after a missed acknowledgement, partition assignment, or retry delays. Run a real broker locally or in CI (for example in a container) and test:
- A handler that fails twice and then succeeds is retried and ends up processed once.
- An event that always fails ends up in the DLQ with its error details.
- Events with the same key are handled in order.
- The relay publishes outbox rows after a restart, with no loss.
Asynchronous tests need care. Never use a fixed sleep. Poll for the expected outcome with a timeout:
import time
def wait_until(condition, timeout=5.0, interval=0.05):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if condition():
return True
time.sleep(interval)
return False
# Example usage in a flow test:
# publish_order_placed("o-1")
# assert wait_until(lambda: receipt_exists("o-1")), "receipt was not sent in time"A fixed sleep makes tests either slow (too long) or flaky (too short). Polling is fast when the system is fast and tolerant when it is slow.
Replay as a test and debugging tool
If the broker retains events (as log-based brokers do), you can replay a recorded sequence into a staging consumer to reproduce a bug. For DLQ events, fix the handler, then redrive the messages and watch the DLQ depth return to zero. Redrive is safe only if consumers are idempotent, which is why idempotency tests come first.
Common errors
- Alerting only on errors. A stopped consumer has no errors. Alert on lag and age of the oldest message as well.
- Ignoring the DLQ. Events pile up unseen. Alert on depth and assign someone to triage.
- Dropping trace context in retries or batch jobs.
- Testing only the happy path. Duplicates, failures, and old schema versions are where production incidents come from.
- Fixed sleeps in tests.
- High-cardinality metric labels. Using
eventIdororderIdas a metric label overloads the metrics system. Put identifiers in logs and traces, and keep metric labels to low-cardinality values such as event type and consumer name.
Exercise
Consumer lag for the receipts service has stayed flat at a small value for a week, yet customers report receipts arriving 30 minutes late since this morning. Name two metrics or checks that would reveal the problem and explain why lag alone missed it.
Show answer
Age of the oldest message, and a business-level check such as "orders with no receipt after N minutes". Lag counts how many events are waiting, not how long they have waited. If events arrive at a low rate, or a stuck handler is processing one slow event, the count can stay small while the oldest event keeps aging. Processing duration (p95/p99) would also show a slow handler, and the outbox backlog age would show whether the delay happens before the broker.
Exercise
A test publishes an event, calls time.sleep(2), and then checks the database. It passes locally and fails about one run in ten in CI. What is wrong, and how do you fix it?
Show answer
The test assumes the consumer always finishes within two seconds. CI is slower and variable, so sometimes it does not. Replace the sleep with a polling helper such as wait_until(condition, timeout) that checks repeatedly and fails only after a generous timeout. This is both faster in the normal case and more reliable in the slow case.