Domain Event

Domain Event

A domain event records that something happened in the domain. It is an immutable, past-tense fact — OrderPlaced, BookCheckedOut, PaymentReceived. Subscribers react to it; the publisher doesn't know who's listening.

Defining trait

Python shape

from dataclasses import dataclass, field
from datetime import datetime, timezone
from uuid import UUID

@dataclass(frozen=True, kw_only=True)
class OrderPlaced:
    order_id: UUID
    customer_id: UUID
    total: Money
    placed_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))

Three rules:

  1. frozen=True — immutability is non-negotiable for events.
  2. Carry IDs of involved aggregates plus the data subscribers most likely need. Don't dump the whole aggregate.
  3. Timestamp the moment it occurred, not the moment it was published.

Where they come from

Aggregates produce events as part of their state changes:

@dataclass
class Order:
    id: UUID
    customer_id: UUID
    items: list[OrderItem]
    placed_at: datetime | None = None
    _events: list = field(default_factory=list, repr=False)

    def place(self) -> None:
        if self.placed_at is not None:
            raise OrderAlreadyPlaced()
        self.placed_at = datetime.now(timezone.utc)
        self._events.append(OrderPlaced(
            order_id=self.id,
            customer_id=self.customer_id,
            total=self.total(),
            placed_at=self.placed_at,
        ))

    def pull_events(self) -> list:
        events, self._events = self._events, []
        return events

The use case calls order.place(), then publishes the pulled events after saving.

Anti-patterns

Domain Event vs Integration Event

Domain Event Integration Event
Scope Inside one bounded context Across bounded contexts
Transport In-process bus Message broker
Naming OrderPlaced order.placed.v1
Coupling Tied to model Stable contract (versioned)
Failure Same-tx or compensating Retries, dead-letter, idempotency

See the EDA overview for the full split.

Why bother

The whole point: subscribers can react without the publisher knowing. New requirement ("notify on order placed") = new subscriber. The aggregate that places the order doesn't change. Open-Closed at the architecture level.