/design-patterns:domain-eventsfrom design-patterns
Use when aggregates need to stay loosely coupled, side effects (emails, audit logs, projections) are tangled into domain operations, or one aggregate directly calls methods on another. Apply when something significant happens in the domain that other parts of the system need to react to without being tightly coupled. Covers Domain Events, publishing patterns, synchronous vs asynchronous handling, idempotency, and eventual consistency trade-offs.
Ships in design-patterns. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Sources: Eric Evans — Domain-Driven Design (2003); Vaughn Vernon — Implementing DDD (2013)
A Domain Event represents something that happened in the domain that domain experts care about. It is a fact — immutable, past tense, cannot be rejected. Other parts of the system react to it; they do not modify it.
Events vs Commands:
| Event | Command | |
|---|---|---|
| Tense | Past — OrderSubmitted | Imperative — SubmitOrder |
| Intent | Announces a fact | Requests an action |
| Can be rejected? | No — already happened | Yes |
| Consumers | Many (broadcast) | One (targeted) |
Events are value objects — immutable, no identity, equality by value. They carry exactly what happened and enough data for consumers to react without querying back.
@dataclass(frozen=True)
class OrderSubmitted:
order_id: OrderId
customer_id: CustomerId
total: Money
item_count: int
submitted_at: datetime
# Enrich at creation time — consumers should not need to query back
Naming rules:
OrderSubmitted, PaymentFailed, SubscriptionRenewedOrderUpdated, RecordSaved, DataChanged — too generic to be meaningfulInclude enough data: a consumer should be able to react using only what is in the event. If consumers routinely query back for more information, the event is under-specified.
Aggregates record events internally. The application service publishes them after saving — never before.
class Order:
def __init__(self):
self._events: list[DomainEvent] = []
def submit(self) -> None:
if not self._items:
raise EmptyOrderError()
self._status = OrderStatus.SUBMITTED
self._events.append(OrderSubmitted(
order_id=self.id,
customer_id=self._customer_id,
total=self._total,
item_count=len(self._items),
submitted_at=datetime.utcnow()
))
def pop_events(self) -> list[DomainEvent]:
events, self._events = self._events, []
return events
class OrderApplicationService:
def submit_order(self, command: SubmitOrderCommand) -> None:
order = self._orders.find_by_id(command.order_id)
order.submit()
self._orders.save(order) # persist first
self._events.publish(order.pop_events()) # then publish
Save before publish: always persist the aggregate before publishing events. Publishing first risks announcing a state that was never durably saved.
Handler executes within the same transaction as the originating operation. Use when the reaction must succeed or fail atomically with the originator.
OrderSubmitted → reserve inventory (must be atomic — same transaction)
Risk: slow or failing handlers block the originating operation and can cause transaction timeouts.
Events are published to a message bus; handlers run in separate transactions. Use when a delay in the reaction is acceptable to the business.
OrderSubmitted → send confirmation email (delay is fine)
OrderSubmitted → update analytics dashboard (eventual is acceptable)
Trade-off: consumers may see stale state; events may be delivered more than once. Handlers must be designed for this.
Asynchronous event handlers must be idempotent — processing the same event twice produces the same result as processing it once.
class SendOrderConfirmationHandler:
def handle(self, event: OrderSubmitted) -> None:
if self._emails.already_sent_for(event.order_id):
return # idempotent guard — safe to process duplicate
self._emails.send_confirmation(
to=event.customer_id,
order_id=event.order_id,
total=event.total
)
self._emails.mark_sent(event.order_id)
Publishing to a message bus after saving introduces a window where the save succeeds but the publish fails. The Outbox pattern closes this gap.
class OrderApplicationService:
def submit_order(self, command: SubmitOrderCommand) -> None:
with self._unit_of_work as uow:
order = uow.orders.find_by_id(command.order_id)
order.submit()
uow.orders.save(order)
# Write events to outbox in the same transaction as the aggregate
uow.outbox.store(order.pop_events())
uow.commit()
# A separate process reads and publishes from the outbox reliably
Use when:
When NOT to use:
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub entelligentsia/skillforge --plugin design-patterns10 skills in this plugin
/anti-corruptionUse when external system types, vocabulary, or conventions bleed into your domain model, a single provider change would require touching many internal files, or a legacy system must keep running while a new one is built alongside it. Apply before writing any integration with an external API, legacy codebase, or third-party service. Covers Anti-Corruption Layer, Gateway, Facade, and Strangler Fig./behaviouralUse when behaviour varies across cases, accumulates conditionals, or needs to be decoupled, queued, undone, or observed. Apply when a method is growing if/switch branches, an algorithm differs per context, a pipeline needs flexible steps, or objects need to react to each other without tight coupling. Covers all 10 GoF behavioural patterns./cqrsUse when read and write performance requirements diverge significantly, complex reporting is painful through the domain model, or you need to scale reads and writes independently. Apply before splitting any command/query handler or building read-optimised projections. Covers Command Query Responsibility Segregation — including when it is overkill — with guidance on applying only as much separation as the problem demands./creationalUse when object creation is the source of pain — constructors growing too complex, the same setup repeated, unclear which concrete type to instantiate, or a shared instance causing hidden coupling. Apply before writing any factory, builder, or instantiation logic. Covers all 5 GoF creational patterns: Singleton, Builder, Factory Method, Abstract Factory, Prototype./data-accessUse when persistence logic bleeds into domain or business code, tests require a real database to verify business logic, ORM types appear in service or handler code, or switching storage would require touching domain classes. Apply before writing any database query, repository, or ORM integration. Covers Repository, Unit of Work, Data Mapper, and Active Record with explicit guidance on when each applies./domain-modelingUse when business objects have no behaviour (anemic model), invariants are enforced in services or controllers instead of domain classes, ownership of business rules is unclear, or the code allows states the business forbids. Apply before designing or reviewing any business domain class. Covers DDD tactical patterns: Entity, Value Object, Aggregate, Aggregate Root.Other plugins' skills for the same job