Sub topic 15
Tracing, Monitoring and Testing Event Flows
This chapter assumes you know what producers, consumers and brokers are. It also assumes you have met at-least-once delivery, idempotent consumers and dead-letter queues from earlier chapters. Here you learn how to see what an event-driven system is doing, and how to test it.
Why event flows are hard to see
In a request/response system, one call returns one answer, and a stack trace shows the path. In an event-driven system, a producer publishes and moves on. Consumers act later, in other processes. A single business action, such as placing an order, can fan out across many services. No one component sees the whole path.
Failures also look different. A consumer that stops working does not cause an error for the producer. The symptom is usually something missing: no receipt email, no stock reservation.
Tracing across the broker
Distributed tracing links the work done for one original action. Two identifiers do most of the job:
- A correlation ID is an ID shared by every event and log line that belongs to one business flow.
- A trace context is the standard set of headers (for example W3C
traceparent) that tracing tools use to build a tree of spans.
The producer must put these in the message headers or envelope. Each consumer must read them and pass them on to any event it publishes in turn.
import uuid
def publish_with_context(bus_publish, event_type, data, incoming=None):
correlation_id = incoming["correlationId"] if incoming else str(uuid.uuid4())
event = {
"id": str(uuid.uuid4()),
"type": event_type,
"correlationId": correlation_id,
"causationId": incoming["id"] if incoming else None,
"data": data,
}
bus_publish(event)
return event
first = publish_with_context(print, "order.placed", {"orderId": "o-1"})
publish_with_context(print, "stock.reserved", {"orderId": "o-1"}, incoming=first)The causationId records which event directly caused this one. Together the two IDs let you rebuild the chain.
What to monitor
Monitor the broker and the consumers. Host CPU is a poor guide.
| Signal | What it tells you |
|---|---|
| Consumer lag | How far a consumer is behind the newest event. Rising lag means it cannot keep up or is stuck. |
| Queue depth | Messages waiting in a queue. |
| Processing time | How long a handler takes, including the 95th and 99th percentiles. |
| Error and retry rate | How often handlers fail and messages are redelivered. |
| Dead-letter queue size | Messages that exhausted retries. Alert on any growth. |
| End-to-end latency | Time from `occurredAt` to the final effect. |
Testing event flows
Test at several levels, from cheap to costly.
- Handler unit tests. Call the handler with an event and check the result. No broker is needed.
- Idempotency tests. Deliver the same event twice and check that the state changes once.
- Out-of-order tests. Deliver events in a different order than expected, where your design allows it.
- Contract tests. Check that the producer's events match the schema each consumer relies on. This catches breaking schema changes before release.
- Integration tests. Run a real broker, often in a container, and check the whole flow.
balances = {"acct-1": 100}
processed_ids = set()
def handle_deposit(event):
if event["event_id"] in processed_ids:
return
balances[event["account"]] += event["amount"]
processed_ids.add(event["event_id"])
def test_duplicate_delivery_applies_once():
event = {"event_id": "e-42", "account": "acct-1", "amount": 25}
handle_deposit(event)
handle_deposit(event)
assert balances["acct-1"] == 125
test_duplicate_delivery_applies_once()
print("ok")Asynchronous tests need care. Do not use a fixed sleep. Poll for the expected result until a timeout, so the test is fast when the system is fast and still passes when it is slow.
A flow as seen by tracing
Common mistakes
- Dropping the correlation ID when a consumer publishes a new event.
- Alerting on errors only, and never on lag or silence.
- Replaying messages from the dead-letter queue into tests or production without checking for idempotency.
- Testing only the happy path with a single delivery.
Exercise
A consumer's process is running and logs no errors, yet customers report missing receipts. Which metric do you check first, and why?
Show answer
Consumer lag (and queue depth). A stuck or disconnected consumer logs nothing, but the backlog of unprocessed events grows. Then use the correlation ID of one affected order to find where its chain of events stops.
Exercise
Why should an integration test poll for a result instead of using a fixed sleep?
Show answer
Processing is asynchronous, so its duration varies. A fixed sleep is either too short, which makes the test flaky, or too long, which makes it slow. Polling with a timeout passes as soon as the result appears and fails only if the timeout is reached.