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
- Past tense. Events describe what already happened — not commands ("do something").
- Immutable. A frozen record. Once produced, it cannot change.
- Self-describing. Carries enough data for subscribers to react without re-fetching state.
- Belongs to the domain. Named in the ubiquitous language. Not "RecordCreated" or "RowUpdated".
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:
frozen=True— immutability is non-negotiable for events.- Carry IDs of involved aggregates plus the data subscribers most likely need. Don't dump the whole aggregate.
- 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
- Command events.
SendEmail,UpdateInventory. These are commands, not facts. Events say "X happened"; commands say "do X". - Mutable events. Adding fields or correcting one after the fact. If something changed, publish a new event.
- Bare events.
OrderPlaced(order_id=x)with nothing else — every subscriber has to re-fetch. Carry the payload. - Fat events. Dumping the whole aggregate state. Subscribers couple to the publisher's internals.
- Tense confusion.
PlaceOrder(sounds like a command). Use past tense:OrderPlaced.
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.