Skip to content

Message Tracing in Event-Driven Systems

In event-driven architectures, a single user action often triggers a cascade of commands and events across multiple aggregates and services. Without tracing, debugging a production issue means manually piecing together log entries, database records, and event store messages. Two simple metadata fields (correlation_id and causation_id) solve this by threading through every message in the chain.

The Problem

Consider an e-commerce checkout: placing an order triggers payment processing, inventory reservation, and shipping notification. If the shipping notification fails, you need to answer:

  1. Which user request caused this? (correlation)
  2. What was the immediate trigger? (causation)
  3. What other effects did that request produce? (chain traversal)

Without explicit tracing, the only clue is origin_stream, a single string recording where a command came from. That tells you the source aggregate but not the full chain.

The Pattern

Attach two identifiers to every command and event:

  • correlation_id: Constant across the entire causal chain. Generated at the earliest entry point (often the API gateway or frontend) and carried through every subsequent message. All messages belonging to the same business operation share one correlation_id.

  • causation_id: Points to the immediate parent. When a command handler raises an event, the event's causation_id is the command's message ID. When an event handler dispatches a new command during asynchronous processing, the command's causation_id is the event's message ID.

Together, the two identifiers form a causation tree:

PlaceOrder [corr=X, cause=None]              <-- root command
  +-- OrderPlaced [corr=X, cause=PlaceOrder.id]
        +-- ReserveInventory [corr=X, cause=OrderPlaced.id]
        |     +-- InventoryReserved [corr=X, cause=ReserveInventory.id]
        +-- NotifyCustomer [corr=X, cause=OrderPlaced.id]
              +-- NotificationSent [corr=X, cause=NotifyCustomer.id]

Design Decisions

Where to Generate correlation_id

The correlation_id should be generated as early as possible, ideally by the caller (API gateway, frontend, CLI). This lets you trace a request from the moment it enters the system.

The examples on this page use this ordering domain. Commands are processed synchronously, so domain.process() returns the command handler's result:

from protean import Domain, apply, current_domain, handle
from protean.fields import Dict, Identifier, List, String

domain = Domain(name="MyApp", config={"command_processing": "sync"})


@domain.event(part_of="Order")
class OrderPlaced:
    order_id: Identifier(required=True)
    customer_id: Identifier(required=True)
    items: List(content_type=Dict)


@domain.event(part_of="Order")
class InventoryReserved:
    order_id: Identifier(required=True)


@domain.event(part_of="Order")
class PaymentConfirmed:
    order_id: Identifier(required=True)


@domain.aggregate(event_sourced=True)
class Order:
    customer_id: Identifier()
    items: List(content_type=Dict)
    status: String(default="NEW")

    @apply
    def when_placed(self, event: OrderPlaced) -> None:
        self.id = event.order_id
        self.customer_id = event.customer_id
        self.items = event.items
        self.status = "PLACED"

    @apply
    def when_reserved(self, event: InventoryReserved) -> None:
        self.status = "RESERVED"

    @apply
    def when_paid(self, event: PaymentConfirmed) -> None:
        self.status = "PAID"


@domain.command(part_of=Order)
class PlaceOrder:
    customer_id: Identifier(required=True)
    items: List(content_type=Dict)


@domain.command(part_of=Order)
class ReserveInventory:
    order_id: Identifier(required=True)


@domain.command(part_of=Order)
class ConfirmPayment:
    order_id: Identifier(required=True)


@domain.command_handler(part_of=Order)
class OrderCommandHandler:
    @handle(PlaceOrder)
    def place(self, command: PlaceOrder):
        order = Order()
        order.raise_(
            OrderPlaced(
                order_id=order.id,
                customer_id=command.customer_id,
                items=command.items,
            )
        )
        current_domain.repository_for(Order).add(order)
        return order.id

    @handle(ReserveInventory)
    def reserve(self, command: ReserveInventory):
        repo = current_domain.repository_for(Order)
        order = repo.get(command.order_id)
        order.raise_(InventoryReserved(order_id=order.id))
        repo.add(order)

    @handle(ConfirmPayment)
    def confirm_payment(self, command: ConfirmPayment):
        repo = current_domain.repository_for(Order)
        order = repo.get(command.order_id)
        order.raise_(PaymentConfirmed(order_id=order.id))
        repo.add(order)


@domain.event_handler(part_of=Order)
class InventoryEventHandler:
    @handle(OrderPlaced)
    def reserve_stock(self, event: OrderPlaced) -> None:
        current_domain.process(ReserveInventory(order_id=event.order_id))

A FastAPI endpoint reads the caller's ID from the X-Correlation-ID header:

from typing import Annotated
from uuid import uuid4

from fastapi import APIRouter, Header
from pydantic import BaseModel

router = APIRouter()


class PlaceOrderRequest(BaseModel):
    customer_id: str
    items: list[dict]


@router.post("/orders", status_code=201)
def place_order(
    body: PlaceOrderRequest,
    x_correlation_id: Annotated[str | None, Header()] = None,
):
    # Fallback: generate at the API boundary
    correlation_id = x_correlation_id or uuid4().hex
    order_id = domain.process(
        PlaceOrder(**body.model_dump()),
        correlation_id=correlation_id,
    )
    return {"order_id": order_id, "correlation_id": correlation_id}

If no external correlation_id is provided, Protean generates one automatically when domain.process() is called. This means every message chain always has a correlation_id. You never have to check for None.

Format: Flexible Strings, Not UUIDs

The correlation_id is a flexible string, not strictly a UUID. It can be:

  • A UUID4 hex (a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6), Protean's default
  • A request ID from an API gateway (req-abc-123-def)
  • A trace ID from an external tracing system (00-4bf92f3577b34da6a3ce929d0e0e4736-...)

This flexibility lets you integrate with existing infrastructure without reformatting IDs.

The causation_id is always a Protean message ID (e.g., myapp::order-abc123-0.1), which is intentionally human-readable for debugging.

Separation from W3C TraceParent

Protean supports W3C TraceParent in MessageHeaders.traceparent for integration with distributed tracing tools (Jaeger, Zipkin, Datadog). The domain-level correlation_id and causation_id serve a different purpose:

Concern Domain tracing Distributed tracing
Location DomainMeta.correlation_id / causation_id MessageHeaders.traceparent
Purpose Business operation tracking Infrastructure span tracking
Format Flexible strings W3C 32-hex / 16-hex
Required Always present Optional integration

Both layers carry the correlation_id. It identifies the same operation. But you cannot store causation_id in TraceParent.parent_id, because Protean's message IDs are human-readable strings and TraceParent.parent_id takes a 16-hex-char span ID.

Protean's Implementation

Protean implements this pattern automatically. No opt-in required.

Automatic Propagation

Trace context flows through all message construction paths via g.message_in_context:

  1. domain.process(command): Generates or accepts correlation_id, sets causation_id = None (root command)
  2. Command handler raises events: Events inherit correlation_id from the command, causation_id = command's headers.id
  3. Event handler dispatches commands: New commands inherit correlation_id from the event, causation_id = event's headers.id

The correlation_id carries through in both sync and async processing modes. Step 3's causation_id holds only in async mode. In sync mode the event handler runs inside the original command's handler, so the new command records that original command as its cause.

Outbox Denormalization

The outbox stores correlation_id and causation_id as indexed columns alongside the full message metadata. This enables efficient queries:

# fragment
# Find all messages from a business operation
outbox_repo.find_by_correlation_id("a1b2c3d4...")

# Find all messages caused by a specific parent
outbox_repo.find_by_causation_id("myapp::order-abc123-0.1")

Causation Chain API

The event store provides methods to traverse causation chains programmatically:

def explain(event_message, command_message, correlation_id: str):
    store = domain.event_store

    # Walk UP from a message to the root command
    chain = store.trace_causation(event_message)
    # Returns [root_command, ..., target_message]

    # Walk DOWN from a command to find all its effects
    effects = store.trace_effects(command_message)
    # Returns downstream events/commands in chronological order

    # Build the full tree for a correlation ID
    root = store.build_causation_tree(correlation_id)
    # Returns a CausationNode with .children recursively populated

    return chain, effects, root

These methods answer the three debugging questions directly:

  1. "Which user request caused this?": trace_causation() walks up to the root
  2. "What was the immediate trigger?": Check causation_id on the message
  3. "What other effects did that request produce?": trace_effects() walks down

CLI Inspection

The protean events CLI supports tracing with both tree and flat views:

# Show trace IDs alongside events
protean events read "myapp::order-abc123" --trace

# Follow a full causal chain (tree view, default)
protean events trace "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6"

# Flat table view for chronological listing
protean events trace "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6" --flat

The tree view reconstructs parent-child relationships from causation_id links:

CMD App.PlaceOrder.v1 (myapp::order:command-abc123-0) @ 2026-02-22 10:30:00
├── EVT App.OrderPlaced.v1 (myapp::order-abc123-0) @ 2026-02-22 10:30:00
│   └── CMD App.ReserveInventory.v1 (myapp::inventory:command-inv456-0) @ 2026-02-22 10:30:01
│       └── EVT App.InventoryReserved.v1 (myapp::inventory-inv456-0) @ 2026-02-22 10:30:02

When to Use External Correlation IDs

Always prefer external IDs when available. If your API gateway or frontend generates request IDs, pass them through as correlation_id. This gives you end-to-end traceability from the user's browser to the last event handler.

Generate IDs at the Protean boundary only when:

  • The entry point is a scheduled job or cron task
  • The message originates from an external system that doesn't provide trace IDs
  • You're in development/testing and don't have an API gateway

Multi-Service Tracing

When one Protean service consumes events from another (via subscribers), the correlation_id from the source event should be forwarded. A subscriber receives the published message as a dict:

@domain.subscriber(stream="payments")
class PaymentSubscriber:
    def __call__(self, message: dict) -> None:
        # A message from a system outside Protean may have no domain metadata,
        # a null one, or a blank correlation ID
        metadata = message.get("metadata") or {}
        domain_metadata = metadata.get("domain") or {}
        correlation_id = domain_metadata.get("correlation_id") or None

        current_domain.process(
            ConfirmPayment(order_id=message["data"]["order_id"]),
            correlation_id=correlation_id,
        )

With the forwarded correlation_id, you can follow one causal chain across service boundaries. When the Engine delivers a broker message, it already puts the message's correlation_id in context before it calls the subscriber. So a command the subscriber processes picks up that correlation_id. Passing it explicitly keeps the link when the subscriber runs some other way, such as a direct call in a test or a script. The Engine looks for the ID at metadata.domain.correlation_id, then metadata.correlation_id, then a top-level correlation_id. A message with none of these starts a new chain with a generated ID.

Testing Trace Propagation

Protean's test DSL runs a command through given(...).process() and records the events it raised, with their trace metadata:

from protean.testing import given


def place_order_with_generated_ids():
    result = given(Order).process(
        PlaceOrder(customer_id="cust-1", items=[{"sku": "BOOK-1", "qty": 2}])
    )
    assert result.events.types == [OrderPlaced]

    # Verify correlation_id was generated
    corr_id = result.events[0]._metadata.domain.correlation_id
    assert corr_id is not None
    assert len(corr_id) == 32  # UUID4 hex

    # Verify causation chain
    assert result.events[0]._metadata.domain.causation_id is not None
    return result

For multi-step chains, pass the correlation ID to the next process() call explicitly:

def reserve_in_the_same_operation(result):
    corr_id = result.events[0]._metadata.domain.correlation_id
    first_cause = result.events[0]._metadata.domain.causation_id

    result2 = result.process(
        ReserveInventory(order_id=result.aggregate.id),
        correlation_id=corr_id,
    )

    # Same correlation_id, different causation_id
    assert result2.events[0]._metadata.domain.correlation_id == corr_id
    assert result2.events[0]._metadata.domain.causation_id != first_cause
    return result2

Key Takeaways

  • correlation_id groups all messages from one business operation. Generate early, propagate everywhere.
  • causation_id links each message to its direct parent, forming a tree.
  • Protean propagates both IDs automatically. You only need to supply an external correlation_id at the entry point if you have one.
  • Use trace_causation(), trace_effects(), and build_causation_tree() to traverse chains programmatically.
  • Use protean events trace to follow a full chain in the event store.
  • Prefer external (caller-provided) correlation IDs for end-to-end traceability across services.

Related reading

Complete guide: Correlation and Causation IDs: End-to-end guide covering HTTP headers, OTEL spans, Observatory traces, structured logging, and cross-service propagation.

Guide: Message Tracing: How-to guide with code examples for setting up tracing.

Reference: protean events trace: CLI command for following causal chains.

Internals: Causation Chain Traversal: Algorithm details for trace_causation, trace_effects, and build_causation_tree.

Related patterns: