Domain Events vs Integration Events
"Something happened that domain experts care about." — Eric Evans, Domain-Driven Design Reference (2015), pattern "Domain Events"
Summary: A domain event is a fact inside one bounded context, named in its ubiquitous language, recorded by an aggregate and handled in-process; an integration event is a versioned, contract-shaped message that the context publishes for other contexts. Keep them apart, translate at the edge, and dispatch only after commit. Focus: Definitions and the reasons for the split, payload and naming, recording in the aggregate and dispatching after commit, in-process handlers and eventual consistency between aggregates, the outbox pointer, integration events across services (contract, versioning, idempotency, ordering, notification vs event-carried state transfer, CloudEvents), translation (zero, one or many), ownership, testing, correlation and causation ids, and the anti-patterns. Learning goal: Take a command such as PlaceOrder and implement it end to end in Go and Laravel: OrderPlaced recorded by the aggregate, an in-process loyalty listener, a translated sales.order.placed.v1 written to the outbox in the same transaction, idempotent consumers in Fulfilment and Billing, and tests that prove a rollback publishes nothing.
This chapter belongs to group DD 02 (Tactical Design). It assumes Aggregates & Factories (an aggregate is the consistency boundary that records events) and Bounded Context (the line an event crosses when it becomes an integration event). It owns the distinction and the design of the two kinds of events. It does not re-teach the plumbing. The messaging path owns brokers, relay strategies and guarantees: Transactional Outbox, Message Design & Schema Evolution, Idempotent Consumers, Ordering & Partitioning and Event Sourcing & CQRS. The design path owns event handling as a control style (Control Flow & Event Handling). The architecture path owns sync vs async between services (Service Communication).
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why two kinds of event exist at all | Why the split exists |
| Evans, Fowler, Vernon, Dahan, Richardson, Microsoft, CloudEvents | Where it comes from |
| What a domain event is, precisely | Domain event |
| What an integration event is | Integration event |
| Why one class must not do both jobs | Keeping them apart |
| Payload, names, when to raise | Designing a domain event |
| Raise, collect, commit, dispatch | Recording and dispatching |
| Same transaction or eventual | In-process handlers and consistency |
| Broker, contract, versions, duplicates, order | Integration events across contexts |
| Thin event or fat event | Notification vs event-carried state transfer |
| Envelope, correlation and causation ids | CloudEvents and tracing ids |
| Domain event to zero, one or many integration events | Translation at the edge |
| Who owns the contract | Ownership and naming |
| Eloquent model events, broadcasting | Framework events are not domain events |
| Event Storming, event sourcing | Neighbours |
| Timings, failure windows, knobs | Mechanics |
| The running example in code | Go, Laravel |
| Classic problems and fixes | Solving the classic problems |
| Which kind, which style | Choosing |
| Monolith to distributed | In architecture |
| Hands-on | Lab |
| Wrong beliefs, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The two kinds side by side. Every row is unpacked below.
| Aspect | Domain event | Integration event |
|---|---|---|
| What it is | A fact in the model of one bounded context | A message other contexts or services may depend on |
| Example | OrderPlaced (Go struct / PHP readonly class) | sales.order.placed.v1 (JSON in a CloudEvents envelope) |
| Language | The context's ubiquitous language | The context's published language |
| Audience | Handlers in the same context | Other bounded contexts, services, partners |
| Transport | In-process call (bus, dispatcher) | Broker or HTTP, via an outbox |
| When delivered | After commit (or inside the transaction for same-DB handlers) | After commit, asynchronously, at least once |
| Shape | Ids, values, what changed; may use model types | Primitive, documented fields; no internal types |
| Versioning | None; refactor freely with the model | Explicit (.v1, schema, compatibility rules) |
| Who may change it | The team, in one commit | The owning team, with a deprecation window |
| Failure mode if confused | Internal refactors break other teams | The model freezes because a contract leaks into it |
The order of operations in one command (details in Recording and dispatching):
| Step | Where | What happens | If it fails |
|---|---|---|---|
| 1. Raise | Aggregate method (Order.Place) | The event is recorded in a list on the aggregate | Command rejected, nothing recorded |
| 2. Save | Repository, inside the transaction | Aggregate state written | Rollback |
| 3. Translate + outbox | Application service, inside the transaction | Integration events inserted as rows | Rollback; nothing published |
| 4. Commit | Database | State and outbox become visible together | Nothing happened |
| 5. Dispatch | Application service, after commit | In-process handlers run | The fact stands; the handler retries on its own |
| 6. Relay | Background process | Outbox rows go to the broker | Retried; at least once |
| 7. Consume | Other contexts | Handlers de-duplicate and react | Retry, then DLQ |
Handler kinds (details in In-process handlers and consistency):
| Handler | Same context? | Consistency | Example in the running domain |
|---|---|---|---|
| Update another aggregate | Yes | Eventual (own transaction) | Reserve loyalty points for the customer |
| Side effect to the outside world | Yes | After commit, retryable | Send the order-confirmation email |
| Read model / projection | Yes | Eventual | Update "my orders" summary table |
| Translator to integration event | Yes (edge) | Same transaction as the aggregate (outbox row) | OrderPlaced → sales.order.placed.v1 |
| Consumer in another context | No | Eventual, at least once, idempotent | Fulfilment releases a WorkOrder; Billing opens an Invoice |
Anti-pattern → fix (details in Solving the classic problems):
| Anti-pattern | Symptom | Fix |
|---|---|---|
OrderUpdated | Consumers diff rows to guess what happened | Name the fact: OrderPlaced, OrderCancelled |
| Publishing domain events raw | A rename in Sales breaks Billing | Translate at the edge into a versioned contract |
| Dispatch before commit | Emails for orders that rolled back | Dispatch after commit; outbox for messages |
| Event as command | ShipOrder published as an "event" | Use a command message, or name the fact |
| Mutable references in events | Listener sees a later state than the fact | Copy ids and values into an immutable event |
| Order across aggregates assumed | Handler B runs before handler A's effect | Design handlers to be order-independent |
Why the split exists
A bounded context needs two things that pull in opposite directions. Inside, the model must stay free to change: names are refined, aggregates are split, fields move. Outside, other teams need something stable to build on. One event class cannot serve both: either the model freezes, or consumers break.
| If one event type does both jobs | With a domain event and an integration event |
|---|---|
| Renaming a field in Sales breaks Fulfilment's deploy | Sales renames freely; the translator keeps the contract |
| Internal fields (status codes, prices per line) leak to every consumer | The contract carries only what consumers need |
| Consumers need Sales' classes or library to decode | Consumers need a JSON schema and a type name |
| A new consumer forces changes into the domain class | A new consumer is a new contract field or a new contract |
| Versioning rules apply to domain code | Versioning applies only at the edge |
| Every internal event becomes public by accident | Internal events (OrderLineRepriced) publish nothing |
The everyday analogy. A hospital ward keeps a detailed chart for each patient: medications, vital signs every hour, nurses' notes in the ward's shorthand. When the patient is discharged, the ward sends the family doctor a discharge letter: a fixed format, plain words, only what the doctor needs, signed and dated. The chart (domain events) changes format whenever the ward improves its practice. The letter (integration event) changes rarely and announces it. Nobody sends the chart.
Three common misunderstandings, up front
- "An event is an event; one class is enough." Semantically they are the same kind of thing, a notification that something happened; Microsoft's guide says exactly that and then adds: "However, their implementation must be different." The difference is audience, stability and transport.
- "Domain events are asynchronous messages." Domain events are usually handled in the same process. The integration event is the asynchronous, cross-process message.
- "If we use events, we are doing event sourcing." Publishing events is not event sourcing. Event sourcing stores the events as the state (Event Sourcing & CQRS); most systems that publish events store state in tables.
Where it comes from
| Year | Source | What it contributed |
|---|---|---|
| 2004 | Eric Evans, Domain-Driven Design ("the 2004 book", in Evans' own words) | Aggregates, consistency boundaries; Domain Events is marked in the 2015 Reference as a "New term introduced since the 2004 book" |
| 2005 | Martin Fowler, bliki "Domain Event" (12 December 2005) | "Captures the memory of something interesting which affects the domain"; occurred vs noticed time |
| 2006 | Martin Fowler, "Event Collaboration" (19 June 2006) | Components "raise events when things change" instead of making requests |
| 2009 | Udi Dahan, "Domain Events – Salvation" (14 June 2009) | Raising events from entities via a static DomainEvents.Raise; secondary here |
| 2011 | Vaughn Vernon, "Effective Aggregate Design", part II | "Use eventual consistency outside the boundary"; an aggregate command publishes a domain event delivered to asynchronous subscribers |
| 2013 | Vaughn Vernon, Implementing Domain-Driven Design, ch. 8 | Domain events chapter, event stores, publishing across contexts (secondary here, not fetched) |
| 2015 | Evans, DDD Reference | Domain Events added as a pattern: immutable, timestamped, identities of entities involved |
| 2017 | Fowler, "What do you mean by 'Event-Driven'?" (7 February 2017) | Event notification, event-carried state transfer, event sourcing, CQRS: four different things |
| — | CloudEvents 1.0 (CNCF), tagged release v1.0.2 used here | A common envelope: id, source, specversion, type required |
| — | Chris Richardson, microservices.io "Domain event" and "Transactional outbox" | Aggregates emit domain events; the service publishes them; outbox makes publishing transactional |
| — | Microsoft, .NET Microservices: Architecture for Containerized .NET Applications | Names the split "domain events versus integration events" and the deferred dispatch approach |
| 2021 | Vlad Khononov, Learning Domain-Driven Design | Event notification vs event-carried state transfer vs domain event as message types; public vs private events (secondary here, not fetched) |
| — | AsyncAPI 3.0.0 | Machine-readable descriptions of message-driven APIs; a Correlation ID Object |
Primary quotes read for this page (saved text, see References). Evans, DDD Reference: "A domain event is a full-fledged part of the domain model, a representation of something that happened in the domain" and "Domain events are ordinarily immutable, as they are a record of something in the past." Microsoft: "the purpose of integration events is to propagate committed transactions and updates to additional subsystems, whether they are other microservices, Bounded Contexts or even external applications." Vernon (quoting Evans, DDD p128): "Any rule that spans AGGREGATES will not be expected to be up-to-date at all times."
Note on wording: the Evans PDF text renders "full-fledged" with a doubled hyphen in the extracted text; the quote above restores the single hyphen.
The concept catalogue
The picture is the whole chapter in one view: the domain event never leaves the dashed box; the integration event is born at the edge, written to the outbox, and only the relay talks to the broker.
Domain event Must-know
In plain words: A domain event is a sentence in the past tense that a domain expert would say, "the order was placed", turned into a small immutable object that the model records when it happens.
Common misunderstanding: "A domain event is any notification the code emits, like UserSaved." A domain event is part of the model: experts care about it, it has a name from the ubiquitous language, and it would exist even without a database. saved is a persistence hook, not a domain fact.
Definition: Evans' Reference: "Model information about activity in the domain as a series of discrete events. Represent each event as a domain object." The properties that follow: past tense, immutable, named in the ubiquitous language, raised by the aggregate whose state changed, carrying a timestamp and the identities of the entities involved (Evans), and optionally its own identity so duplicates can be recognised.
# PlaceOrder, inside Sales
1 Customer -> Sales API: POST /orders (cart c-7)
2 App service: order := NewDraft(o-42); AddLine(...)
3 Order.Place(now): checks invariants, status := placed
4 Order.Place records OrderPlaced{OrderID: o-42, CustomerID: c-7, Total: 30.00 EUR, Lines, At}
5 Nothing has been sent anywhere yet: the event sits in order.eventsReal scenarios:
OrderPlaced,OrderCancelled,PaymentCaptured,ParcelDispatched,RefundIssuedin an ordering business.SeatReservedin a booking system;LimitExceededin a credit system;PasswordChangedin Identity.- Facts that are not state changes of one row:
DeliveryWindowMissed(a deadline passed) is a domain event raised by a scheduler calling the aggregate. - Not domain events:
RowInserted,CacheCleared,UserSaved,JobFailed(these are system events; Evans: "distinct from system events that reflect activity within the software itself").
What provides it:
| Platform | Primitive | Note |
|---|---|---|
| Go | A plain struct implementing a small Event interface | No library needed; aggregates keep []Event |
| Laravel 13 | A plain PHP readonly class | Any object can be dispatched by Event::dispatch / the Dispatcher contract |
| Watermill (Go) | cqrs.EventBus + EventProcessor | Works with Go structs; useful when events go to a Pub/Sub |
| .NET (for comparison) | MediatR INotification in eShop | Microsoft's reference uses an in-memory mediator |
How to use it: the event is a value type with past-tense name, ids and values. Go: sales.OrderPlaced in the Go section. Laravel: App\Modules\Sales\Domain\Events\OrderPlaced in the Laravel section.
Integration event Must-know
In plain words: An integration event is the public announcement a bounded context makes about something that happened, written in a fixed, documented format that other teams can rely on.
Common misunderstanding: "It is the domain event serialized to JSON." That shortcut couples every consumer to the producer's internal model. The integration event is a separate type with its own fields, name and version, produced from one or more domain events.
Definition: A message, owned and versioned by the producing context, that is part of its published language (Context Maps). It is emitted only for committed changes. Microsoft's guide: "they should occur only if the entity is successfully persisted, otherwise it's as if the entire operation never happened", and "integration events must be based on asynchronous communication between multiple microservices (other Bounded Contexts) or even external systems/applications".
# The same fact, crossing the boundary
1 Sales tx: INSERT orders ...; INSERT outbox (type = sales.order.placed.v1, subject = o-42)
2 Sales tx: COMMIT
3 Relay: SELECT ... FROM outbox WHERE published_at IS NULL -> publish -> UPDATE published_at
4 Broker -> Fulfilment: sales.order.placed.v1 (id evt-1) -> WorkOrder released
5 Broker -> Billing: sales.order.placed.v1 (id evt-1) -> Invoice drafted
6 Broker re-delivers evt-1 to Fulfilment -> inbox says "seen" -> ack, no changeReal scenarios:
sales.order.placed.v1for Fulfilment (lines, shipping country) and Billing (total, currency).identity.customer.address-changed.v1so Sales keeps its own copy of the shipping address (event-carried state transfer).billing.payment.captured.v1that Sales turns intoOrder.MarkPaid.- A partner webhook (
fulfilment.parcel.dispatched.v1) is an integration event delivered over HTTP instead of a broker.
What provides it:
| Concern | Product or spec | What it gives |
|---|---|---|
| Transport | RabbitMQ, Kafka, Redis Streams, NATS JetStream, SQS/SNS, Google Pub/Sub | Delivery to many consumers; see broker comparison |
| Atomic publish with the state change | Transactional outbox; Watermill Forwarder; Debezium outbox router | No lost, no ghost events (outbox) |
| Envelope | CloudEvents 1.0 | id, source, specversion, type (+ optional subject, time, datacontenttype, dataschema) |
| Contract description | AsyncAPI 3.0.0, JSON Schema, Avro, Protobuf + a schema registry | Machine-readable contract, compatibility checks |
| Contract tests | Pact message pacts | Consumers' expectations verified against the producer |
How to use it: a separate contracts package (Go) or Integration namespace (Laravel) owned by Sales; type names sales.order.placed.v1; consumers depend on the schema, never on Sales' classes.
Keeping them apart: translation at the edge Must-know
In plain words: Domain events are for the family; integration events are for the neighbours. A translator at the door decides what the neighbours hear, in which words, and in which format.
Common misunderstanding: "A translator is boilerplate; just add #[Public] to the domain event." The translator is where the context protects its freedom. It drops internal fields, renames to contract words, enriches with data consumers need, and chooses zero, one or many outputs. That is an anti-corruption layer pointed outwards.
Definition: (the general EIP translator, enricher and canonical model live in Message Transformation.) Translation is a function from domain events (plus local data) to integration events, executed inside the producing context and inside the same transaction as the aggregate change, so that the outbox row and the state commit together.
# Why the separation pays off: a refactor six months later
1 Sales renames Order.lines[].unitPrice to Order.lines[].agreedPrice (domain refactor)
2 Domain event OrderPlaced changes in the same commit; all Sales tests pass
3 Translator still maps to sales.order.placed.v1 { lines: [{sku, quantity}] }
4 Fulfilment and Billing see no change, no coordinated deploy
5 Without the translator: Billing's decoder fails on the missing field at 02:00Real scenarios: an internal event that should stay private (OrderLineRepriced); one domain event becoming two integration events during a v1 → v2 migration; two domain events folded into one public fact (OrderPlaced + PaymentCaptured → sales.order.confirmed.v1 for a partner); enriching OrderPlaced with the shipping country from Sales' own checkout data.
| Translator decision | Example | Why |
|---|---|---|
| Zero outputs | OrderLineRepriced → nothing | Internal fact; nobody outside needs it |
| One output | OrderCancelled → sales.order.cancelled.v1 | Normal case |
| Many outputs | OrderPlaced → .v1 and .v2 | Dual publishing during a migration window |
| Enrichment | add shippingCountry | Fulfilment can act without calling Sales back |
| Reduction | drop unitPrice, status | Not part of the contract; free to change |
| Aggregation | OrderPlaced + PaymentCaptured → sales.order.confirmed.v1 | A partner only cares about confirmed orders (needs a process manager) |
Designing a domain event Must-know
In plain words: Name it like a headline in the past tense, put in the ids and the values that changed, never the whole aggregate, and raise it only when the command actually succeeded.
Common misunderstanding: "Put the whole Order in the event so listeners have everything." A reference to the aggregate is mutable: by the time a queued listener runs, the order may be cancelled. The listener then acts on a state that is not the fact. Copy the values the fact needs.
Definition: Design rules, each with its reason:
| Rule | Good | Bad | Reason |
|---|---|---|---|
| Past tense, business verb | OrderPlaced | PlaceOrder, OrderEvent | A fact, not a request |
| Specific, not CRUD | OrderCancelled | OrderUpdated, OrderChanged | Listeners should not diff to understand |
| Ids of every entity involved | OrderID, CustomerID | Only the order row id | Evans: "the identity of entities involved" |
| What changed, as values | Total, Lines (copied) | *Order, Order $order (Eloquent model) | Immutable record of the past |
| When it happened | At / occurredAt | Only the DB created_at | Occurred time vs noticed time (Fowler) |
| Raised by the aggregate | Inside Order.Place | In a controller after save() | The aggregate knows when the fact is true |
| Raised only on success | After invariants pass | Before validation | A rejected command produced no fact |
| No infrastructure types | Money, SKU | *sql.Tx, Request | It is part of the model |
| Small and focused | One fact per event | OrderPlacedAndPaidAndDispatched | Different listeners, different timings |
# When to raise: the order of checks inside the aggregate
1 Order.Place(now)
2 if status != Draft -> return ErrBadTransition (no event)
3 if len(lines) == 0 -> return ErrEmptyOrder (no event)
4 status = Placed (state change)
5 record(OrderPlaced{...copied values...}) (fact recorded)
6 return nilReal scenarios: a "placed" event that carried an Eloquent model, serialised by SerializesModels, was re-loaded fresh by a queued listener and showed the order already cancelled; a CustomerUpdated event that forced five consumers to compare old and new addresses; an OrderPlaced raised in the controller before save() that fired for orders that later failed a unique constraint.
Fix: see sales/events.go and Domain/Events/OrderPlaced.php below: copied values, readonly, no model reference. For naming in depth see Ubiquitous Language.
Recording and dispatching: raise, collect, commit, dispatch Must-know
In plain words: The aggregate writes the event in its notebook. The application service reads the notebook, saves everything in one transaction, and only after the database says "committed" does it tell the listeners.
Common misunderstanding: "Dispatch the moment the aggregate raises it; that is simplest." Immediate dispatch from inside the aggregate (Dahan's 2009 static DomainEvents.Raise) runs side effects before the transaction is decided. If the commit fails, the email is already sent. Microsoft's guide also notes it makes testing harder: "the event handlers with side-effects logic are executed immediately after the event is raised".
Definition: the deferred approach (Microsoft credits Jimmy Bogard's "A better domain events pattern"): "add the domain events to a collection and then to dispatch those domain events right before or right after committing the transaction". The choice of before or after is the choice between one transaction and eventual consistency:
| Dispatch point | Handlers that are safe here | Handlers that are dangerous here |
|---|---|---|
| Immediately in the aggregate | None in production | Everything: no transaction decided yet |
| Right before commit, same transaction | Handlers that only write to the same database (they commit or roll back with the order) | Email, HTTP, broker publish, queue push: they cannot be rolled back |
| Right after commit | In-process side effects: email, cache, read model, queued listeners | None for correctness, but a crash between commit and dispatch loses them |
| Via the outbox (row in the transaction) | Anything that must not be lost, especially integration events | None; costs a relay and at-least-once handling |
App service (Sales) Database Listeners / Broker
1 order.Place(now) -> records OrderPlaced
2 BEGIN tx open
3 repo.Save(order) UPDATE orders
4 envs := translate(order.PendingEvents())
5 outbox.Insert(envs) INSERT outbox
6 COMMIT both visible
7 bus.Dispatch(events); order.MarkCommitted() loyalty, email, read model
8 relay publishes outbox rows
-- crash between 6 and 7: email not sent (retry job or outbox-driven handler needed)
-- crash between 6 and 8: nothing lost, the relay publishes on restartReal scenarios: a Laravel listener dispatched inside DB::transaction that queued a job, which a fast worker ran before commit and could not find the order (the Laravel queue docs describe exactly this: "it is possible that the job will be processed by a worker before the parent transaction has committed"); a Go service that published to Kafka inside the transaction and then hit a serialization failure on COMMIT; a Doctrine/EF style "dispatch in SaveChanges" that sent emails for rolled-back orders.
What provides after-commit dispatch:
| Platform | Mechanism | Scope |
|---|---|---|
| Laravel 13 | ShouldDispatchAfterCommit on the event class | Event is dispatched after the active transaction commits |
| Laravel 13 | ShouldQueueAfterCommit on a queued listener | Job is pushed after commit |
| Laravel 13 | Queue connection option after_commit => true | All jobs on that connection |
| Laravel 13 | ShouldHandleEventsAfterCommit on an Eloquent observer | Observer handlers wait for commit |
| Laravel 13 | Event::defer(fn () => ...) | Delays model events and listeners until the closure has run; not a transaction hook |
| Go | Collect PendingEvents(), call the bus after tx.Commit() returns nil | Explicit in the application service |
| Watermill | Forwarder: publish to an SQL Pub/Sub inside the transaction, forward to the broker | Outbox for Go |
Fix: see app/place_order.go and Application/PlaceOrder.php. The rule that ties it together: translate and insert the outbox rows inside the transaction; dispatch in-process handlers after commit; anything that must not be lost goes through the outbox.
In-process handlers and consistency Important
In plain words: One command changes one aggregate. If another aggregate in the same context has to react, a handler does it a moment later, in its own transaction. The business usually accepts that moment.
Common misunderstanding: "Handling the event in the same process means it is in the same transaction." Not necessarily, and usually it should not be. Vernon's rule is "Use Eventual Consistency Outside the Boundary": "if executing a command on one aggregate instance requires that additional business rules execute on one or more other aggregates, use eventual consistency." Two aggregates in one transaction mean more lock contention and larger failure scope (Aggregates).
Definition: a domain event handler is application-layer code (Microsoft: "Handling the domain events is an application concern") that loads another aggregate, calls one method on it, and saves it. It runs after commit, retries on its own, and is idempotent because it may run twice.
# OrderPlaced -> loyalty points, eventual inside Sales
1 T1: BEGIN; save Order o-42 (placed); INSERT outbox; COMMIT
2 after commit: dispatch OrderPlaced -> ReserveLoyaltyPoints queued (Laravel) / called (Go)
3 T2: BEGIN; INSERT loyalty_reservations (order_id o-42, 30 points) ON CONFLICT DO NOTHING; COMMIT
4 Between 1 and 3 (milliseconds to seconds) the order exists without points: accepted by the business
5 If T2 fails: retried (queue tries / backoff); the order is not rolled backReal scenarios and the consistency they need:
| Rule | Transactional (same tx) or eventual? | Reason |
|---|---|---|
| Order total equals the sum of lines | Transactional, inside one aggregate | Invariant of the aggregate |
| Loyalty points reserved for a placed order | Eventual | The business tolerates seconds; two aggregates |
| "My orders" list shows the new order | Eventual (read model) | A short lag is fine; show "processing" |
| Confirmation email | After commit, retryable | Cannot be rolled back |
| Stock decremented for each order | Eventual across contexts, with a saga | Inventory is another context (Saga) |
| Customer credit limit not exceeded | Decide where the invariant lives; often redesign the aggregate | A cross-aggregate invariant that cannot be eventual is a boundary smell |
Ask the expert. Vernon: "Domain experts are sometimes far more comfortable with the idea of delayed consistency than are developers."
Fix: Go loyalty/reserve.go (idempotent by order id); Laravel ReserveLoyaltyPoints (queued, ShouldQueueAfterCommit, insertOrIgnore on a unique key).
Integration events across contexts Important
In plain words: Once an event leaves the process it becomes a message: it can arrive twice, late, or out of order, and the receiver is a different team with a different model. Design for that.
Common misunderstanding: "The broker guarantees exactly-once, in order." Brokers give at-least-once, with ordering only within a partition or a single queue. Consumers de-duplicate and tolerate reordering (Delivery Guarantees, Ordering & Partitioning).
Definition: the checklist for every integration event:
| Concern | Rule for this chapter | Owned in depth by |
|---|---|---|
| Contract | Type name, schema, documented fields, owner | Message Design & Schema Evolution |
| Versioning | Additive changes in place; breaking changes = new .vN type, dual-publish, deprecate | Same |
| Reliable publish | Outbox row in the business transaction, relay after commit | Outbox |
| Duplicates | Consumer inbox keyed by source + id | Idempotent Consumers |
| Ordering | Partition key = aggregate id (subject); never assume order across aggregates | Ordering & Partitioning |
| Poison messages | Reject to a DLQ after retries | Dead-Letter Queue |
| Unknown types/versions | Ignore (tolerant reader), do not fail | Same as contract |
# Ordering caveat: two aggregates, two partitions
1 Sales: OrderPlaced(o-42) -> partition 3 (key o-42)
2 Identity: CustomerAddressChanged(c-7) -> partition 1 (key c-7)
3 Fulfilment receives the address change AFTER the order, though it happened before
4 Fulfilment must not assume "latest address seen" = "address at order time"
5 Fix: the order event carries the shipping country it was placed with (enrichment)Real scenarios: Fulfilment consumes sales.order.placed.v1 and releases a WorkOrder; Billing consumes it and drafts an Invoice; Sales consumes billing.payment.captured.v1 and calls Order.MarkPaid; a data platform consumes everything into a warehouse. Each consumer translates the contract into its own words (inbound ACL).
Notification vs event-carried state transfer Important
In plain words: A thin event says "order o-42 was placed, ask me if you need more". A fat event says "order o-42 was placed, here are its lines, total and country" so the consumer never has to call back.
Common misunderstanding: "Thin events are always better because they are decoupled." A thin event plus a callback creates a synchronous runtime dependency on the producer (and a race: the callback may see a newer state). A fat event duplicates data but lets the consumer work while the producer is down.
Definition: Fowler (2017) names both. Event notification: "An event need not carry much data on it, often just some id information and a link back to the sender that can be queried for more information." Event-carried state transfer: consumers "update clients of a system in such a way that they don't need to contact the source system in order to do further work", gaining "greater resilience" at the cost of "lots of data schlepped around and lots of copies".
| Style | Payload | Consumer does | Strength | Cost |
|---|---|---|---|---|
| Notification | ids (+ link) | Calls back (GET /orders/o-42) | Small, private data stays home | Runtime coupling, callback race, load on producer |
| Event-carried state transfer | ids + the state consumers need | Updates its own copy | Works when producer is down, no callback latency | Bigger messages, copies, PII spreads |
| Hybrid | ids + a stable subset | Uses payload, calls back rarely | Usual production choice | Contract design effort |
# Notification + callback (race)
1 Sales: OrderPlaced(o-42) published (thin)
2 Customer cancels o-42 one second later
3 Billing receives OrderPlaced, calls GET /orders/o-42 -> status cancelled
4 Billing does not know whether the placement or the cancellation is "the" event to act on
# Event-carried state transfer
1 Sales: sales.order.placed.v1 {lines, total, country}
2 Billing drafts the invoice from the payload; later sales.order.cancelled.v1 voids itFowler's four meanings of "event-driven" are owned by Event-Driven Architecture.
Choice for the running example: sales.order.placed.v1 carries what Fulfilment and Billing need (lines with sku and quantity, total, currency, shipping country), not Sales' internal prices per line or status codes.
CloudEvents envelope and tracing ids Good to know
In plain words: Put every integration event in the same envelope: who sent it, what kind it is, a unique id, when. Then routers, logs and consumers can treat all events alike.
Common misunderstanding: "CloudEvents defines correlation ids." The core spec (v1.0.2) requires id, source, specversion and type; correlation and causation ids are extension attributes you add yourself (the spec: "CloudEvents attribute names MUST consist of lower-case letters ('a' to 'z') or digits ('0' to '9')", hence correlationid, causationid). AsyncAPI 3.0.0 describes where a correlation id lives with its Correlation ID Object.
Definition: the attributes used in the running example:
| Attribute | Required (CloudEvents 1.0.2) | Running example | Purpose |
|---|---|---|---|
specversion | Yes | 1.0 | Spec version |
id | Yes | evt-1 (UUID in Laravel) | With source, the duplicate key |
source | Yes | /sales | Producer context |
type | Yes | sales.order.placed.v1 | Routing and versioning |
subject | No | o-42 | Aggregate id; partition key |
time | No | occurred time of the domain event | Business time |
datacontenttype | No | application/json | Payload encoding |
correlationid | Extension | req-1 (checkout request) | Groups the whole flow |
causationid | Extension | cmd-1 (the PlaceOrder command) | The message that directly caused this one |
The spec's duplicate rule: "Producers MUST ensure that source + id is unique for each distinct event. If a duplicate event is re-sent (e.g. due to a network error) it MAY have the same id. Consumers MAY assume that Events with identical source and id are duplicates." The Fulfilment consumer's inbox key is exactly source + "/" + id.
# Correlation and causation through three hops
1 HTTP POST /orders request-id req-1
2 PlaceOrder cmd-1 correlation req-1, causation req-1
3 sales.order.placed.v1 evt-1 correlation req-1, causation cmd-1
4 fulfilment.workorder.released.v1 evt-9 correlation req-1, causation evt-1
5 Search logs by req-1 -> the whole story; follow causation -> the exact chainW3C traceparent propagation in message headers is owned by Messaging Observability.
Ownership, naming and contracts Good to know
In plain words: The context that knows the fact owns the event and its contract. Consumers may ask for changes; they do not dictate the producer's words.
Common misunderstanding: "Consumers define the events they need (BillingNeedsInvoiceData)." That turns events into commands addressed to a consumer. The producer publishes facts in its published language; a consumer that needs a different shape translates on its side, or the teams negotiate a contract (Customer-Supplier in Context Maps).
Definition and naming scheme: <context>.<aggregate>.<fact-in-past-tense>.v<major>, for example sales.order.placed.v1. CloudEvents suggests the type "SHOULD be prefixed with a reverse-DNS name" (com.example.sales.order.placed.v1) when events leave the organisation.
| Question | Answer |
|---|---|
Who owns sales.order.placed.v1? | Sales (the team and the code under contracts) |
| Where is it documented? | AsyncAPI document or schema registry next to the producer |
| How does a consumer protect itself? | Consumer-driven contract tests (Pact message pacts) run in the producer's CI |
| May Billing add a field? | It may ask; Sales adds it if it is a Sales fact |
| What is a breaking change? | Removing/renaming a field, changing a type or meaning: new .v2 |
Pact's docs describe the idea: "Contract testing is a technique for testing an integration point by checking each application in isolation to ensure the messages it sends or receives conform to a shared understanding that is documented in a "contract"."
Framework events are not domain events Important
In plain words: Laravel's Eloquent fires created, updated, saved for every row change. These are persistence hooks. They tell you a row changed, not what happened in the business.
Common misunderstanding: "An OrderObserver::updated that publishes to Kafka is our event-driven architecture." It publishes CRUD events with whole models, it may publish before commit, and it silently misses changes: the Laravel docs warn that for a mass update "the saving, saved, updating, and updated model events will not be fired for the updated models."
Definition: Eloquent model events are retrieved, creating, created, updating, updated, saving, saved, deleting, deleted, trashed, forceDeleting, forceDeleted, restoring, restored, and replicating (Laravel 13 docs). Broadcasting (ShouldBroadcast) pushes an event to browsers over WebSockets; it is a UI delivery channel, not an integration contract.
| Mechanism | Is it a domain event? | Use it for |
|---|---|---|
| Eloquent model events / observers | No | Technical concerns: UUID on creating, cache busting |
$dispatchesEvents mapping | Only if you map to a real business fact, still risky | Rarely |
| A domain event class dispatched by the application service | Yes | Business reactions inside the context |
ShouldBroadcast event | No (UI channel) | Live order-status page |
| Integration event in the outbox | No (it is the public translation) | Other contexts |
# The silent miss
1 Support runs: Order::where('status', 'placed')->where('created_at', '<', $cutoff)->update(['status' => 'expired'])
2 No model is retrieved -> no updated event -> OrderObserver never runs
3 Fulfilment never hears that 3,000 orders expired
4 With domain events: an ExpireStaleOrders command loads each aggregate, calls Order.Expire, records OrderExpiredNeighbours: Event Storming and event sourcing Good to know
In plain words: Event Storming is how you find domain events (a workshop with orange sticky notes). Event sourcing is a way to store an aggregate (as its list of events). Neither is required to use domain events.
Common misunderstanding: "We publish events, so we are event-sourced." Fowler: event sourcing means "whenever we make a change to the state of a system, we record that state change as an event, and we can confidently rebuild the system state by reprocessing the events". The running example stores orders in a table and publishes events; that is not event sourcing.
Definition: Event Storming (chapter) discovers domain events, commands, policies ("whenever X then Y" = an event handler) and aggregates. Event sourcing (Event Sourcing & CQRS) makes the events the source of truth; then the domain events are the persisted state, and integration events are still translated from them.
| You have | You are doing |
|---|---|
| Aggregates that record events, tables for state | Domain events (this chapter) |
| Plus an outbox and a broker | Domain + integration events, event-driven integration |
| Events stored as the only state, rebuilt by replay | Event sourcing |
| Separate read models fed by events | CQRS (with or without event sourcing) |
Mechanics
Where events live in each layer
| Layer (services chapter) | Domain events | Integration events |
|---|---|---|
| Domain | Defined and recorded by aggregates | Never referenced |
| Application | Collected, dispatched after commit; handlers live here | Translator called here, inside the transaction |
| Infrastructure | In-process bus implementation | Outbox table, relay, broker adapter, consumer endpoints |
| Contracts (published language) | Never | Defined here, versioned, documented |
The outbox table
Only the shape this chapter needs; relay strategies, CDC and ordering across the relay are in Transactional Outbox. Richardson's solution: "the service that sends the message to first store the message in the database as part of the transaction that updates the business entities."
-- PostgreSQL: Sales' outbox, written in the same transaction as orders
CREATE TABLE outbox (
seq bigserial PRIMARY KEY, -- relay order
event_id uuid NOT NULL UNIQUE, -- CloudEvents id
event_type text NOT NULL, -- sales.order.placed.v1
subject text NOT NULL, -- aggregate id, partition key
correlation_id text,
payload jsonb NOT NULL, -- the whole envelope
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz
);
CREATE INDEX outbox_unpublished ON outbox (seq) WHERE published_at IS NULL;
-- Relay (one batch): several relay instances may run, SKIP LOCKED keeps them apart
BEGIN;
SELECT seq, payload FROM outbox
WHERE published_at IS NULL ORDER BY seq LIMIT 100
FOR UPDATE SKIP LOCKED;
-- publish each row to the broker, wait for the broker's confirm, then:
UPDATE outbox SET published_at = now() WHERE seq = $1;
COMMIT;
-- Consumer side (Fulfilment): the inbox makes redelivery harmless
CREATE TABLE fulfilment_inbox (message_key text PRIMARY KEY, received_at timestamptz NOT NULL);
INSERT INTO fulfilment_inbox VALUES ('/sales/evt-1', now()) ON CONFLICT DO NOTHING; -- 0 rows = duplicateFailure windows
| Crash or error at | Without outbox | With outbox |
|---|---|---|
| Before COMMIT | Nothing persisted; if you published already: ghost event | Nothing persisted, nothing published |
COMMIT fails (40001 serialization failure, 40P01 deadlock in PostgreSQL) | Ghost event if published before | Rollback; retry the command |
| After COMMIT, before publish | Event lost forever | Row waits; relay publishes on restart |
| After publish, before marking published | n/a | Republished: consumers de-duplicate |
| Consumer crashes after side effect, before ack | Redelivered: duplicate side effect | Inbox in the same transaction as the side effect: no duplicate |
| In-process handler fails after commit | The fact stands; handler must retry on its own | Same; or drive the handler from the outbox too |
The last row is the honest limit of in-process after-commit dispatch: it is not durable. When a reaction must survive a crash (points must be reserved), either make it a queued job pushed after commit with retries (Laravel ShouldQueueAfterCommit; note the push itself can still be lost if the process dies right after commit), or feed it from the outbox like an integration event. Microsoft's guide frames the same trade-off as "whether you will include the side effects as part of the same transaction or in different transactions".
Knobs and names you will meet
| Product | Knob or API | Effect |
|---|---|---|
| Laravel 13 | ShouldDispatchAfterCommit (event) | Dispatch waits for the open transaction to commit |
| Laravel 13 | ShouldQueueAfterCommit (listener) | Queued listener is pushed after commit |
| Laravel 13 | 'after_commit' => true (queue connection) | All jobs and queued listeners on the connection wait for commit; default false in the shipped config |
| Laravel 13 | ShouldHandleEventsAfterCommit (observer) | Observer runs after commit; immediately if no transaction |
| Laravel 13 | Event::defer() | Model events and listeners run after the closure; discarded if it throws |
| Laravel 13 | ShouldBeEncrypted (queued listener) | Payload encrypted on the queue (PII in events) |
| Laravel 13 | withEvents(discover: [...]) | Listener discovery paths, for app/Modules/*/Listeners |
| Laravel 13 | $tries, failed() on queued listeners | Retries and a failure hook |
| Go (stdlib) | tx.Commit() return value | Dispatch only when it is nil |
| Watermill | cqrs.EventBus, cqrs.EventProcessor, cqrs.NewEventHandler | Struct-based events over any Pub/Sub |
| Watermill | Forwarder (the outbox pattern) | SQL Pub/Sub inside the transaction, forwarded to the broker |
| CloudEvents | id, source, specversion, type | Required attributes |
| AsyncAPI 3.0.0 | channels, operations, messages, correlationId | Contract description |
Go
The Go module runs the whole running example in one process: domain events in the aggregate, an in-process bus, the translator, an in-memory database with real commit/rollback semantics standing in for PostgreSQL, the outbox relay, and the Fulfilment consumer. Standard library only; a Watermill message.Publisher or a franz-go producer would sit behind the outbox.Publisher port.
Domain events and the aggregate
// Package sales is the Sales bounded context. Its domain events are part of
// the model: past-tense, immutable, named in the ubiquitous language, and
// carrying identities and values only. They have no wire name and no version,
// because they never leave the context as they are.
package sales
import "time"
// Event is a domain event recorded by an aggregate.
type Event interface {
// OccurredAt is when the fact became true in the domain.
OccurredAt() time.Time
}
// PlacedLine is a value copy of one order line at the moment of placing.
type PlacedLine struct {
SKU SKU
Quantity int
UnitPrice Money
}
// OrderPlaced: the customer committed to buy.
type OrderPlaced struct {
OrderID OrderID
CustomerID CustomerID
Total Money
Lines []PlacedLine
At time.Time
}
// OccurredAt implements Event.
func (e OrderPlaced) OccurredAt() time.Time { return e.At }
// OrderCancelled: the commitment was withdrawn before shipping.
type OrderCancelled struct {
OrderID OrderID
Reason string
RefundDue bool
At time.Time
}
// OccurredAt implements Event.
func (e OrderCancelled) OccurredAt() time.Time { return e.At }
// OrderLineRepriced is internal to Sales: no other context needs it, so the
// translator at the edge publishes nothing for it.
type OrderLineRepriced struct {
OrderID OrderID
SKU SKU
OldPrice Money
NewPrice Money
At time.Time
}
// OccurredAt implements Event.
func (e OrderLineRepriced) OccurredAt() time.Time { return e.At }package sales
import (
"errors"
"time"
)
type (
// OrderID is the identity of the Order aggregate.
OrderID string
// CustomerID references the Identity context's customer by id.
CustomerID string
// SKU references a Catalog product by id.
SKU string
)
// Money is a value object in minor units.
type Money struct {
Minor int64
Currency string
}
// Status is the Order state machine.
type Status string
// Order states.
const (
Draft Status = "draft"
Placed Status = "placed"
Cancelled Status = "cancelled"
)
// Domain errors, phrased in the ubiquitous language.
var (
ErrEmptyOrder = errors.New("an order needs at least one line")
ErrBadTransition = errors.New("this status change is not allowed")
)
type line struct {
sku SKU
quantity int
unitPrice Money
}
// Order is the aggregate root. It records events; it never dispatches them.
type Order struct {
id OrderID
customer CustomerID
currency string
status Status
lines []line
events []Event
}
// NewDraft starts an empty draft order.
func NewDraft(id OrderID, customer CustomerID, currency string) *Order {
return &Order{id: id, customer: customer, currency: currency, status: Draft}
}
// AddLine adds a line to a draft (validation kept short for the example).
func (o *Order) AddLine(sku SKU, qty int, unitPrice Money) {
o.lines = append(o.lines, line{sku: sku, quantity: qty, unitPrice: unitPrice})
}
// Place turns the draft into a commitment and records OrderPlaced.
func (o *Order) Place(now time.Time) error {
if o.status != Draft {
return ErrBadTransition
}
if len(o.lines) == 0 {
return ErrEmptyOrder
}
o.status = Placed
o.record(OrderPlaced{
OrderID: o.id, CustomerID: o.customer,
Total: o.Total(), Lines: o.placedLines(), At: now,
})
return nil
}
// Cancel withdraws a placed order and records OrderCancelled.
func (o *Order) Cancel(reason string, now time.Time) error {
if o.status != Placed {
return ErrBadTransition
}
o.status = Cancelled
o.record(OrderCancelled{OrderID: o.id, Reason: reason, At: now})
return nil
}
// Total is derived from the lines.
func (o *Order) Total() Money {
t := Money{Currency: o.currency}
for _, l := range o.lines {
t.Minor += l.unitPrice.Minor * int64(l.quantity)
}
return t
}
// ID returns the identity.
func (o *Order) ID() OrderID { return o.id }
// Status returns the current state.
func (o *Order) Status() Status { return o.status }
// PendingEvents returns a copy of the events recorded since the last commit.
func (o *Order) PendingEvents() []Event { return append([]Event(nil), o.events...) }
// MarkCommitted clears the recorded events; call it only after COMMIT.
func (o *Order) MarkCommitted() { o.events = nil }
func (o *Order) record(e Event) { o.events = append(o.events, e) }
// placedLines copies lines into the event so the event never aliases state.
func (o *Order) placedLines() []PlacedLine {
out := make([]PlacedLine, len(o.lines))
for i, l := range o.lines {
out[i] = PlacedLine{SKU: l.sku, Quantity: l.quantity, UnitPrice: l.unitPrice}
}
return out
}package sales
import (
"errors"
"testing"
"time"
)
var now = time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)
func TestPlaceRecordsOrderPlaced(t *testing.T) {
o := NewDraft("o-42", "c-7", "EUR")
o.AddLine("sku-1", 2, Money{Minor: 1500, Currency: "EUR"})
if err := o.Place(now); err != nil {
t.Fatal(err)
}
evs := o.PendingEvents()
if len(evs) != 1 {
t.Fatalf("want 1 event, got %d", len(evs))
}
placed, ok := evs[0].(OrderPlaced)
if !ok {
t.Fatalf("want OrderPlaced, got %T", evs[0])
}
if placed.Total.Minor != 3000 || placed.OrderID != "o-42" || !placed.At.Equal(now) {
t.Fatalf("unexpected payload %+v", placed)
}
}
func TestFailedCommandRecordsNothing(t *testing.T) {
o := NewDraft("o-43", "c-7", "EUR")
if err := o.Place(now); !errors.Is(err, ErrEmptyOrder) {
t.Fatalf("want ErrEmptyOrder, got %v", err)
}
if n := len(o.PendingEvents()); n != 0 {
t.Fatalf("a rejected command must not record events, got %d", n)
}
}
func TestEventDoesNotAliasAggregateState(t *testing.T) {
o := NewDraft("o-44", "c-7", "EUR")
o.AddLine("sku-1", 1, Money{Minor: 100, Currency: "EUR"})
_ = o.Place(now)
ev := o.PendingEvents()[0].(OrderPlaced)
o.lines[0].quantity = 99 // later change inside the aggregate
if ev.Lines[0].Quantity != 1 {
t.Fatal("the event must be an immutable copy of the fact")
}
}The in-process bus
// Package eventbus is an in-process domain event dispatcher for ONE bounded
// context. It is synchronous and in-memory: handlers run in the caller's
// goroutine, in subscription order, after the application service committed.
// Nothing here crosses a process boundary; that is the outbox's job.
package eventbus
import (
"context"
"errors"
"fmt"
"academy/domain-events-integration-events/sales"
)
type handler struct {
name string
fn func(context.Context, sales.Event) (handled bool, err error)
}
// Bus routes domain events to the handlers subscribed to their type.
type Bus struct{ handlers []handler }
// Subscribe registers fn for events of type E. The name shows up in errors and logs.
func Subscribe[E sales.Event](b *Bus, name string, fn func(context.Context, E) error) {
b.handlers = append(b.handlers, handler{name: name, fn: func(ctx context.Context, ev sales.Event) (bool, error) {
e, ok := ev.(E)
if !ok {
return false, nil
}
return true, fn(ctx, e)
}})
}
// Dispatch delivers every event to every matching handler. One failing handler
// does not stop the others; all errors are joined and returned to the caller,
// which logs them (the business transaction is already committed).
func (b *Bus) Dispatch(ctx context.Context, events []sales.Event) error {
var errs []error
for _, ev := range events {
for _, h := range b.handlers {
if _, err := h.fn(ctx, ev); err != nil {
errs = append(errs, fmt.Errorf("%s: %w", h.name, err))
}
}
}
return errors.Join(errs...)
}package eventbus
import (
"context"
"errors"
"testing"
"academy/domain-events-integration-events/sales"
)
func TestDispatchRoutesByTypeAndKeepsGoingOnError(t *testing.T) {
var b Bus
var seen []string
Subscribe(&b, "fails", func(context.Context, sales.OrderPlaced) error {
seen = append(seen, "fails")
return errors.New("smtp down")
})
Subscribe(&b, "loyalty", func(context.Context, sales.OrderPlaced) error {
seen = append(seen, "loyalty")
return nil
})
Subscribe(&b, "cancel-only", func(context.Context, sales.OrderCancelled) error {
seen = append(seen, "cancel-only")
return nil
})
err := b.Dispatch(context.Background(), []sales.Event{sales.OrderPlaced{OrderID: "o-1"}})
if err == nil {
t.Fatal("want the handler error to be reported")
}
if len(seen) != 2 || seen[0] != "fails" || seen[1] != "loyalty" {
t.Fatalf("unexpected handler calls %v", seen)
}
}The published language and the translator
// Package contracts is Sales' PUBLISHED LANGUAGE: the integration events other
// bounded contexts may depend on. Sales owns these types; changing them is a
// contract change (new version, deprecation window), not a refactoring.
package contracts
import (
"encoding/json"
"time"
)
// Envelope follows the CloudEvents 1.0 attribute names in its JSON form
// (specversion, id, source, type, subject, time, datacontenttype, data).
// correlationid and causationid are extension attributes (lower-case a-z0-9
// names, as the spec requires for extensions).
type Envelope struct {
SpecVersion string `json:"specversion"`
ID string `json:"id"`
Source string `json:"source"`
Type string `json:"type"`
Subject string `json:"subject,omitempty"`
Time time.Time `json:"time"`
DataContentType string `json:"datacontenttype"`
CorrelationID string `json:"correlationid,omitempty"`
CausationID string `json:"causationid,omitempty"`
Data json.RawMessage `json:"data"`
}
// Event types are the contract names: <context>.<entity>.<fact>.v<major>.
const (
TypeOrderPlacedV1 = "sales.order.placed.v1"
TypeOrderPlacedV2 = "sales.order.placed.v2"
TypeOrderCancelledV1 = "sales.order.cancelled.v1"
SourceSales = "/sales"
)
// LineV1 is one order line as other contexts see it.
type LineV1 struct {
SKU string `json:"sku"`
Quantity int `json:"quantity"`
}
// OrderPlacedV1 is the payload of sales.order.placed.v1. It is enriched for
// its consumers: Fulfilment needs lines and the shipping country, Billing
// needs the total. It does NOT carry Sales' internal status or line prices.
type OrderPlacedV1 struct {
OrderID string `json:"orderId"`
CustomerID string `json:"customerId"`
TotalMinor int64 `json:"totalMinor"`
Currency string `json:"currency"`
ShippingCountry string `json:"shippingCountry"`
Lines []LineV1 `json:"lines"`
PlacedAt string `json:"placedAt"`
}
// OrderPlacedV2 changes the money shape (a breaking change), so it is a new
// type published side by side with v1 during the migration window.
type OrderPlacedV2 struct {
OrderID string `json:"orderId"`
CustomerID string `json:"customerId"`
Total MoneyV2 `json:"total"`
ShippingCountry string `json:"shippingCountry"`
Lines []LineV1 `json:"lines"`
PlacedAt string `json:"placedAt"`
}
// MoneyV2 is the v2 money shape.
type MoneyV2 struct {
Amount string `json:"amount"` // decimal string, e.g. "30.00"
Currency string `json:"currency"`
}
// OrderCancelledV1 is the payload of sales.order.cancelled.v1.
type OrderCancelledV1 struct {
OrderID string `json:"orderId"`
RefundDue bool `json:"refundDue"`
CancelledAt string `json:"cancelledAt"`
}// Package translate is the anti-corruption layer on the way OUT of Sales.
// It maps domain events (internal model, free to change) to integration
// events (published language, versioned). One domain event may yield zero,
// one or many integration events.
package translate
import (
"context"
"encoding/json"
"fmt"
"time"
"academy/domain-events-integration-events/contracts"
"academy/domain-events-integration-events/sales"
)
// Directory is Sales-local data used for enrichment, read in the same
// transaction as the aggregate so the integration event is self-contained.
type Directory interface {
ShippingCountry(ctx context.Context, id sales.CustomerID) (string, error)
}
// Meta carries tracing identities from the command that caused the events.
type Meta struct {
CorrelationID string // the whole business flow (e.g. the checkout request)
CausationID string // the message or command that directly caused this one
}
// Translator turns domain events into CloudEvents-shaped envelopes.
type Translator struct {
Dir Directory
NewID func() string
PublishV2Too bool // dual-publish during a v1 -> v2 migration window
}
// Translate returns the integration events for one domain event.
func (t Translator) Translate(ctx context.Context, ev sales.Event, m Meta) ([]contracts.Envelope, error) {
switch e := ev.(type) {
case sales.OrderPlaced:
country, err := t.Dir.ShippingCountry(ctx, e.CustomerID)
if err != nil {
return nil, fmt.Errorf("enrich OrderPlaced: %w", err)
}
lines := make([]contracts.LineV1, len(e.Lines))
for i, l := range e.Lines {
lines[i] = contracts.LineV1{SKU: string(l.SKU), Quantity: l.Quantity}
}
v1 := contracts.OrderPlacedV1{
OrderID: string(e.OrderID), CustomerID: string(e.CustomerID),
TotalMinor: e.Total.Minor, Currency: e.Total.Currency,
ShippingCountry: country, Lines: lines, PlacedAt: e.At.Format(time.RFC3339),
}
out := []contracts.Envelope{t.wrap(contracts.TypeOrderPlacedV1, string(e.OrderID), e.At, m, v1)}
if t.PublishV2Too {
v2 := contracts.OrderPlacedV2{
OrderID: v1.OrderID, CustomerID: v1.CustomerID,
Total: contracts.MoneyV2{Amount: decimal(e.Total.Minor), Currency: e.Total.Currency},
ShippingCountry: country, Lines: lines, PlacedAt: v1.PlacedAt,
}
out = append(out, t.wrap(contracts.TypeOrderPlacedV2, string(e.OrderID), e.At, m, v2))
}
return out, nil
case sales.OrderCancelled:
p := contracts.OrderCancelledV1{OrderID: string(e.OrderID), RefundDue: e.RefundDue, CancelledAt: e.At.Format(time.RFC3339)}
return []contracts.Envelope{t.wrap(contracts.TypeOrderCancelledV1, string(e.OrderID), e.At, m, p)}, nil
case sales.OrderLineRepriced:
return nil, nil // internal to Sales: nothing is published
default:
return nil, fmt.Errorf("no translation rule for %T", ev)
}
}
// TranslateAll translates a batch, preserving the aggregate's recording order.
func (t Translator) TranslateAll(ctx context.Context, evs []sales.Event, m Meta) ([]contracts.Envelope, error) {
var out []contracts.Envelope
for _, ev := range evs {
envs, err := t.Translate(ctx, ev, m)
if err != nil {
return nil, err
}
out = append(out, envs...)
}
return out, nil
}
func (t Translator) wrap(typ, subject string, at time.Time, m Meta, payload any) contracts.Envelope {
data, _ := json.Marshal(payload) // contract structs always marshal
return contracts.Envelope{
SpecVersion: "1.0", ID: t.NewID(), Source: contracts.SourceSales, Type: typ,
Subject: subject, Time: at.UTC(), DataContentType: "application/json",
CorrelationID: m.CorrelationID, CausationID: m.CausationID, Data: data,
}
}
func decimal(minor int64) string { return fmt.Sprintf("%d.%02d", minor/100, minor%100) }package translate
import (
"context"
"encoding/json"
"fmt"
"testing"
"time"
"academy/domain-events-integration-events/contracts"
"academy/domain-events-integration-events/sales"
)
type fixedDir string
func (d fixedDir) ShippingCountry(context.Context, sales.CustomerID) (string, error) {
return string(d), nil
}
func newTranslator(v2 bool) Translator {
n := 0
return Translator{Dir: fixedDir("DE"), PublishV2Too: v2, NewID: func() string { n++; return fmt.Sprintf("evt-%d", n) }}
}
var at = time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)
func placed() sales.OrderPlaced {
return sales.OrderPlaced{
OrderID: "o-42", CustomerID: "c-7", At: at,
Total: sales.Money{Minor: 3000, Currency: "EUR"},
Lines: []sales.PlacedLine{{SKU: "sku-1", Quantity: 2, UnitPrice: sales.Money{Minor: 1500, Currency: "EUR"}}},
}
}
func TestZeroOneOrMany(t *testing.T) {
tests := []struct {
name string
ev sales.Event
v2 bool
want []string
}{
{"internal event publishes nothing", sales.OrderLineRepriced{OrderID: "o-42"}, false, nil},
{"placed publishes v1", placed(), false, []string{contracts.TypeOrderPlacedV1}},
{"placed dual-publishes during migration", placed(), true, []string{contracts.TypeOrderPlacedV1, contracts.TypeOrderPlacedV2}},
{"cancelled publishes v1", sales.OrderCancelled{OrderID: "o-42", At: at}, false, []string{contracts.TypeOrderCancelledV1}},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
envs, err := newTranslator(tc.v2).Translate(context.Background(), tc.ev, Meta{CorrelationID: "req-1"})
if err != nil {
t.Fatal(err)
}
if len(envs) != len(tc.want) {
t.Fatalf("want %v, got %d envelopes", tc.want, len(envs))
}
for i, e := range envs {
if e.Type != tc.want[i] || e.SpecVersion != "1.0" || e.Source != "/sales" || e.CorrelationID != "req-1" {
t.Fatalf("bad envelope %+v", e)
}
}
})
}
}
func TestPlacedV1IsEnrichedAndHidesInternals(t *testing.T) {
envs, _ := newTranslator(false).Translate(context.Background(), placed(), Meta{})
var raw map[string]any
if err := json.Unmarshal(envs[0].Data, &raw); err != nil {
t.Fatal(err)
}
if raw["shippingCountry"] != "DE" {
t.Fatalf("want enrichment, got %v", raw)
}
if _, leaked := raw["status"]; leaked {
t.Fatal("internal status must not leak into the contract")
}
lines := raw["lines"].([]any)
if _, leaked := lines[0].(map[string]any)["unitPrice"]; leaked {
t.Fatal("line prices are not part of v1")
}
}Transaction, outbox and the application service
// Package memdb is an in-memory stand-in for one PostgreSQL database holding
// Sales' orders table and its outbox table. A transaction stages writes and
// applies them all on commit, or none on rollback, which is the property the
// outbox relies on.
package memdb
import (
"context"
"sync"
"academy/domain-events-integration-events/contracts"
"academy/domain-events-integration-events/sales"
)
// OutboxRow mirrors one row of the outbox table.
type OutboxRow struct {
Seq int64
Envelope contracts.Envelope
Published bool
}
// DB is the whole "database".
type DB struct {
mu sync.Mutex
orders map[sales.OrderID]sales.Status
outbox []OutboxRow
nextSeq int64
country map[sales.CustomerID]string
}
// New returns an empty database with a customer directory for enrichment.
func New(country map[sales.CustomerID]string) *DB {
return &DB{orders: map[sales.OrderID]sales.Status{}, country: country}
}
// Tx stages writes until commit.
type Tx struct {
db *DB
orders map[sales.OrderID]sales.Status
outbox []contracts.Envelope
}
// SaveOrder stages the order row.
func (tx *Tx) SaveOrder(o *sales.Order) error { tx.orders[o.ID()] = o.Status(); return nil }
// AppendOutbox stages outbox rows in the same transaction as the order.
func (tx *Tx) AppendOutbox(envs []contracts.Envelope) error {
tx.outbox = append(tx.outbox, envs...)
return nil
}
// ShippingCountry reads Sales-local data inside the transaction.
func (tx *Tx) ShippingCountry(_ context.Context, id sales.CustomerID) (string, error) {
return tx.db.country[id], nil
}
// InTx runs fn; a nil error commits every staged write, any error discards all.
func (db *DB) InTx(_ context.Context, fn func(*Tx) error) error {
tx := &Tx{db: db, orders: map[sales.OrderID]sales.Status{}}
if err := fn(tx); err != nil {
return err // ROLLBACK: nothing staged becomes visible
}
db.mu.Lock()
defer db.mu.Unlock()
for id, st := range tx.orders {
db.orders[id] = st
}
for _, e := range tx.outbox {
db.nextSeq++
db.outbox = append(db.outbox, OutboxRow{Seq: db.nextSeq, Envelope: e})
}
return nil // COMMIT
}
// OrderStatus reads a committed order.
func (db *DB) OrderStatus(id sales.OrderID) (sales.Status, bool) {
db.mu.Lock()
defer db.mu.Unlock()
st, ok := db.orders[id]
return st, ok
}
// Unpublished returns committed, unpublished outbox rows in sequence order.
func (db *DB) Unpublished(limit int) []OutboxRow {
db.mu.Lock()
defer db.mu.Unlock()
var out []OutboxRow
for _, r := range db.outbox {
if !r.Published && len(out) < limit {
out = append(out, r)
}
}
return out
}
// MarkPublished flags a row after the broker confirmed it.
func (db *DB) MarkPublished(seq int64) {
db.mu.Lock()
defer db.mu.Unlock()
for i := range db.outbox {
if db.outbox[i].Seq == seq {
db.outbox[i].Published = true
}
}
}
// OutboxLen counts all committed outbox rows.
func (db *DB) OutboxLen() int {
db.mu.Lock()
defer db.mu.Unlock()
return len(db.outbox)
}// Package app is Sales' application layer. The order of operations is the
// point of this file: raise (in the aggregate) -> collect -> translate and
// write the outbox (inside the transaction) -> commit -> dispatch in-process.
package app
import (
"context"
"log/slog"
"time"
"academy/domain-events-integration-events/eventbus"
"academy/domain-events-integration-events/memdb"
"academy/domain-events-integration-events/sales"
"academy/domain-events-integration-events/translate"
)
// Line is one requested line of the PlaceOrder command.
type Line struct {
SKU sales.SKU
Quantity int
Price sales.Money
}
// PlaceOrder is the command.
type PlaceOrder struct {
CommandID string // also the causation id of the events it produces
RequestID string // correlation id of the whole checkout flow
OrderID sales.OrderID
CustomerID sales.CustomerID
Currency string
Lines []Line
}
// Service places orders.
type Service struct {
DB *memdb.DB
Bus *eventbus.Bus
NewID func() string
Clock func() time.Time
Logger *slog.Logger
V2Too bool
}
// Place runs one business transaction.
func (s Service) Place(ctx context.Context, cmd PlaceOrder) error {
order := sales.NewDraft(cmd.OrderID, cmd.CustomerID, cmd.Currency)
for _, l := range cmd.Lines {
order.AddLine(l.SKU, l.Quantity, l.Price)
}
err := s.DB.InTx(ctx, func(tx *memdb.Tx) error {
if err := order.Place(s.Clock()); err != nil { // 1. raise: recorded, not dispatched
return err
}
if err := tx.SaveOrder(order); err != nil { // 2. persist the aggregate
return err
}
tr := translate.Translator{Dir: tx, NewID: s.NewID, PublishV2Too: s.V2Too}
envs, err := tr.TranslateAll(ctx, order.PendingEvents(), // 3. collect + translate at the edge
translate.Meta{CorrelationID: cmd.RequestID, CausationID: cmd.CommandID})
if err != nil {
return err
}
return tx.AppendOutbox(envs) // 4. same transaction as the order row
})
if err != nil {
return err // rollback: no order row, no outbox row, nothing dispatched
}
// 5. after COMMIT: in-process listeners of the same context.
events := order.PendingEvents()
order.MarkCommitted()
if derr := s.Bus.Dispatch(ctx, events); derr != nil {
// The order IS placed. A failed side effect is logged and retried by
// its own mechanism; it never turns a committed fact into an error.
s.Logger.Warn("domain event handler failed", "order", cmd.OrderID, "err", derr)
}
return nil
}package app
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"testing"
"time"
"academy/domain-events-integration-events/eventbus"
"academy/domain-events-integration-events/loyalty"
"academy/domain-events-integration-events/memdb"
"academy/domain-events-integration-events/sales"
)
func newService(db *memdb.DB, bus *eventbus.Bus) Service {
n := 0
return Service{
DB: db, Bus: bus,
NewID: func() string { n++; return fmt.Sprintf("evt-%d", n) },
Clock: func() time.Time { return time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC) },
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
}
}
func cmd(lines ...Line) PlaceOrder {
return PlaceOrder{CommandID: "cmd-1", RequestID: "req-1", OrderID: "o-42", CustomerID: "c-7", Currency: "EUR", Lines: lines}
}
var oneLine = Line{SKU: "sku-1", Quantity: 2, Price: sales.Money{Minor: 1500, Currency: "EUR"}}
func TestPlaceCommitsOrderAndOutboxThenDispatches(t *testing.T) {
db := memdb.New(map[sales.CustomerID]string{"c-7": "DE"})
var bus eventbus.Bus
ledger := loyalty.NewLedger()
sawCommitted := false
eventbus.Subscribe(&bus, "loyalty", ledger.OnOrderPlaced)
eventbus.Subscribe(&bus, "probe", func(_ context.Context, e sales.OrderPlaced) error {
_, sawCommitted = db.OrderStatus(e.OrderID) // runs after COMMIT
return nil
})
if err := newService(db, &bus).Place(context.Background(), cmd(oneLine)); err != nil {
t.Fatal(err)
}
if !sawCommitted {
t.Fatal("handlers must run after the order is committed")
}
if got := ledger.Reserved("o-42"); got != 30 {
t.Fatalf("want 30 points, got %d", got)
}
rows := db.Unpublished(10)
if len(rows) != 1 || rows[0].Envelope.Type != "sales.order.placed.v1" || rows[0].Envelope.CausationID != "cmd-1" {
t.Fatalf("unexpected outbox %+v", rows)
}
}
func TestRollbackMeansNoOutboxAndNoDispatch(t *testing.T) {
db := memdb.New(nil)
var bus eventbus.Bus
called := false
eventbus.Subscribe(&bus, "probe", func(context.Context, sales.OrderPlaced) error { called = true; return nil })
err := newService(db, &bus).Place(context.Background(), cmd()) // no lines: Place fails
if !errors.Is(err, sales.ErrEmptyOrder) {
t.Fatalf("want ErrEmptyOrder, got %v", err)
}
if _, ok := db.OrderStatus("o-42"); ok || db.OutboxLen() != 0 || called {
t.Fatal("a rolled-back transaction must leave no order, no outbox row and no dispatch")
}
}
func TestFailingHandlerDoesNotUndoTheFact(t *testing.T) {
db := memdb.New(nil)
var bus eventbus.Bus
eventbus.Subscribe(&bus, "email", func(context.Context, sales.OrderPlaced) error { return errors.New("smtp down") })
if err := newService(db, &bus).Place(context.Background(), cmd(oneLine)); err != nil {
t.Fatalf("the order is placed even if an email fails: %v", err)
}
if st, _ := db.OrderStatus("o-42"); st != sales.Placed {
t.Fatalf("want placed, got %q", st)
}
}The PostgreSQL version of the outbox write and the relay claim, with database/sql:
package outbox
import (
"context"
"database/sql"
"encoding/json"
"academy/domain-events-integration-events/contracts"
)
// InsertTx writes envelopes into the outbox table inside the caller's
// transaction (PostgreSQL syntax). The schema is on the chapter page.
func InsertTx(ctx context.Context, tx *sql.Tx, envs []contracts.Envelope) error {
const q = `INSERT INTO outbox (event_id, event_type, subject, correlation_id, payload)
VALUES ($1, $2, $3, $4, $5)`
for _, e := range envs {
body, err := json.Marshal(e)
if err != nil {
return err
}
if _, err := tx.ExecContext(ctx, q, e.ID, e.Type, e.Subject, e.CorrelationID, body); err != nil {
return err
}
}
return nil
}
// ClaimBatch locks a batch of unpublished rows so several relay instances can
// run without publishing the same row concurrently (PostgreSQL SKIP LOCKED).
// The caller publishes them and runs MarkPublishedTx in the same transaction.
func ClaimBatch(ctx context.Context, tx *sql.Tx, limit int) ([]contracts.Envelope, []int64, error) {
rows, err := tx.QueryContext(ctx, `SELECT seq, payload FROM outbox
WHERE published_at IS NULL ORDER BY seq LIMIT $1 FOR UPDATE SKIP LOCKED`, limit)
if err != nil {
return nil, nil, err
}
defer rows.Close()
var envs []contracts.Envelope
var seqs []int64
for rows.Next() {
var seq int64
var body []byte
if err := rows.Scan(&seq, &body); err != nil {
return nil, nil, err
}
var e contracts.Envelope
if err := json.Unmarshal(body, &e); err != nil {
return nil, nil, err
}
envs, seqs = append(envs, e), append(seqs, seq)
}
return envs, seqs, rows.Err()
}
// MarkPublishedTx stamps published rows.
func MarkPublishedTx(ctx context.Context, tx *sql.Tx, seq int64) error {
_, err := tx.ExecContext(ctx, `UPDATE outbox SET published_at = now() WHERE seq = $1`, seq)
return err
}// Package outbox holds the relay that moves committed integration events from
// the outbox table to the broker. It is at-least-once: a crash between publish
// and mark re-publishes the row, so consumers must be idempotent.
package outbox
import (
"context"
"fmt"
"academy/domain-events-integration-events/contracts"
"academy/domain-events-integration-events/memdb"
)
// Publisher is the broker port. A Watermill message.Publisher, a franz-go
// producer or an amqp091 channel sits behind an adapter with this shape.
type Publisher interface {
Publish(ctx context.Context, topic string, e contracts.Envelope) error
}
// Store is the part of the database the relay needs.
type Store interface {
Unpublished(limit int) []memdb.OutboxRow
MarkPublished(seq int64)
}
// Relay is a polling publisher.
type Relay struct {
Store Store
Publisher Publisher
Batch int
}
// RunOnce publishes one batch in sequence order and stops at the first
// failure, so a later row never overtakes an earlier one for the same order.
func (r Relay) RunOnce(ctx context.Context) (int, error) {
n := 0
for _, row := range r.Store.Unpublished(r.Batch) {
// Topic per event type; the key for partitioning is the subject (order id).
if err := r.Publisher.Publish(ctx, row.Envelope.Type, row.Envelope); err != nil {
return n, fmt.Errorf("publish seq %d: %w", row.Seq, err)
}
r.Store.MarkPublished(row.Seq)
n++
}
return n, nil
}Listeners and consumers
// Package loyalty is a module INSIDE Sales (same bounded context, its own
// aggregate). It reacts to OrderPlaced eventually, in a separate step from the
// order's transaction: one transaction, one aggregate.
package loyalty
import (
"context"
"sync"
"academy/domain-events-integration-events/sales"
)
// Ledger holds reserved points per order; reservation is idempotent by order id.
type Ledger struct {
mu sync.Mutex
reserved map[sales.OrderID]int64
}
// NewLedger returns an empty ledger.
func NewLedger() *Ledger { return &Ledger{reserved: map[sales.OrderID]int64{}} }
// OnOrderPlaced reserves one point per full currency unit.
func (l *Ledger) OnOrderPlaced(_ context.Context, e sales.OrderPlaced) error {
l.mu.Lock()
defer l.mu.Unlock()
if _, done := l.reserved[e.OrderID]; done {
return nil // a re-delivered event changes nothing
}
l.reserved[e.OrderID] = e.Total.Minor / 100
return nil
}
// Reserved returns the points reserved for an order.
func (l *Ledger) Reserved(id sales.OrderID) int64 {
l.mu.Lock()
defer l.mu.Unlock()
return l.reserved[id]
}// Package fulfilment consumes Sales' published language. It never imports
// the sales package: it depends only on the contract (JSON shape + type name).
package fulfilment
import (
"context"
"encoding/json"
"fmt"
"sync"
"academy/domain-events-integration-events/contracts"
)
// WorkOrder is Fulfilment's own model of "an order": lines to pick and pack.
type WorkOrder struct {
SalesOrderID string
Country string
PickLines map[string]int
}
// Consumer handles integration events with an inbox for de-duplication.
type Consumer struct {
mu sync.Mutex
inbox map[string]bool // key: source + "/" + id (CloudEvents duplicate rule)
WorkOrders map[string]WorkOrder
Released int // work orders released to the warehouse floor (a non-idempotent effect)
}
// NewConsumer returns an empty consumer.
func NewConsumer() *Consumer {
return &Consumer{inbox: map[string]bool{}, WorkOrders: map[string]WorkOrder{}}
}
// Handle is idempotent: a duplicate delivery is acknowledged and ignored.
func (c *Consumer) Handle(_ context.Context, e contracts.Envelope) error {
c.mu.Lock()
defer c.mu.Unlock()
key := e.Source + "/" + e.ID
if c.inbox[key] {
return nil
}
switch e.Type {
case contracts.TypeOrderPlacedV1:
var p contracts.OrderPlacedV1
if err := json.Unmarshal(e.Data, &p); err != nil {
return fmt.Errorf("poison message %s: %w", e.ID, err) // to the DLQ
}
wo := WorkOrder{SalesOrderID: p.OrderID, Country: p.ShippingCountry, PickLines: map[string]int{}}
for _, l := range p.Lines {
wo.PickLines[l.SKU] += l.Quantity
}
c.WorkOrders[p.OrderID] = wo
c.Released++ // e.g. a pick list printed: repeating it is visible
case contracts.TypeOrderCancelledV1:
var p contracts.OrderCancelledV1
if err := json.Unmarshal(e.Data, &p); err != nil {
return fmt.Errorf("poison message %s: %w", e.ID, err)
}
delete(c.WorkOrders, p.OrderID)
default:
// Unknown types and versions (e.g. sales.order.placed.v2 before we
// migrate) are ignored, not failed: tolerant reader.
}
c.inbox[key] = true
return nil
}package fulfilment
import (
"context"
"encoding/json"
"testing"
"academy/domain-events-integration-events/contracts"
)
func envelope(id, typ string, payload any) contracts.Envelope {
b, _ := json.Marshal(payload)
return contracts.Envelope{SpecVersion: "1.0", ID: id, Source: "/sales", Type: typ, Data: b}
}
func TestDuplicateDeliveryIsIgnored(t *testing.T) {
c := NewConsumer()
e := envelope("evt-1", contracts.TypeOrderPlacedV1, contracts.OrderPlacedV1{
OrderID: "o-42", ShippingCountry: "DE", Lines: []contracts.LineV1{{SKU: "sku-1", Quantity: 2}},
})
for range 2 { // at-least-once: the relay re-sent it
if err := c.Handle(context.Background(), e); err != nil {
t.Fatal(err)
}
}
if got := c.WorkOrders["o-42"].PickLines["sku-1"]; got != 2 {
t.Fatalf("want 2 to pick, got %d", got)
}
if c.Released != 1 {
t.Fatalf("want 1 work order released, got %d", c.Released)
}
}
func TestUnknownVersionIsToleratedNotFailed(t *testing.T) {
c := NewConsumer()
e := envelope("evt-2", contracts.TypeOrderPlacedV2, map[string]string{"orderId": "o-42"})
if err := c.Handle(context.Background(), e); err != nil {
t.Fatalf("tolerant reader: %v", err)
}
if len(c.WorkOrders) != 0 {
t.Fatal("v2 is not consumed yet")
}
}
func TestPoisonMessageFails(t *testing.T) {
c := NewConsumer()
e := contracts.Envelope{ID: "evt-3", Source: "/sales", Type: contracts.TypeOrderPlacedV1, Data: []byte("{not json")}
if err := c.Handle(context.Background(), e); err == nil {
t.Fatal("malformed payload must be rejected (DLQ)")
}
}What not to do
// Package wrong shows designs this chapter argues against. They compile and
// they even work in a demo; they fail in production.
package wrong
import (
"context"
"database/sql"
"encoding/json"
)
// Order is a stand-in for an Eloquent-style active record.
type Order struct {
ID string
Status string
Total int64
Internal map[string]string
}
// Broker publishes raw bytes.
type Broker interface {
Publish(ctx context.Context, topic string, body []byte) error
}
// OrderUpdated is a CRUD event: it says a row changed, not what happened, and
// it carries the whole aggregate (internal fields included) to other services.
type OrderUpdated struct{ Order *Order }
// PlaceBeforeCommit publishes to the broker INSIDE the transaction. If COMMIT
// fails, Fulfilment ships an order that does not exist; if the broker is down,
// the customer's checkout fails for an infrastructure reason.
func PlaceBeforeCommit(ctx context.Context, db *sql.DB, b Broker, o *Order) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
if _, err := tx.ExecContext(ctx, `UPDATE orders SET status = 'placed' WHERE id = $1`, o.ID); err != nil {
return err
}
body, _ := json.Marshal(OrderUpdated{Order: o}) // whole aggregate on the wire
if err := b.Publish(ctx, "orders", body); err != nil {
return err
}
return tx.Commit() // may still fail after the world was told
}
// PlaceAfterCommitNoOutbox is better but still loses events: a crash or a
// broker outage between COMMIT and Publish drops the message forever.
func PlaceAfterCommitNoOutbox(ctx context.Context, db *sql.DB, b Broker, o *Order) error {
if _, err := db.ExecContext(ctx, `UPDATE orders SET status = 'placed' WHERE id = $1`, o.ID); err != nil {
return err
}
// <- process killed here: the order is placed, nobody is ever told
body, _ := json.Marshal(map[string]string{"orderId": o.ID})
return b.Publish(ctx, "sales.order.placed.v1", body)
}The demo
// Command demo runs the whole OrderPlaced flow in one process and prints the
// timeline: raise, translate, commit, in-process dispatch, relay, consumers,
// a duplicate delivery, and a rolled-back command.
package main
import (
"context"
"fmt"
"log/slog"
"os"
"time"
"academy/domain-events-integration-events/app"
"academy/domain-events-integration-events/contracts"
"academy/domain-events-integration-events/eventbus"
"academy/domain-events-integration-events/fulfilment"
"academy/domain-events-integration-events/loyalty"
"academy/domain-events-integration-events/memdb"
"academy/domain-events-integration-events/outbox"
"academy/domain-events-integration-events/sales"
)
// fanout is a toy broker: every subscriber gets every message.
type fanout struct {
subs []func(context.Context, contracts.Envelope) error
}
func (f *fanout) Publish(ctx context.Context, topic string, e contracts.Envelope) error {
fmt.Printf(" broker <- %s id=%s subject=%s correlation=%s\n", topic, e.ID, e.Subject, e.CorrelationID)
for _, s := range f.subs {
if err := s(ctx, e); err != nil {
return err
}
}
return nil
}
func main() {
ctx := context.Background()
db := memdb.New(map[sales.CustomerID]string{"c-7": "DE"})
var bus eventbus.Bus
ledger := loyalty.NewLedger()
eventbus.Subscribe(&bus, "loyalty", func(ctx context.Context, e sales.OrderPlaced) error {
fmt.Printf(" in-proc -> loyalty reserves points for %s\n", e.OrderID)
return ledger.OnOrderPlaced(ctx, e)
})
n := 0
svc := app.Service{
DB: db, Bus: &bus,
NewID: func() string { n++; return fmt.Sprintf("evt-%d", n) },
Clock: func() time.Time { return time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC) },
Logger: slog.New(slog.NewTextHandler(os.Stdout, nil)),
}
ful := fulfilment.NewConsumer()
billed := map[string]int64{}
broker := &fanout{subs: []func(context.Context, contracts.Envelope) error{
ful.Handle,
func(_ context.Context, e contracts.Envelope) error { // Billing, minimal
if e.Type == contracts.TypeOrderPlacedV1 {
billed[e.Subject]++
}
return nil
},
}}
relay := outbox.Relay{Store: db, Publisher: broker, Batch: 100}
fmt.Println("1. PlaceOrder o-42")
err := svc.Place(ctx, app.PlaceOrder{
CommandID: "cmd-1", RequestID: "req-1", OrderID: "o-42", CustomerID: "c-7", Currency: "EUR",
Lines: []app.Line{{SKU: "sku-1", Quantity: 2, Price: sales.Money{Minor: 1500, Currency: "EUR"}}},
})
st, _ := db.OrderStatus("o-42")
fmt.Printf(" committed: order=%s outbox rows=%d err=%v\n", st, db.OutboxLen(), err)
fmt.Println("2. Relay publishes the outbox")
published, _ := relay.RunOnce(ctx)
fmt.Printf(" published=%d workOrder=%v\n", published, ful.WorkOrders["o-42"].PickLines)
fmt.Println("3. Broker re-delivers the same message (at-least-once)")
rows := db.Unpublished(1)
fmt.Printf(" unpublished rows left=%d\n", len(rows))
dup := contracts.Envelope{SpecVersion: "1.0", ID: "evt-1", Source: "/sales", Type: contracts.TypeOrderPlacedV1}
_ = ful.Handle(ctx, dup)
fmt.Printf(" work orders=%d (unchanged), loyalty points=%d\n", len(ful.WorkOrders), ledger.Reserved("o-42"))
fmt.Println("4. PlaceOrder o-43 with no lines")
err = svc.Place(ctx, app.PlaceOrder{CommandID: "cmd-2", RequestID: "req-2", OrderID: "o-43", CustomerID: "c-7", Currency: "EUR"})
_, exists := db.OrderStatus("o-43")
fmt.Printf(" rolled back: err=%q order exists=%v outbox rows=%d\n", err, exists, db.OutboxLen())
}The Go angle
- No framework is needed for domain events. A
[]Eventon the aggregate,PendingEvents()andMarkCommitted()(the same vocabulary as Aggregates & Factories), and a typedSubscribe[E]using generics cover in-process dispatch. - Return values make timing explicit.
InTxreturns an error; the application service dispatches only on nil. There is no hidden "after commit" hook to forget. - Watermill is the common library when events go over a Pub/Sub: its CQRS component "lets you work with Go structs instead of messages" with
EventBusandEventProcessor, and its Forwarder is described as "a background running daemon which awaits messages that are published to a database, and makes sure they eventually reach a message broker". Its Go Channel Pub/Sub can serve as an in-process bus; keep domain events on it only if you accept that it is not transactional. - Brokers:
github.com/rabbitmq/amqp091-go,github.com/twmb/franz-go/pkg/kgo,github.com/redis/go-redis/v9behind thePublisherport; see Event-Driven Go. - Tests assert recorded events directly on the aggregate (
PendingEvents()), the translator with table tests (zero, one, many), and the application service with a fake database that really rolls back.
Laravel
The Laravel version keeps the aggregate as plain PHP (persisted by a repository, see Repositories), dispatches domain events through Laravel's event dispatcher after DB::transaction returns, and writes integration events to the outbox inside the transaction.
Domain events and the aggregate
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
/**
* Aggregates record domain events; they never dispatch them. The application
* service releases them after the transaction commits.
*/
trait RecordsDomainEvents
{
/** @var list<object> */
private array $recordedEvents = [];
protected function record(object $event): void
{
$this->recordedEvents[] = $event;
}
/** @return list<object> */
public function releaseEvents(): array
{
$events = $this->recordedEvents;
$this->recordedEvents = [];
return $events;
}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain\Events;
use DateTimeImmutable;
/**
* Domain event: past tense, immutable (readonly), ids and values only.
* No wire name, no version, no Eloquent model inside: it never leaves Sales.
*/
final readonly class OrderPlaced
{
/** @param list<array{sku: string, quantity: int, unitPriceMinor: int}> $lines */
public function __construct(
public string $orderId,
public string $customerId,
public int $totalMinor,
public string $currency,
public array $lines,
public DateTimeImmutable $occurredAt,
) {}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain\Events;
use DateTimeImmutable;
/** Internal to Sales: the translator publishes nothing for it. */
final readonly class OrderLineRepriced
{
public function __construct(
public string $orderId,
public string $sku,
public int $oldPriceMinor,
public int $newPriceMinor,
public DateTimeImmutable $occurredAt,
) {}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
use App\Modules\Sales\Domain\Events\OrderPlaced;
use DateTimeImmutable;
use DomainException;
/** Aggregate root (plain PHP; persisted by a repository, not an Eloquent model). */
final class Order
{
use RecordsDomainEvents;
/** @var list<array{sku: string, quantity: int, unitPriceMinor: int}> */
private array $lines = [];
private string $status = 'draft';
public function __construct(
public readonly string $id,
public readonly string $customerId,
public readonly string $currency,
) {}
public function addLine(string $sku, int $quantity, int $unitPriceMinor): void
{
$this->lines[] = ['sku' => $sku, 'quantity' => $quantity, 'unitPriceMinor' => $unitPriceMinor];
}
public function place(DateTimeImmutable $now): void
{
if ($this->status !== 'draft') {
throw new DomainException('Only a draft order can be placed.');
}
if ($this->lines === []) {
throw new DomainException('An order needs at least one line.');
}
$this->status = 'placed';
$this->record(new OrderPlaced(
orderId: $this->id,
customerId: $this->customerId,
totalMinor: $this->totalMinor(),
currency: $this->currency,
lines: $this->lines, // arrays are copied by value in PHP
occurredAt: $now,
));
}
public function status(): string
{
return $this->status;
}
public function totalMinor(): int
{
return array_sum(array_map(
fn (array $l): int => $l['quantity'] * $l['unitPriceMinor'],
$this->lines,
));
}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
interface OrderRepository
{
public function save(Order $order): void;
}Application service: transaction, outbox, after-commit dispatch
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Application;
use App\Modules\Sales\Domain\Order;
use App\Modules\Sales\Domain\OrderRepository;
use App\Modules\Sales\Infrastructure\Outbox;
use App\Modules\Sales\Integration\IntegrationEventTranslator;
use DateTimeImmutable;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Support\Facades\DB;
/**
* Application service. Order of operations:
* raise (aggregate) -> save -> translate + outbox (same transaction) -> COMMIT -> dispatch in-process.
*/
final readonly class PlaceOrder
{
public function __construct(
private OrderRepository $orders,
private IntegrationEventTranslator $translator,
private Outbox $outbox,
private Dispatcher $events,
) {}
/** @param list<array{sku: string, quantity: int, unitPriceMinor: int}> $lines */
public function __invoke(
string $orderId,
string $customerId,
string $currency,
array $lines,
string $requestId,
string $commandId,
): void {
$order = new Order($orderId, $customerId, $currency);
foreach ($lines as $l) {
$order->addLine($l['sku'], $l['quantity'], $l['unitPriceMinor']);
}
$domainEvents = DB::transaction(function () use ($order, $requestId, $commandId): array {
$order->place(new DateTimeImmutable()); // raise: recorded, not dispatched
$this->orders->save($order);
$events = $order->releaseEvents(); // collect
$meta = ['correlation_id' => $requestId, 'causation_id' => $commandId];
foreach ($events as $event) {
$this->outbox->append($this->translator->translate($event, $meta));
}
return $events; // COMMIT happens when the closure returns
});
// After COMMIT: in-process listeners of the Sales context.
foreach ($domainEvents as $event) {
$this->events->dispatch($event);
}
}
}Queued listener inside Sales
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Listeners;
use App\Modules\Sales\Domain\Events\OrderPlaced;
use Illuminate\Contracts\Queue\ShouldQueueAfterCommit;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\DB;
/**
* Same bounded context, different aggregate (LoyaltyAccount): eventual
* consistency, its own transaction, idempotent by order id because a queued
* listener can run more than once.
*
* ShouldQueueAfterCommit: if someone dispatches OrderPlaced inside an open
* transaction, the job is only pushed after COMMIT.
*/
final class ReserveLoyaltyPoints implements ShouldQueueAfterCommit
{
use InteractsWithQueue;
public int $tries = 5;
public function handle(OrderPlaced $event): void
{
DB::table('loyalty_reservations')->insertOrIgnore([
'order_id' => $event->orderId, // unique key: replays insert nothing
'customer_id' => $event->customerId,
'points' => intdiv($event->totalMinor, 100),
'created_at' => now(),
]);
}
}Listeners outside app/Listeners are found by discovery when the paths are registered, as the docs show for app/Domain/*/Listeners: ->withEvents(discover: [__DIR__.'/../app/Modules/*/Listeners']) in bootstrap/app.php.
Integration event, translator, outbox, relay
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Integration;
/**
* Integration event: Sales' published language. Owned by Sales, versioned,
* consumed by Fulfilment and Billing. A breaking change means OrderPlacedV2.
*/
final readonly class OrderPlacedV1
{
public const string TYPE = 'sales.order.placed.v1';
public const int VERSION = 1;
/** @param list<array{sku: string, quantity: int}> $lines */
public function __construct(
public string $orderId,
public string $customerId,
public int $totalMinor,
public string $currency,
public string $shippingCountry,
public array $lines,
public string $placedAt,
) {}
/** @return array<string, mixed> */
public function toArray(): array
{
return get_object_vars($this);
}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Integration;
use App\Modules\Sales\Domain\Events\OrderLineRepriced;
use App\Modules\Sales\Domain\Events\OrderPlaced;
use DateTimeInterface;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use LogicException;
/**
* Anti-corruption layer on the way OUT: domain event -> zero, one or many
* CloudEvents-shaped envelopes. Runs inside the business transaction.
*/
final class IntegrationEventTranslator
{
/**
* @param array{correlation_id: string, causation_id: string} $meta
* @return list<array<string, mixed>>
*/
public function translate(object $event, array $meta): array
{
return match (true) {
$event instanceof OrderPlaced => [$this->envelope(
OrderPlacedV1::TYPE,
$event->orderId,
$event->occurredAt,
$meta,
new OrderPlacedV1(
orderId: $event->orderId,
customerId: $event->customerId,
totalMinor: $event->totalMinor,
currency: $event->currency,
shippingCountry: $this->shippingCountry($event->customerId), // enrichment
lines: array_map(
fn (array $l): array => ['sku' => $l['sku'], 'quantity' => $l['quantity']],
$event->lines,
),
placedAt: $event->occurredAt->format(DateTimeInterface::ATOM),
),
)],
$event instanceof OrderLineRepriced => [], // internal fact, nothing published
default => throw new LogicException('No translation rule for '.$event::class),
};
}
/** @param array{correlation_id: string, causation_id: string} $meta */
private function envelope(string $type, string $subject, DateTimeInterface $at, array $meta, OrderPlacedV1 $data): array
{
return [
'specversion' => '1.0',
'id' => (string) Str::uuid(),
'source' => '/sales',
'type' => $type,
'subject' => $subject,
'time' => $at->format(DateTimeInterface::ATOM),
'datacontenttype' => 'application/json',
'correlationid' => $meta['correlation_id'],
'causationid' => $meta['causation_id'],
'data' => $data->toArray(),
];
}
private function shippingCountry(string $customerId): string
{
// Sales' own copy of the checkout address, read in the same transaction.
return (string) DB::table('sales_checkout_addresses')
->where('customer_id', $customerId)
->value('country');
}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Infrastructure;
use Illuminate\Support\Facades\DB;
/** Writes integration events into the outbox table, inside the caller's transaction. */
final class Outbox
{
/** @param list<array<string, mixed>> $envelopes */
public function append(array $envelopes): void
{
foreach ($envelopes as $e) {
DB::table('outbox')->insert([
'event_id' => $e['id'],
'event_type' => $e['type'],
'subject' => $e['subject'],
'correlation_id' => $e['correlationid'],
'payload' => json_encode($e, JSON_THROW_ON_ERROR),
'created_at' => now(),
]);
}
}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Infrastructure;
/**
* Port to the broker. Adapters: vladimir-yuldashev/laravel-queue-rabbitmq,
* mateusjunges/laravel-kafka, or the Redis facade (XADD) — see the messaging path.
*/
interface BrokerPublisher
{
/** @param array<string, mixed> $envelope */
public function publish(string $topic, string $key, array $envelope): void;
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Infrastructure;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\DB;
/**
* Polling relay, scheduled every few seconds. At-least-once: a crash after
* publish and before the UPDATE re-publishes, so consumers de-duplicate by
* CloudEvents source + id. Full relay design: /messaging/outbox-pattern.
*/
final class RelayOutbox implements ShouldQueue, ShouldBeUnique
{
use Dispatchable, Queueable;
public function handle(BrokerPublisher $broker): void
{
DB::transaction(function () use ($broker): void {
$rows = DB::table('outbox')
->whereNull('published_at')
->orderBy('seq')
->limit(100)
->lock('for update skip locked') // raw lock clause, PostgreSQL / MySQL 8
->get();
foreach ($rows as $row) {
$envelope = json_decode($row->payload, true, flags: JSON_THROW_ON_ERROR);
$broker->publish(topic: $row->event_type, key: $row->subject, envelope: $envelope);
DB::table('outbox')->where('seq', $row->seq)->update(['published_at' => now()]);
}
});
}
}<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('outbox', function (Blueprint $table): void {
$table->id('seq');
$table->uuid('event_id')->unique();
$table->string('event_type');
$table->string('subject');
$table->string('correlation_id')->nullable();
$table->json('payload');
$table->timestamp('created_at');
$table->timestamp('published_at')->nullable()->index();
});
Schema::create('loyalty_reservations', function (Blueprint $table): void {
$table->string('order_id')->primary();
$table->string('customer_id');
$table->integer('points');
$table->timestamp('created_at');
});
Schema::create('sales_checkout_addresses', function (Blueprint $table): void {
$table->string('customer_id')->primary();
$table->string('country', 2);
});
}
public function down(): void
{
Schema::dropIfExists('sales_checkout_addresses');
Schema::dropIfExists('loyalty_reservations');
Schema::dropIfExists('outbox');
}
};Consumer in Fulfilment
<?php
declare(strict_types=1);
namespace App\Modules\Fulfilment\Integration;
use Illuminate\Support\Facades\DB;
/**
* Fulfilment's consumer. It depends on the CONTRACT (type + JSON shape),
* never on App\Modules\Sales classes. Inbox row and work order are written in
* one transaction, so a duplicate delivery changes nothing.
*/
final class HandleOrderPlacedV1
{
/** @param array<string, mixed> $envelope */
public function __invoke(array $envelope): void
{
if ($envelope['type'] !== 'sales.order.placed.v1') {
return; // tolerant reader: other types and versions are not ours (yet)
}
DB::transaction(function () use ($envelope): void {
$fresh = DB::table('fulfilment_inbox')->insertOrIgnore([
'message_key' => $envelope['source'].'/'.$envelope['id'],
'received_at' => now(),
]);
if ($fresh === 0) {
return; // duplicate: already handled
}
$data = $envelope['data'];
$workOrderId = DB::table('work_orders')->insertGetId([
'sales_order_id' => $data['orderId'],
'country' => $data['shippingCountry'],
'status' => 'released',
'created_at' => now(),
]);
foreach ($data['lines'] as $line) {
DB::table('pick_lines')->insert([
'work_order_id' => $workOrderId,
'sku' => $line['sku'],
'quantity' => $line['quantity'],
]);
}
});
}
}Tests
<?php
declare(strict_types=1);
use App\Modules\Sales\Domain\Events\OrderPlaced;
use App\Modules\Sales\Domain\Order;
it('records OrderPlaced when a draft is placed', function () {
$order = new Order('o-42', 'c-7', 'EUR');
$order->addLine('sku-1', 2, 1500);
$order->place(new DateTimeImmutable('2026-11-25T10:00:00Z'));
$events = $order->releaseEvents();
expect($events)->toHaveCount(1)
->and($events[0])->toBeInstanceOf(OrderPlaced::class)
->and($events[0]->totalMinor)->toBe(3000)
->and($order->releaseEvents())->toBe([]); // released once
});
it('records nothing when the command is rejected', function () {
$order = new Order('o-43', 'c-7', 'EUR');
expect(fn () => $order->place(new DateTimeImmutable()))->toThrow(DomainException::class)
->and($order->releaseEvents())->toBe([]);
});<?php
declare(strict_types=1);
use App\Modules\Sales\Application\PlaceOrder;
use App\Modules\Sales\Domain\Events\OrderPlaced;
use App\Modules\Sales\Domain\Order;
use App\Modules\Sales\Domain\OrderRepository;
use App\Modules\Sales\Listeners\ReserveLoyaltyPoints;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
uses(RefreshDatabase::class);
beforeEach(function () {
app()->instance(OrderRepository::class, new class implements OrderRepository
{
public function save(Order $order): void {}
});
DB::table('sales_checkout_addresses')->insert(['customer_id' => 'c-7', 'country' => 'DE']);
});
it('writes the integration event to the outbox and dispatches the domain event', function () {
Event::fake([OrderPlaced::class]);
app(PlaceOrder::class)('o-42', 'c-7', 'EUR', [['sku' => 'sku-1', 'quantity' => 2, 'unitPriceMinor' => 1500]], 'req-1', 'cmd-1');
Event::assertDispatched(fn (OrderPlaced $e) => $e->orderId === 'o-42' && $e->totalMinor === 3000);
$this->assertDatabaseHas('outbox', [
'event_type' => 'sales.order.placed.v1',
'subject' => 'o-42',
'correlation_id' => 'req-1',
]);
$payload = json_decode(DB::table('outbox')->value('payload'), true);
expect($payload['data'])->toHaveKey('shippingCountry', 'DE')
->and($payload['data']['lines'][0])->not->toHaveKey('unitPriceMinor'); // internals stay inside
});
it('leaves no outbox row and dispatches nothing when the command fails', function () {
Event::fake([OrderPlaced::class]);
expect(fn () => app(PlaceOrder::class)('o-43', 'c-7', 'EUR', [], 'req-2', 'cmd-2'))
->toThrow(DomainException::class);
Event::assertNotDispatched(OrderPlaced::class);
$this->assertDatabaseCount('outbox', 0);
});
it('wires the loyalty listener to OrderPlaced', function () {
Event::fake();
Event::assertListening(OrderPlaced::class, ReserveLoyaltyPoints::class);
});What not to do
<?php
declare(strict_types=1);
namespace App\Observers;
use App\Models\Order;
use Illuminate\Support\Facades\Redis;
/**
* Anti-pattern, three times over:
* 1. a CRUD event ("updated") instead of a business fact (placed? cancelled? repriced?);
* 2. the whole Eloquent model, internal columns included, is the "contract";
* 3. it publishes from inside the save, possibly before COMMIT, with no outbox.
* Mass updates (Order::where(...)->update()) do not fire it at all.
*/
final class OrderObserver
{
public function updated(Order $order): void
{
Redis::xadd('orders', '*', [
'type' => 'OrderUpdated',
'payload' => $order->toJson(),
]);
}
}The Laravel angle
- Events and listeners are generic dispatch. Laravel dispatches any object; the framework does not know whether it is a domain event, an integration event or a UI event. The namespaces (
Domain\Events,Integration) carry that meaning. - After commit, four ways.
ShouldDispatchAfterCommiton an event ("only dispatch an event after the active database transaction has committed"),ShouldQueueAfterCommiton a queued listener,after_commiton the queue connection, andShouldHandleEventsAfterCommiton an observer. The example dispatches afterDB::transactionreturns, which needs none of them;ShouldQueueAfterCommiton the listener protects against someone dispatching inside a transaction later. - Queued listeners are at-least-once.
$tries,failed()and the queue's retry make them run more than once: make them idempotent (unique key +insertOrIgnore). - Testing.
Event::fake([OrderPlaced::class])fakes only that event;Event::assertDispatchedwith a closure checks the payload;Event::assertNotDispatchedproves the rollback path;Event::assertListeningchecks wiring. The docs warn that afterEvent::fake()"no event listeners will be executed", so factories relying on model events should run first. - Model events stay technical. Use observers for UUIDs and cache busting, not for publishing business facts; mass updates do not fire them.
- Broadcasting (
ShouldBroadcast) is a separate output for browsers; a listener can broadcast anOrderStatusChangedUI event in reaction to a domain event. - Brokers. Laravel has no RabbitMQ or Kafka driver built in:
vladimir-yuldashev/laravel-queue-rabbitmq,mateusjunges/laravel-kafka, orRedis::xaddbehindBrokerPublisher; see Laravel Queue Internals and Testing Messaging Systems.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Side effects for rolled-back changes | Deferred dispatch after commit | Record in aggregate, dispatch when commit returned | No ghost emails | In-process reaction can be lost on crash |
| Lost messages after commit | Transactional outbox | Insert rows in the business tx, relay later | No loss, no ghost | Relay to run; at-least-once |
| Duplicate deliveries | Idempotent consumer | Inbox keyed by source + id, same tx as the effect | Safe redelivery | Inbox table, retention |
| Model changes break consumers | Translation at the edge | Separate contract types, versioned | Internal freedom | Mapping code to maintain |
| Consumers call back too much | Event-carried state transfer | Enrich the integration event | Resilience, lower latency | Bigger messages, data copies |
| CRUD events nobody understands | Business-named domain events | OrderCancelled raised by Order.Cancel | Self-explaining, fewer consumers' bugs | Requires a real domain model |
| Lost in a chain of events | Correlation and causation ids | Envelope extensions, logged | Traceable flows | Discipline at every hop |
| Breaking contract change | New major version + dual publish | .v1 and .v2 side by side, then retire v1 | No coordinated deploy | Two contracts for a while |
| Handler order assumptions | Order-independent handlers | Each handler reads its own data | Robust to reordering | Sometimes extra checks |
Problem 1: an email for an order that never existed
1 BEGIN
2 order.place(); Event::dispatch(new OrderPlaced(...)) -> SendConfirmation runs synchronously -> email sent
3 repo.save(order) -> unique violation on external_ref (SQLSTATE 23505)
4 ROLLBACK
5 Customer has a confirmation for an order that does not existFix: dispatch after the transaction returns (the example), or mark the event ShouldDispatchAfterCommit, or make the mailer listener ShouldQueueAfterCommit.
Problem 2: Billing broke when Sales renamed a field
Fix: introduce contracts.OrderPlacedV1 / OrderPlacedV1.php, translate in the application service, and add a contract test that decodes a golden JSON file of sales.order.placed.v1. Sales' domain event can then change in any commit.
Problem 3: the relay sends the same event twice
Fix: Fulfilment writes fulfilment_inbox(message_key) and the WorkOrder in one transaction; INSERT ... ON CONFLICT DO NOTHING returning 0 rows means duplicate (Go fulfilment/consumer.go, Laravel HandleOrderPlacedV1).
Problem 4: a migration to a new money shape
Fix: publish sales.order.placed.v2 next to v1 (PublishV2Too), let consumers move one at a time (they ignore types they do not know), watch v1 consumer lag drop to zero, then stop v1. Compatibility modes and registries: Message Design & Schema Evolution.
Choosing
| Situation | Use | Extra technique | Reason |
|---|---|---|---|
| Another aggregate in the same context must react | Domain event + in-process handler | Own transaction, idempotent | One transaction per aggregate (Vernon) |
| Two writes must be atomic and live in one aggregate | No event; one aggregate method | Redesign the aggregate if needed | Invariants belong inside one boundary |
| Reaction writes only to the same database and must be atomic with the change | Handler before commit, same transaction | Keep it small | Commits or rolls back together |
| Email, push notification, cache | Domain event, after commit | Queued listener with retries | Cannot be rolled back |
| Another bounded context or service must know | Integration event via outbox | Contract, version, inbox on consumer | Reliable, decoupled |
| Partner or external system | Integration event, often webhook | Reverse-DNS type, signed payloads | Public contract |
| Consumer needs data to act offline | Event-carried state transfer | Enrichment in translator | No callbacks |
| Data is sensitive or large | Notification + authorised callback, or claim check | ShouldBeEncrypted for queued listeners | Data stays home |
| You need the full history as state | Event sourcing (separate decision) | Projections | Audit, temporal queries |
| UI must update live | Broadcasting from a listener | ShouldBroadcast | Not a contract |
In architecture: from a single process to a distributed system
Monolith: one process, one database
All contexts live in one codebase and one database. Domain events and in-process handlers are enough for most reactions; there are no integration events yet, but the habit starts here: put events that other modules react to behind a translator, even if it only copies fields. Example: Order.Place records OrderPlaced; after commit the loyalty handler reserves points and the email handler sends the confirmation; the "my orders" table may be updated in the same transaction because it is a table in the same database (the before-commit, same-database case); once it moves to another store or module it becomes the eventual read model of the tables above. The atomicity of that one transaction is ACID at work.
Modular monolith: modules as bounded contexts
Sales, Fulfilment and Billing are modules in one deployable, ideally with separate schemas (Modular Monolith). Fulfilment must not import Sales\Domain\Events\OrderPlaced; it subscribes to sales.order.placed.v1 delivered by an in-process outbox relay (a scheduled RelayOutbox that hands envelopes to local module handlers). Extracting Fulfilment into a service later changes only the transport: the contract, the translator and the inbox already exist. Architecture tests enforce the import rule.
Microservices: the contract becomes the boundary
Each context is a service with its own database (Data Ownership); only integration events and APIs cross (Service Communication); where the service lines go is Service Boundaries. The full flow of the running example:
1 Sales: POST /orders -> Order.Place -> OrderPlaced (domain)
2 Sales tx: UPDATE orders; INSERT outbox(sales.order.placed.v1, subject o-42); COMMIT
3 Sales: after commit -> ReserveLoyaltyPoints (in-process, queued)
4 Relay: outbox -> Kafka topic sales.order.placed.v1, key o-42 (or RabbitMQ exchange "sales", routing key sales.order.placed.v1)
5 Fulfilment: inbox(/sales/evt-1) new -> WorkOrder released -> fulfilment.workorder.released.v1
6 Billing: inbox(/sales/evt-1) new -> Invoice drafted -> billing.invoice.issued.v1
7 Billing: later billing.payment.captured.v1 -> Sales translates (inbound ACL) -> Order.MarkPaidMulti-step business processes that need compensation are sagas (Saga); this chapter's events are their building blocks. Reliability patterns: Designing for Failure.
Distributed data: replicas, caches, multi-region
- Read replicas: a consumer that receives
sales.order.placed.v1and calls Sales' API back may hit a lagging replica and get 404. Event-carried state transfer avoids the callback; otherwise read from the primary or retry. - Caches and read models: consumers build their own projections from integration events; they are eventually consistent by design and must handle redelivery and reordering per aggregate (version or
timechecks). - Multi-region: events are produced in the region that owns the aggregate; cross-region replication of topics (MirrorMaker, RabbitMQ federation/shovel) adds delay and duplicates; the inbox key
source + idkeeps consumers safe. - CDC instead of a polling relay: Debezium's outbox event router reads the outbox table from the WAL/binlog (Change Data Capture); the contract is unchanged.
Scaling path: 1×, 10×, 100×
| Scale | Domain events | Integration events |
|---|---|---|
| 1× (one team, one app) | In-process bus, after-commit dispatch | Maybe none; a translator for module boundaries |
| 10× (several teams, modular monolith or few services) | Queued listeners for slow reactions | Outbox + one broker, contracts in a shared catalogue, inbox per consumer |
| 100× (many services) | Unchanged inside each service | Schema registry with compatibility checks, AsyncAPI docs, partitioning by aggregate id, CDC relay, DLQ and replay tooling, correlation ids in every log line |
The domain side barely changes with scale; the integration side grows tooling. That is the payoff of keeping them apart.
Lab: the OrderPlaced flow end to end
Prerequisite: Go 1.24+. The Go commands and experiments 1–4 were run (each on a scratch copy of the module) and the results below are the real output; the PHP and SQL steps need a Laravel 13 app or a PostgreSQL server and are expected, not run.
cd docs/snippets/ddd/domain-events-integration-events/go
gofmt -l . # expected: no output
go vet ./... # expected: no output
go test ./... # expected: ok for app, eventbus, fulfilment, sales, translate
go run ./cmd/demoOutput of go run ./cmd/demo (run):
1. PlaceOrder o-42
in-proc -> loyalty reserves points for o-42
committed: order=placed outbox rows=1 err=<nil>
2. Relay publishes the outbox
broker <- sales.order.placed.v1 id=evt-1 subject=o-42 correlation=req-1
published=1 workOrder=map[sku-1:2]
3. Broker re-delivers the same message (at-least-once)
unpublished rows left=0
work orders=1 (unchanged), loyalty points=30
4. PlaceOrder o-43 with no lines
rolled back: err="an order needs at least one line" order exists=false outbox rows=1Experiments:
- In
app/place_order.go, moves.Bus.Dispatch(...)inside theInTxclosure, beforereturn tx.AppendOutbox(envs), and remove the after-commit call. Rungo test ./app/. Result:TestPlaceCommitsOrderAndOutboxThenDispatchesfails with "handlers must run after the order is committed". - In
contracts/envelope.go, add a fieldStatus stringwith tagjson:"status"toOrderPlacedV1. Rungo test ./translate/. Result:TestPlacedV1IsEnrichedAndHidesInternalsfails with "internal status must not leak into the contract". - Set
V2Too: truein the demo'sService. Result: step 2 prints two broker lines (sales.order.placed.v1id=evt-1 andsales.order.placed.v2id=evt-2) andpublished=2; Fulfilment ignores v2 and still showsworkOrder=map[sku-1:2]. - In
fulfilment/consumer.go, delete theif c.inbox[key]check. Rungo test ./fulfilment/. Result:TestDuplicateDeliveryIsIgnoredfails with "want 1 work order released, got 2": the map overwrite hides the duplicate, the release counter does not. - Laravel (expected, not run):
php artisan test --filter=PlaceOrderTestpasses; remove theforeach ($domainEvents ...)block and the first test fails onassertDispatched; set an empty$linesand the second test provesassertDatabaseCount('outbox', 0). - SQL (expected, not run, PostgreSQL 16): create the
outboxtable above, open twopsqlsessions, run the relaySELECT ... FOR UPDATE SKIP LOCKEDin both; the second session gets the rows the first did not lock.
Common misconceptions
| Belief | Reality |
|---|---|
| Domain events and integration events are the same class | Same idea, different audience, stability and transport; translate between them |
| Domain events are asynchronous by definition | Usually in-process; the integration event is the async message |
| Dispatching before commit is always wrong | It is fine for handlers that only write to the same database in the same transaction; wrong for anything external |
| After-commit dispatch is reliable | It is correct but not durable; a crash after commit loses in-process reactions unless they come from the outbox |
| Put the aggregate in the event for convenience | Mutable reference: listeners see a later state; copy ids and values |
OrderUpdated is a good generic event | CRUD events hide intent; name the business fact |
| An event named in the past tense cannot be a command | ShipOrderRequested aimed at one consumer is a command in disguise (Fowler's "passive-aggressive command") |
| Publishing events means event sourcing | Event sourcing stores events as the state; publishing does not |
| The broker guarantees order and exactly-once | At-least-once, order per partition/queue only; consumers de-duplicate |
| Consumers define what the producer publishes | The producer owns facts and contract; consumers translate or negotiate |
| Eloquent observers are domain events | Persistence hooks; they miss mass updates and leak models |
| Thin events are always more decoupled | A callback adds runtime coupling and races |
Cheat sheet
| Topic | Remember |
|---|---|
| Domain event | Past tense, immutable, ubiquitous language, raised by the aggregate, ids + values |
| Integration event | Published language, versioned context.aggregate.fact.vN, owned by the producer |
| Separation | Translate at the edge: zero, one or many outputs; drop, rename, enrich |
| Raise | Inside the aggregate, after invariants pass, recorded in a list |
| Dispatch | After commit for in-process reactions; same-tx only for same-DB writes |
| Outbox | Integration events inserted in the business transaction; relay publishes |
| Consistency | One transaction per aggregate; eventual between aggregates and contexts |
| Consumers | Idempotent (inbox on source + id), tolerant of unknown types, order per key only |
| Payload style | Notification (ids) vs event-carried state transfer (state); usually a stable subset |
| Envelope | CloudEvents: id, source, specversion, type + subject, time |
| Tracing | correlationid for the flow, causationid for the direct cause |
| Laravel | ShouldDispatchAfterCommit, ShouldQueueAfterCommit, after_commit, Event::fake, assertDispatched |
| Go | PendingEvents() → translate → outbox in tx → Commit → Dispatch → MarkCommitted() |
| Anti-patterns | CRUD events, raw domain events on the wire, events as commands, model references, order across aggregates |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Name four properties of a domain event. Must-know
Answer
Answer: Past tense and named in the ubiquitous language; immutable; raised by the aggregate whose state changed; carries the identities involved and the time it occurred (plus the values that changed).
2 — Why not publish the domain event class directly to the broker? Must-know
Answer
Answer: Every consumer would couple to Sales' internal model: renames and internal fields would become breaking changes, and the model would freeze. A translated, versioned integration event keeps the model free and the contract stable.
3 — A listener sends an email when OrderPlaced is dispatched inside DB::transaction, and the commit fails. What happened and how do you fix it? Must-know
Answer
Answer: The email went out for an order that does not exist. Dispatch after the transaction returns, or implement ShouldDispatchAfterCommit on the event, or make the listener ShouldQueueAfterCommit.
4 — When is it acceptable to run a domain event handler before commit, in the same transaction? Good to know
Answer
Answer: When the handler only writes to the same database and the business requires those writes to be atomic with the change. It must not call email, HTTP, queues or brokers.
5 — Where is the integration event written, and why there? Important
Answer
Answer: Into the outbox table, inside the same transaction as the aggregate change. Both commit or neither does; the relay publishes afterwards, so there are no lost and no ghost events.
6 — Give an example of one domain event producing zero, one and two integration events. Good to know
Answer
Answer: OrderLineRepriced → zero (internal). OrderCancelled → sales.order.cancelled.v1. OrderPlaced → sales.order.placed.v1 and .v2 during a migration window.
7 — What is the difference between event notification and event-carried state transfer? Important
Answer
Answer: Notification carries ids and maybe a link; the consumer calls back for details. Event-carried state transfer carries the state the consumer needs, so it can act without the producer, at the cost of bigger messages and copies.
8 — Which CloudEvents attributes are required, and how does a consumer detect duplicates? Important
Answer
Answer: id, source, specversion, type. Events with the same source and id may be treated as duplicates; the inbox key is source + "/" + id.
9 — What do correlation id and causation id record? Important
Answer
Answer: Correlation id: the whole business flow (e.g. the checkout request), copied to every message in it. Causation id: the id of the message or command that directly caused this one.
10 — Why is OrderObserver::updated a poor source of business events in Laravel? Important
Answer
Answer: It fires on persistence, not on business facts (CRUD naming), carries the whole model, may run before commit, and does not fire for mass updates or deletes.
11 — Your team publishes events and stores orders in tables. Are you event-sourced? Must-know
Answer
Answer: No. Event sourcing stores events as the source of truth and rebuilds state by replay. You use domain and integration events with state-based persistence.
12 — Who owns sales.order.placed.v1, and how does Billing protect itself against breaking changes? Important
Answer
Answer: Sales owns it. Billing ignores unknown types and versions (tolerant reader) and contributes consumer-driven contract tests (Pact message pacts) that run in Sales' pipeline.
Glossary
| Term | Meaning |
|---|---|
| Domain event | An immutable, past-tense fact in one bounded context's model, raised by an aggregate |
| Integration event | A versioned message in the published language for other contexts or services |
| System event | A technical occurrence (row saved, job failed), not a domain fact |
| Published language | The documented, shared format a context uses to talk to others |
| Translator / ACL out | Code that maps domain events to integration events at the edge |
| Enrichment | Adding data to an integration event so consumers need not call back |
| Deferred dispatch | Recording events and dispatching them around the commit, not when raised |
| After commit | Dispatching only once the database transaction has committed |
| Transactional outbox | Table where messages are inserted in the business transaction, then relayed |
| Relay | Process that publishes outbox rows to the broker (polling or CDC) |
| Inbox | Consumer table of processed message keys, for idempotency |
| Idempotent consumer | A consumer whose effect is the same whether a message arrives once or many times |
| At-least-once | Delivery that may duplicate but does not lose |
| Eventual consistency | Other aggregates or contexts become consistent after a delay |
| Event notification | A thin event with ids; consumers call back for details |
| Event-carried state transfer | An event carrying the state consumers need |
| Event collaboration | Components raise events when things change instead of making requests |
| Passive-aggressive command | A command disguised as an event (Fowler) |
| CRUD event | OrderUpdated-style event describing a row change, not a fact |
| CloudEvents | CNCF envelope spec; required id, source, specversion, type |
| Extension attribute | An additional CloudEvents context attribute such as correlationid |
| Correlation id | Id shared by all messages of one business flow |
| Causation id | Id of the message that directly caused this one |
| AsyncAPI | Specification for describing message-driven APIs |
| Consumer-driven contract | Consumers' expectations tested against the producer (Pact) |
| Tolerant reader | A consumer that ignores unknown fields and types |
| Dual publishing | Publishing old and new versions side by side during a migration |
| Event Storming | Workshop that discovers domain events and their policies |
| Event sourcing | Storing state as the sequence of events, rebuilt by replay |
ShouldDispatchAfterCommit | Laravel interface: dispatch the event after the open transaction commits |
ShouldQueueAfterCommit | Laravel interface: push the queued listener after commit |
Event::fake | Laravel test helper that stops listeners and records dispatched events |
| Watermill Forwarder | Watermill component implementing the outbox for Go |
References
- Eric Evans, Domain-Driven Design Reference (2015), "Domain Events": https://www.domainlanguage.com/wp-content/uploads/2016/05/DDD_Reference_2015-03.pdf
- Vaughn Vernon, "Effective Aggregate Design, Part II" (2011): https://www.dddcommunity.org/wp-content/uploads/files/pdf_articles/Vernon_2011_2.pdf
- Vaughn Vernon, Implementing Domain-Driven Design (2013), ch. 8 "Domain Events" (book; not fetched, secondary here)
- Vlad Khononov, Learning Domain-Driven Design (O'Reilly, 2021) (book; not fetched, secondary here)
- Martin Fowler, "Domain Event" (2005): https://martinfowler.com/eaaDev/DomainEvent.html
- Martin Fowler, "Event Collaboration" (2006): https://martinfowler.com/eaaDev/EventCollaboration.html
- Martin Fowler, "What do you mean by 'Event-Driven'?" (2017): https://martinfowler.com/articles/201701-event-driven.html
- Udi Dahan, "Domain Events – Salvation" (2009): https://udidahan.com/2009/06/14/domain-events-salvation/
- Chris Richardson, "Pattern: Domain event": https://microservices.io/patterns/data/domain-event.html
- Chris Richardson, "Pattern: Transactional outbox": https://microservices.io/patterns/data/transactional-outbox.html
- Microsoft, "Domain events: Design and implementation": https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/domain-events-design-implementation
- Microsoft, "Implementing event-based communication between microservices (integration events)": https://learn.microsoft.com/en-us/dotnet/architecture/microservices/multi-container-microservice-net-applications/integration-event-based-microservice-communications
- Laravel 13, Events: https://laravel.com/docs/13.x/events
- Laravel 13, Eloquent (events, observers, mass updates): https://laravel.com/docs/13.x/eloquent
- Laravel 13, Queues (jobs and database transactions,
after_commit): https://laravel.com/docs/13.x/queues - Laravel 13, Broadcasting: https://laravel.com/docs/13.x/broadcasting
- Watermill, CQRS component: https://watermill.io/docs/cqrs/
- Watermill, Forwarder (the outbox pattern): https://watermill.io/advanced/forwarder/
- CloudEvents specification v1.0.2: https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md
- AsyncAPI specification 3.0.0: https://www.asyncapi.com/docs/reference/specification/v3.0.0
- Pact documentation: https://docs.pact.io/
- EventStorming: https://www.eventstorming.com/