Skip to content

Event-Driven Architecture ​

“The biggest outcome of the summit was recognizing that when people talk about “events”, they actually mean some quite different things.” — Martin Fowler, What do you mean by “Event-Driven”? (7 February 2017)

Summary: Event-driven architecture lets a service announce facts so that other services react on their own schedule, trading call-time coupling for eventual consistency and new operational work. Focus: Events vs commands vs queries, Fowler's three event patterns, domain vs integration events, hidden choreography coupling, local projections and how users experience eventual consistency. Learning goal: Pick the right message intent and event style for a flow, design an integration event that a projection can trust, and run that projection on RabbitMQ, Kafka and Redis Streams without silent loss.

This chapter owns the style: which messages are facts, who owns what, and what changes when state is copied by events. The mechanics of storing state as events live in Event Sourcing & CQRS; durable publication lives in the Transactional Outbox; long business flows with compensation live in Saga; consumer deduplication lives in Idempotent Consumers & the Inbox Pattern. The DDD view of the two event kinds is in Domain Events vs Integration Events.

Page map ​

If you are looking forGo to
Whether a message should be a command, an event or a queryEvents, commands and queries
Thin events that make receivers call backEvent notification
Events that carry data so receivers keep a local copyEvent-carried state transfer
Where event sourcing and CQRS fit (and do not)Event sourcing and CQRS, briefly
OrderPlaced inside a service vs on the wireDomain and integration events
Why nobody can explain the end-to-end flow any moreChoreography and hidden coupling
An "event" that is really an order to one servicePassive-aggressive commands
Whether a consumer may reject an eventIngress validation
Bootstrapping, lag and rebuilding a local copyLocal projections
"I placed an order and my order list is empty"Eventual consistency in the UX
CloudEvents, AsyncAPI, correlation and causation idsEvent envelope
Exchange vs queue ownership, offsets, MAXLENBroker differences
Laravel ShouldDispatchAfterCommit and listenersLaravel
Experiments to runLab

Everything in one minute ​

MessagePlain wordsTiny exampleAddressed toMay the receiver refuse?
Command"Please do this"ReserveStock(order 1001)One ownerYes: it is a request
Event"This happened"OrderPlaced(order 1001, rev 1)Whoever subscribes; unknown to senderNo: the fact stands; a malformed message can still be rejected
Query"Tell me"GetOrderStatus(1001)One owner or read modelIt can fail, but it changes nothing
Fowler patternWhat travelsReceiver gainsReceiver pays
Event notificationAn id and a hintLow coupling, simple setupA callback to the source for details; flow invisible in code
Event-carried state transferThe changed state the receiver needsWorks when the source is down; no remote read latencyOwns a copy: bootstrap, lag, rebuild, storage
Event sourcingNothing new on the wire; events are the source's storageAudit and replay of the source's own historyEvent schema evolution, replay side effects
CQRSNothing by itself; separate read and write modelsRead model shaped for its queriesTwo models to keep in step
BrokerProducer-owned objectSubscriber-owned objectWhere history lives
RabbitMQExchangeQueue + binding (+ its DLX)Only in queues that existed when the message was routed
KafkaTopic (partitions, retention)Consumer group + committed offsetsTopic log until retention.ms / size / compaction removes it
Redis StreamsStream key (+ trimming policy)Consumer group + PELStream entries until MAXLEN/MINID trimming removes them

Where it comes from ​

Hohpe and Woolf's Enterprise Integration Patterns (2003) already separated messages by intent. A Command Message exists "to reliably invoke a procedure in another application"; an Event Message is for "reliable, asynchronous event notification between applications"; a Document Message "just passes data and lets the receiver decide what, if anything, to do with the data". A Publish-Subscribe Channel "delivers a copy of a particular event to each receiver". Those four pages are still the cleanest vocabulary.

Fowler's December 2005 draft pattern Domain Event describes an object that "Captures the memory of something interesting which affects the domain", and his June 2006 Event Collaboration essay paraphrases Jon Udell: "request driven software speaks when spoken to, event driven software speaks when it has something to say." The same essay names the event cascade (A triggers B, B triggers C, and nobody sees A to C).

In 2017 Fowler summarised a Thoughtworks summit whose main finding is the quote above: "event-driven" was covering several unrelated patterns. He separated event notification, event-carried state transfer, event sourcing and CQRS, and warned that "Strictly CQRS isn't really about events". Chris Richardson's microservices.io catalogue later framed the Domain event pattern as aggregates emitting events that other services consume, with the Transactional outbox answering "How to atomically update the database and send messages to a message broker?". CloudEvents (CNCF) standardised an envelope, and AsyncAPI standardised a way to describe message-driven APIs. The split between domain and integration events is DDD practice (Evans, Vernon) popularised by Microsoft's .NET microservices guide; this page uses it as a design convention, not as a quote.

Why it exists ​

A checkout that calls billing, shipping, mail and analytics in sequence is only as available as the least available of them, and only as fast as their sum. Events move those reactions out of the request: the order service records a fact and returns; each subscriber reacts when it can. The price is that the system is now eventually consistent and the flow is no longer written down in one place.

Request/response (call)Event-driven (announce)
Caller knows every receiverProducer does not know subscribers
Answer is available nowEffects appear later; UI must show pending
Failure surfaces at the caller immediatelyFailure surfaces in a consumer, a DLQ or a lag graph
Flow is readable in one functionFlow is spread over subscriptions; needs tracing
Adding a reaction edits the callerAdding a reaction adds a subscriber
Strong consistency is possible in one transactionConsistency across services is eventual

The everyday analogy used throughout: a newsroom bell. The editor rings it when a story breaks (event). Desks decide for themselves what to do. If the editor actually needs the photo desk to send a photographer, ringing the bell and hoping is the wrong tool: phone the photo desk (command).

Three misunderstandings to remove first: an event is not "a message sent asynchronously" (commands can be asynchronous too); event-driven does not mean event-sourced; and decoupled at deploy time does not mean decoupled at run time.

What it is really about ​

Three questions decide every message: who owns the decision (the receiver for a command, the sender for an event), who must know whom (the commander knows its target; the announcer knows no one), and what the receiver may do (refuse a command; never un-happen an event, though it may reject a malformed message). Everything else, from broker choice to UI copy, follows from those answers.

Command“ReserveStock”one owner; may refuseInventoryanswers or rejectsreply / outcomeEvent“OrderPlaced”fact; many subscribersShippingdecides itselfMaildecides itselfAnalyticsdecides itselfQuery“GetOrderStatus”reads; changes nothingOrder read modelreturns a viewreply / outcomeDashed: asynchronous or optional. A command can travel over a queue; a query can read a stale projection.

Once events carry state, a second mechanism appears: every subscriber that keeps a copy runs a small replication system. It needs a starting point (bootstrap), a position (offset or PEL), a freshness metric (lag), an ordering rule (revision per aggregate), and a way to start over (rebuild). Most production trouble with event-driven systems is trouble with one of those five.

An everyday picture ​

In the newsroom, the bell carries almost no information: "something big happened". Desks that need detail walk to the editor's office and ask (event notification, with its callback). A wire service is different: it sends the full story text to every subscribing paper, which files its own copy and never phones the agency (event-carried state transfer). The agency's archive of every story it ever sent is a third thing again (event sourcing). And if the editor rings the bell only because she wants the photo desk to act, while the photo desk does not know that, she has sent a passive-aggressive command.

Concept catalogue ​

Events, commands and queries Must-know ​

In plain words: A command asks one owner to do something and can be refused; an event tells anyone listening that something already happened; a query asks for data and changes nothing.

Common misunderstanding: "Commands are synchronous, events are asynchronous." Intent, not transport, decides. ReserveStock can travel on a RabbitMQ queue and be answered later; a query can read a projection that is minutes old.

Definition: A command is named in the imperative (ReserveStock), has exactly one logical handler that owns the decision, and has an outcome the sender cares about. An event is named in the past tense (StockReserved), is owned by its producer, may have zero or many subscribers, and records a decision already made. A query (GetStock) requests a representation without side effects.

text
1 Checkout  -> Inventory (command, queue):  ReserveStock order=1001 sku=A qty=2
2 Inventory -> Inventory:                   checks stock, decides
3 Inventory -> orders.events (event, pub/sub): StockReserved order=1001  (or StockRejected)
4 Shipping, Checkout -> each own queue:      react independently
5 Browser   -> Order read model (query):     GetOrderStatus 1001 -> "reserved"

Real scenarios: reserving a seat (command: the theatre may say no); PaymentCaptured (event: the money moved, billing cannot "decline" it); a dashboard reading order counts (query against a projection); SendWelcomeEmail (command to the mailer, even if a CustomerRegistered event triggered it).

PropertyCommandEventQuery
Name tenseImperativePastQuestion
ReceiversExactly one owner0..n, unknown to senderOne owner or read model
Sender expectsAn outcomeNothing in particularData
Typical channelPoint-to-point queue, RPCPub/sub exchange, topic, streamHTTP/gRPC, read model
Schema owned byReceiver (its API)Producer (its published facts)Receiver (its API)

How to use it: name messages by intent before choosing a broker; if a sender would page someone when nobody reacts, it is a command. Request-reply over a broker is covered in Request-Reply over Messaging.

Event notification Must-know ​

In plain words: The event is a doorbell: it says "order 1001 changed" and receivers that care fetch the details.

Common misunderstanding: "A thin event removes coupling." It removes deploy-time coupling, but every receiver that calls back now depends on the source being up, fast and able to serve the version that the event referred to.

Definition: Fowler: the source sends event messages to notify other systems of a change and "doesn't really care much about the response". The event often carries "just some id information and a link back to the sender that can be queried for more information".

text
1 Orders   -> orders.events: OrderChanged {id: 1001}            revision 4 committed
2 Orders   -> DB:            commit revision 5 (address edited)
3 Shipping <- orders.events: OrderChanged {id: 1001}
4 Shipping -> Orders API:    GET /orders/1001        -> sees revision 5, not 4
5 Orders API down?           Shipping stalls: runtime coupling through the callback

Real scenarios: a webhook that says "invoice updated, fetch it"; cache invalidation (ProductChanged {id} then re-read); a search indexer that re-reads documents; a fan-out to 40 subscribers that all call back at once and overload the source (a thundering herd).

ConcernThin notificationWhat to add
Source revision vs current stateCallback returns current state, possibly newer than the eventPut revision in the event; let the reader ask for it or ignore older
Source outageConsumers stall or failRetry with backoff; or switch to state transfer
Callback loadn subscribers multiply readsRate-limit, cache, or carry the needed fields
AuthorizationCallback needs credentials to the sourceService identity and scoped read API
Event notificationOrdersemits id onlyOrderPlaced {id}Shippingneeds lines, addressGET /orders/{id} (callback)Runtime coupling remainsOrders must be up and fast for ShippingEvent-carried state transferOrdersemits changed stateOrderPlaced + stateShippinglocal projectionCopy needs bootstrap, lag metric,rebuild path, and only fields it usesEvent sourcing (persistence, not messaging)Command handlerappends eventsEvent storesource of truthreplayCurrent state and read modelsderived; CQRS optional

How to use it: good for "something changed, recompute when convenient" (cache busting, search reindex). Carry the aggregate id and revision so a reader can detect that what it fetched is newer than what it was told about.

Event-carried state transfer Must-know ​

In plain words: The event carries the data, so each receiver keeps its own copy and never needs to ask the source again.

Common misunderstanding: "So the event should contain everything about the order." It should carry what the known projections need. Shipping needs lines and destination; it does not need the card BIN. A field you publish becomes a contract you must keep.

Definition: Fowler: recipients "update it's own copy" from events "so that it never needs to talk to the main customer system". Gains: resilience, lower latency, less load on the source. Costs: "lots of data schlepped around and lots of copies", and complexity on the receiver, which must maintain state.

text
1 Orders    -> topic: OrderPlaced  {order 1001, rev 1, lines, shipCountry NL, customerId cus-7}
2 Shipping  -> own DB: upsert order_summaries(1001, rev 1)
3 Orders API goes down
4 Shipping  -> own DB: picks orders to ship; no call to Orders needed
5 Mailer    needs customer e-mail: NOT in OrderPlaced
6 Mailer    -> own DB: reads customer projection fed by CustomerChanged events

Real scenarios: shipping planning from order events; a pricing service consuming ProductPriceChanged; a fraud service keeping a per-customer history; a mobile backend keeping user profiles to avoid calling an identity service on each request.

DecisionRecommendationWhy
What to includeFields at least one subscribing projection needs, plus id and revisionSmaller contract; fewer leaks
Delta or full snapshotSnapshot of the changed aggregate partLate joiners and reordering are simpler
Data the event does not own (customer e-mail)Separate projection from the owning service's eventsDo not smuggle another context's data
PIIMinimise; see Messaging SecurityCopies spread retention obligations
VersioningNew type or schema version, see Message DesignOld consumers must keep working

How to use it: the Go events.OrderPlacedV1 struct shows a payload sized for shipping and history, holding CustomerID rather than an e-mail address; the projection applies it by revision.

Event sourcing and CQRS, briefly Good to know ​

In plain words: Event sourcing is a way to store a service's own state as a list of events; CQRS is using different models to write and to read. Neither requires a broker.

Common misunderstanding: "We publish events, so we are event-sourced." Publishing integration events from a CRUD database is event-carried state transfer. Fowler also notes that event processing in an event-sourced system need not be asynchronous at all.

Definition: Event sourcing makes the event store "the principal source of truth" and derives state by replay. CQRS separates read and write data structures; it can exist with no events. Both are covered in depth in Event Sourcing & CQRS.

text
1 Command handler -> event store: append OrderPlaced, OrderPaid (source of truth)
2 Projector       -> read model:  derive order_summaries by replay
3 Publisher       -> broker:      translate selected internal events to integration events
PatternRequires a broker?Requires events on the wire?
Event notificationUsuallyYes
Event-carried state transferUsuallyYes
Event sourcingNoNo
CQRSNoNo

How to use it: keep the internal event store's schema private; publish translated integration events, exactly as a CRUD service would.

Domain events and integration events Must-know ​

In plain words: A domain event is a fact inside one service, in its own language; an integration event is a published contract that other services depend on.

Common misunderstanding: "Serialize the domain event and put it on the broker." Then every internal rename becomes a breaking change for other teams, and internal fields (Eloquent models, internal ids, PII) leak.

Definition: A domain event is raised by an aggregate and handled in-process, often in the same transaction or right after commit. An integration event is a versioned message crossing a service boundary through a broker, built explicitly from chosen fields, published durably (outbox), and consumed by unknown subscribers. Translation from the first to the second is deliberate code.

text
1 Order aggregate -> in-process bus:  OrderPlaced (domain, PHP object, internal ids)
2 Listener        -> same DB tx:      insert outbox row with com.example.orders.order.placed.v1
3 COMMIT
4 Relay           -> broker:          publish outbox row (integration event, CloudEvents JSON)
5 Shipping        <- broker:          consumes the contract, never the PHP class

Real scenarios: Laravel's OrderPlaced event updating a local summary table vs order.placed.v1 on Kafka; a Go service emitting domain.OrderPlaced on a channel and translating to Protobuf for other teams; renaming total to grandTotal internally without touching the contract.

AspectDomain eventIntegration event
AudienceSame bounded contextOther services/teams
TransportFunction call, in-process dispatcherBroker (RabbitMQ, Kafka, Redis Streams, NATS, SQS/SNS, Pulsar)
SchemaFree to change with the modelVersioned contract (AsyncAPI, schema registry)
DurabilityLives and dies with the processOutbox + broker persistence
TimingOften before or right after commitAfter commit, via relay
IdentityObject identitysource + id (CloudEvents)

How to use it: the Laravel after snippets keep App\Events\OrderPlaced (domain) separate from App\Messaging\IntegrationEnvelope (contract) and write the envelope to the outbox in the same transaction. See Domain Events vs Integration Events.

Choreography, orchestration and hidden coupling Important ​

In plain words: In choreography each service reacts to others' events and no one directs the whole dance; in orchestration one coordinator sends commands and tracks the state of the flow.

Common misunderstanding: "Choreography is decoupled." Services are decoupled from each other's addresses, but the business flow still exists; it is now encoded in subscriptions, and its timing, ordering and failure behaviour are coupled at run time. Fowler: such a flow is hard to see "as it's not explicit in any program text. Often the only way to figure out this flow is from monitoring a live system."

Definition: Choreography: each local transaction publishes events that trigger local transactions elsewhere (microservices.io saga page). Orchestration: an orchestrator tells participants what to do. Hidden coupling shows up as temporal coupling (B must run before C reads), callback coupling (thin events that require reads back), semantic coupling (C relies on B's interpretation) and event cascades.

text
1 Orders    -> OrderPlaced
2 Payments  <- OrderPlaced  -> PaymentCaptured
3 Inventory <- PaymentCaptured -> StockReserved     (or StockRejected)
4 Shipping  <- StockReserved -> ShipmentScheduled
5 Orders    <- StockRejected -> ??? who refunds?    nobody owns the A->D picture

Real scenarios: a refund that never happens because the compensation subscriber was removed; a loyalty service that silently became a step in checkout; an analytics consumer that someone "temporarily" made the trigger for invoices; an incident review that needs four teams to reconstruct one order.

ChooseWhenCost
ChoreographyFew steps, independent reactions, no compensationFlow invisible; needs tracing and correlation ids
Orchestration (saga, durable workflows)Ordered steps, compensation, deadlinesCoordinator is a component to run and own
HybridOrchestrated core flow; side effects choreographedTwo styles to explain

How to use it: draw the cascade (EventStorming helps); if a step's absence is an incident, own it with a process manager. Carry correlationid and causationid (see envelope) so the flow can be rebuilt from logs.

Passive-aggressive commands Important ​

In plain words: It is an event on paper, but the sender is secretly waiting for one particular service to do something.

Common misunderstanding: "Using events everywhere keeps us consistent." Fowler: the trap happens "when the source system expects the recipient to carry out an action, and ought to use a command message to show that intention, but styles the message as an event instead."

Definition: a message named as a fact whose correctness depends on a specific receiver acting. Symptoms: names like InvoiceShouldBeCreated, alerts when "nobody consumed it", a producer that checks the receiver's state afterwards.

text
1 Orders  -> OrderReadyForInvoicing   (styled as event)
2 Billing <- consumes; creates invoice
3 Billing team unsubscribes during a refactor
4 Orders  -> waits for InvoiceCreated forever; no error anywhere
SymptomBetter message
Producer waits for a specific reactionCommand CreateInvoice to Billing, with a reply event
Event name contains "should", "request", "please"Rename as command, or as a real fact (OrderShipped)
Removing a subscriber breaks a business ruleMake the dependency explicit in an orchestrator
RabbitMQ mandatory return treated as a business failureIt is a command; route to its owner's queue

How to use it: keep the event (OrderShipped) for anyone interested and send the command to the one owner when the business requires the action.

Ingress validation versus refusing a fact Important ​

In plain words: A consumer cannot decide that an order was not placed, but it can and should reject a message it cannot trust or decode.

Common misunderstanding: "Events cannot be refused, so consumers must accept every message." The fact cannot be undone by a subscriber; the message may be malformed, unauthorised, from the wrong source, or of an unknown version. Rejecting it is ingress hygiene, not disagreement with history.

Definition: ingress validation checks size, envelope shape, specversion, trusted source for that type, schema version, and payload invariants before any effect. Invalid messages go to a parking destination (DLQ); valid facts that conflict with local rules produce a new event or a compensating command (for example ShipmentBlocked), never a silent drop.

text
1 Shipping <- order.placed.v1 from source /services/marketing   -> reject: untrusted source, park
2 Shipping <- order.placed.v1 with lines=[]                     -> reject: invariant, park
3 Shipping <- valid order.placed.v1 for an embargoed country    -> accept fact; emit ShipmentBlocked
4 Orders   <- ShipmentBlocked                                    -> business decides refund/cancel
SituationActionNot this
Undecodable bytes, unknown specversionPark raw bytes with reasonInfinite requeue
Type from an unexpected sourceReject and alert (possible spoof or misrouting)Apply it
Unknown newer schema versionPark until consumer upgradedGuess fields
Valid fact the consumer "disagrees" withNew event or command to the ownerPretend it did not happen
Duplicate (same source + id)Acknowledge, no effectTreat as error

How to use it: Go's events.Decode wraps every ingress failure in ErrInvalid; the RabbitMQ consumer rejects those without requeue, the Kafka and Redis consumers park them and continue.

Local projections: bootstrap, lag and rebuild Must-know ​

In plain words: A projection is the subscriber's own table built from events; it has to be filled from somewhere at first, it is always a little behind, and sometimes it has to be thrown away and rebuilt.

Common misunderstanding: "A new consumer group gets every event ever published." It gets what the broker still retains, starting where its configured reset policy says. Kafka's default auto.offset.reset is latest; a RabbitMQ queue receives only messages routed after its binding existed; a Redis group created with $ sees only new entries.

Definition: a projection (read model, local copy) is derived state owned by a consumer. Bootstrap fills it initially (replay from retained history, or a snapshot/export from the owner). Lag is how far behind the source it is (offset lag or event-time age). Rebuild creates a fresh copy, usually with a new group id, beside the live one and switches readers once caught up. An idempotent consumer applies each event at most once in effect, here by keeping the per-aggregate revision.

text
1 T0  shipping-projection-v1 created; reset=earliest; retention 7 days
2 T0  replays 7 days of order events; orders older than that are MISSING
3 T1  live; lag 200 ms
4 T2  bug fix needs new columns: start shipping-projection-v2 (new group) in parallel
5 T3  v2 caught up (lag < 1 s): switch reads to v2; delete v1 group and table

Real scenarios: a new recommendations service needs a year of orders but the topic keeps seven days; a projection bug wrote wrong totals for a week; a region failover where the consumer's offsets are not where its database thinks they are; a deploy that changes the projection schema.

BrokerHow a fresh projection startsHistory limit
RabbitMQOnly messages routed after the queue is bound; backfill from the owner (API export or snapshot)No replay from an exchange; RabbitMQ streams are a separate feature
KafkaNew group + auto.offset.reset=earliest (franz-go ConsumeResetOffset(NewOffset().AtStart()))retention.ms (default 7 days), size, or compaction (latest per key)
Redis StreamsXGROUP CREATE stream group 0 reads retained entries; $ only newMAXLEN/MINID trimming; memory
Bootstrapnew group at oldestretained recordCatch uplag fallsas backlog drainsLivelag near zeroserve readsRebuildnew group v2in parallelSwitchreaders movedrop v1Consumer-owned local projectionRetention gap: history older than retentionis gone; bootstrap needs a snapshot or source exportLag = now minus event time of last applied;UX must show pending until caught up

How to use it: store revision and source_time per row, export lag as a metric, and keep a rebuild path that does not require the source to be down. The Go projection package and the guarded upsert implement it.

Eventual consistency in the user experience Must-know ​

In plain words: After a user acts, some screens are briefly out of date; design the screen so that this is honest and short, not confusing.

Common misunderstanding: "Eventual consistency is an infrastructure detail." Users see it: the order list is empty right after checkout, the balance is old, the button can be pressed twice.

Definition: read-your-writes guarantees that a user sees their own changes; across event-fed read models it is provided by the application, not the broker. Techniques: return the accepted state from the write; show a pending state; optimistic UI (render the expected result, reconcile later); route the user's own reads to the write model or wait for the projection to reach the write's revision; push updates (WebSocket, Laravel broadcasting); a status page per long operation.

text
1 Browser -> Orders API: POST /orders            -> 202 {id 1001, revision 1, status "pending"}
2 Browser -> My Orders (projection): GET         -> projection at revision 0: empty
3 UI      -> shows "Order 1001 being confirmed" from the POST response (optimistic)
4 Projector applies revision 1 (lag 400 ms)
5 Browser -> GET /orders?minRevision=1           -> projection has caught up -> list shows 1001
TechniqueHowCost
Return accepted stateResponse carries id, revision, statusClient must use it
Pending/status pageGET /operations/{id}Extra endpoint
Optimistic UIRender expected result, roll back on failureRollback UX
Read-your-writes by revisionClient sends minRevision; server waits briefly or reads write modelShort waits under lag
PushWebSocket/SSE on projection updateConnection management
Idempotency key on writesRetry-safe POSTKey storage

How to use it: never tell the user "done" for an effect that a projection has not applied; say "received". For replica-based variants see Replication and Eventual Consistency in Databases.

Event envelope, correlation and causation Important ​

In plain words: Every event travels in a standard wrapper that says what it is, who sent it, when, and which request and which earlier message led to it.

Common misunderstanding: "The broker's message id is enough." It changes on republish and differs per broker. Business identity must be in the event.

Definition: CloudEvents 1.0 requires id, source, specversion and type, and offers subject, time, datacontenttype, dataschema. The spec says: "Consumers MAY assume that Events with identical source and id are duplicates." A correlation id follows one business flow across all messages; a causation id is the id of the message that directly caused this one. Both are extension attributes here (correlationid, causationid); EIP's Correlation Identifier pattern is the request-reply ancestor. AsyncAPI describes channels and messages "in a machine-readable format" so subscribers can discover contracts.

text
1 HTTP request  req-42                  -> correlationid=req-42
2 OrderPlaced   id=evt-1 causation=-    correlationid=req-42
3 PaymentCaptured id=evt-7 causationid=evt-1  correlationid=req-42
4 StockReserved   id=evt-9 causationid=evt-7  correlationid=req-42
5 Trace: filter correlationid=req-42; order by causation chain
AttributeRequired?Use
idYesDedup with source
sourceYesProducer identity; ingress trust check
specversionYesEnvelope version (1.0)
typeYesRouting and schema; version suffix such as .v1
subjectNoAggregate id; Kafka key; ordering scope
timeNoEvent time; lag calculation
datacontenttype / dataschemaNoPayload format and schema reference
correlationid / causationidExtensionFlow reconstruction

How to use it: put business identity in the envelope, transport identity in headers. Trace context (W3C traceparent) is covered in Messaging Observability.

Mechanics and exact controls ​

Delivery, ordering and duplicates Important ​

All three brokers deliver at least once to a correctly written consumer, so every subscriber is an idempotent consumer (inbox). Ordering is per queue (RabbitMQ, with one consumer), per partition (Kafka, by key), or per stream (Redis). Keying Kafka records by subject keeps one order's events in order; across orders there is no order. A projection that compares revision is correct even when ordering is not guaranteed.

ControlProductValue used hereEffect
Publisher confirms (confirm.select)RabbitMQonBroker acks once queues accepted the message
mandatory flagRabbitMQtrueUnroutable message returned (basic.return, reply code 312 NO_ROUTE) before the ack
x-delivery-limitRabbitMQ quorum queue10 (default 20 since 4.0)Bounds requeue loops; then dead-letters
x-dead-letter-exchangeRabbitMQ<service>.dlxWhere rejected/over-limit messages go
auto.offset.resetKafka consumerearliest for projectionsStart for a group without committed offsets (default latest)
retention.msKafka topic604800000 default"an SLA on how soon consumers must read their data"
cleanup.policyKafka topicdelete or compactCompaction keeps latest value per key
max.poll.records / PollRecords(ctx, 100)Kafka100Bounds work per poll
max.poll.interval.ms / RebalanceTimeoutKafka60 sMember considered failed if it stops polling
MAXLEN ~ / MINIDRedis XADD~ 5000000Trims oldest entries
KEEPREF / DELREF / ACKEDRedis 8.2+ XADD/XTRIMdefault KEEPREFWhether trimming respects groups
XAUTOCLAIM min-idleRedis60 sReassigns stuck pending entries

Error codes you will meet Good to know ​

ErrorProductMeaning in this chapterResponse
312 NO_ROUTE (basic.return)RabbitMQNo queue bound for that routing keyKeep in outbox, alert; or alternate exchange
404 NOT_FOUNDRabbitMQPassive declare of a missing exchangeProducer not deployed yet; fail the subscriber start
406 PRECONDITION_FAILEDRabbitMQQueue redeclared with different argumentsUse policies; do not fight another owner's queue
OFFSET_OUT_OF_RANGEKafkaCommitted offset deleted by retentionReset policy applies; treat as data loss for the projection
REBALANCE_IN_PROGRESSKafkaCommit during rebalanceStop, recreate client, resume from committed
BUSYGROUPRedisGroup already existsSafe to ignore at bootstrap
NOGROUPRedisGroup or stream missingConsumer-owned bootstrap did not run

Solving classic problems ​

Publish durably after the state change ​

ShouldDispatchAfterCommit (Laravel) or "publish after commit" in Go closes the window where a rolled-back change is announced, but a crash between commit and publish still loses the event. The fix is the outbox: the integration event is a row in the same transaction.

SolutionHowAdvantageCost / limitation
Publish inside the transactionBroker call before COMMITSimpleAnnounces changes that roll back; broker outage fails writes
Publish after commitCallback, ShouldDispatchAfterCommitNo phantom eventsCrash gap loses events
Transactional outboxRow in same tx; relay publishesNo loss, no phantomRelay to run; duplicates downstream
CDC of the outboxDebezium/logical decoding reads outboxNo pollingCDC infrastructure (CDC)
Event sourcingEvents are the stateOne writeWhole persistence model changes
sql
-- PostgreSQL: the outbox row commits with the order (see the outbox chapter for the relay).
CREATE TABLE outbox_messages (
  id            uuid PRIMARY KEY,           -- CloudEvents id
  topic         text NOT NULL,              -- orders.events.v1
  message_key   text NOT NULL,              -- subject, e.g. ord-1001 (Kafka key / ordering scope)
  payload       jsonb NOT NULL,             -- full CloudEvents envelope
  created_at    timestamptz NOT NULL DEFAULT now(),
  published_at  timestamptz
);
CREATE INDEX outbox_unpublished ON outbox_messages (created_at) WHERE published_at IS NULL;

Keep a projection correct under duplicates and reordering ​

sql
-- Consumer-owned read model; one statement does check-and-write.
CREATE TABLE order_summaries (
  order_id     text PRIMARY KEY,
  revision     bigint NOT NULL,
  status       text NOT NULL,
  ship_country text NOT NULL,
  source_time  timestamptz NOT NULL,     -- event time: lag = now() - source_time
  updated_at   timestamptz NOT NULL
);

INSERT INTO order_summaries (order_id, revision, status, ship_country, source_time, updated_at)
VALUES ('ord-1001', 2, 'cancelled', 'NL', '2026-11-26T10:01:00Z', now())
ON CONFLICT (order_id) DO UPDATE
   SET revision = EXCLUDED.revision, status = EXCLUDED.status,
       ship_country = EXCLUDED.ship_country, source_time = EXCLUDED.source_time, updated_at = now()
 WHERE order_summaries.revision < EXCLUDED.revision;   -- 0 rows = duplicate or stale: just ack

-- Freshness check for alerts and read-your-writes:
SELECT max(now() - source_time) AS worst_lag FROM order_summaries WHERE updated_at > now() - interval '5 minutes';

Revision guards make state projections idempotent. Effects that are not state (sending an e-mail, charging a card) need an inbox table keyed by source + id, described in Idempotent Consumers.

Add a subscriber that needs history ​

SituationApproach
Kafka, history within retentionNew group, earliest, run until lag is near zero
Kafka, history older than retentionSnapshot/export from owner, then consume from the snapshot's position; or a compacted "state" topic
RabbitMQBind the queue first, then load a snapshot from the owner, then apply queued events by revision
Redis StreamsXGROUP CREATE ... 0 if retained; otherwise snapshot then $

The order matters for RabbitMQ: bind first, snapshot second, so no change falls between them; revisions discard overlap.

Make the flow visible again ​

Log correlationid, causationid, type and subject at every consume and publish; build the cascade from the logs; publish an AsyncAPI document per producer listing channels and message schemas; keep a "who subscribes to what" inventory from broker metadata (bindings, consumer groups).

Choosing a style ​

SituationRecommendationExtra techniqueReason
Caller needs the answer now (price, authorisation)Request/responseTimeouts, circuit breakerAn event cannot answer
One owner must actCommand (queue or RPC)Reply event, idempotency keyAvoid passive-aggressive events
"Something changed, recompute when convenient"Event notificationRevision in event, callback rate limitSmall contract
Receiver must work while the source is downEvent-carried state transferProjection with revision guard, lag metricResilience and latency
New service needs years of historySnapshot + events, or compacted topicRebuild groupRetention is finite
Multi-step flow with compensationOrchestrated sagaOutbox, process state tableFlow explicit
Audit of every change of one aggregateEvent sourcing (in the owner)Translate to integration eventsPersistence concern
UI right after a writeRead-your-writes by revisionOptimistic UI, pushLag is visible
Cross-team contractIntegration event with CloudEvents + AsyncAPISchema registry, compatibility rulesEvolvable
Same process, same databaseDomain event + listenerShouldDispatchAfterCommitNo broker needed

Go ​

Before ​

The order service calls inventory, billing and the mailer in sequence. It is correct code with a design problem: temporal coupling. A mail relay outage fails a checkout whose order and payment already exist, and each new reaction edits Place.

go
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"time"
)

// Before: the order service knows every downstream reaction and calls each one
// in-line. This is a design smell, not broken code: it compiles and "works".
type Billing interface {
	Charge(ctx context.Context, orderID string, totalMinor int64) error
}

type Inventory interface {
	Reserve(ctx context.Context, orderID string, skus []string) error
}

type Mailer interface {
	SendConfirmation(ctx context.Context, customerID, orderID string) error
}

type OrderService struct {
	billing   Billing
	inventory Inventory
	mailer    Mailer
	// Adding loyalty points or analytics means editing this struct and Place.
}

// Place couples checkout latency and availability to all three services
// (temporal coupling): if the mailer is down, checkout fails even though the
// order and payment already exist.
func (s *OrderService) Place(ctx context.Context, orderID, customerID string, skus []string, totalMinor int64) error {
	ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
	defer cancel()
	if err := s.inventory.Reserve(ctx, orderID, skus); err != nil {
		return fmt.Errorf("reserve: %w", err)
	}
	if err := s.billing.Charge(ctx, orderID, totalMinor); err != nil {
		return fmt.Errorf("charge: %w", err) // the reservation is now orphaned
	}
	if err := s.mailer.SendConfirmation(ctx, customerID, orderID); err != nil {
		return fmt.Errorf("mail: %w", err) // the customer paid but sees an error
	}
	return nil
}

type okBilling struct{}

func (okBilling) Charge(context.Context, string, int64) error { return nil }

type okInventory struct{}

func (okInventory) Reserve(context.Context, string, []string) error { return nil }

type downMailer struct{}

func (downMailer) SendConfirmation(context.Context, string, string) error {
	return errors.New("smtp relay unavailable")
}

func main() {
	s := &OrderService{billing: okBilling{}, inventory: okInventory{}, mailer: downMailer{}}
	err := s.Place(context.Background(), "ord-1001", "cus-7", []string{"SKU-1"}, 4200)
	log.Printf("checkout result: %v", err) // checkout result: mail: smtp relay unavailable
}

After ​

The contract package defines a CloudEvents-shaped Envelope, a payload sized for its known projections, and Decode, which performs ingress validation and marks every rejection with ErrInvalid.

go
// Package events holds the integration contract shared by the order service
// (producer) and its subscribers. Changing it is a contract change.
package events

import (
	"encoding/json"
	"errors"
	"fmt"
	"time"
)

const (
	SpecVersion     = "1.0"
	ContentTypeJSON = "application/json"
	TypeOrderPlaced = "com.example.orders.order.placed.v1"
	TypeOrderVoided = "com.example.orders.order.cancelled.v1"
	SourceOrders    = "/services/orders"
	maxEnvelopeSize = 64 << 10
)

// ErrInvalid marks a message that this consumer can never process as sent.
// It is an ingress decision about the message, not a refusal of the fact.
var ErrInvalid = errors.New("invalid integration event")

// Envelope uses CloudEvents 1.0 attribute names in structured JSON mode.
// correlationid and causationid are extension attributes, not core ones.
type Envelope struct {
	SpecVersion     string          `json:"specversion"`
	ID              string          `json:"id"`
	Source          string          `json:"source"`
	Type            string          `json:"type"`
	Subject         string          `json:"subject"`
	Time            time.Time       `json:"time"`
	DataContentType string          `json:"datacontenttype"`
	CorrelationID   string          `json:"correlationid"`
	CausationID     string          `json:"causationid,omitempty"`
	Data            json.RawMessage `json:"data"`
}

type Line struct {
	SKU      string `json:"sku"`
	Quantity int    `json:"quantity"`
}

// OrderPlacedV1 carries the state the known projections need (shipping,
// order history), not every field any future consumer might want. It holds
// a customer ID, not the customer's e-mail: the mailer keeps its own customer
// projection fed by the customer service's events.
type OrderPlacedV1 struct {
	OrderID      string `json:"orderId"`
	Revision     int64  `json:"revision"` // aggregate version after this change
	CustomerID   string `json:"customerId"`
	Currency     string `json:"currency"`
	TotalMinor   int64  `json:"totalMinor"`
	ShipCountry  string `json:"shipCountry"`
	Lines        []Line `json:"lines"`
	PlacedAtUnix int64  `json:"placedAt"`
}

// OrderCancelledV1 is a later fact about the same aggregate.
type OrderCancelledV1 struct {
	OrderID  string `json:"orderId"`
	Revision int64  `json:"revision"`
	Reason   string `json:"reason"`
}

// New wraps data in an envelope. causationID is the ID of the message that
// caused this one (empty for a user request); correlationID follows the flow.
func New(id, eventType, subject string, at time.Time, correlationID, causationID string, data any) (Envelope, error) {
	raw, err := json.Marshal(data)
	if err != nil {
		return Envelope{}, err
	}
	return Envelope{
		SpecVersion: SpecVersion, ID: id, Source: SourceOrders, Type: eventType,
		Subject: subject, Time: at.UTC(), DataContentType: ContentTypeJSON,
		CorrelationID: correlationID, CausationID: causationID, Data: raw,
	}, nil
}

// trustedSources maps each accepted type to the only source allowed to emit it.
var trustedSources = map[string]string{
	TypeOrderPlaced: SourceOrders,
	TypeOrderVoided: SourceOrders,
}

// Decode is ingress validation: size, envelope shape, and producer authority.
// Every failure wraps ErrInvalid so a consumer can park it instead of retrying.
func Decode(raw []byte) (Envelope, error) {
	var e Envelope
	if len(raw) > maxEnvelopeSize {
		return e, fmt.Errorf("%w: %d bytes exceeds limit", ErrInvalid, len(raw))
	}
	if err := json.Unmarshal(raw, &e); err != nil {
		return e, fmt.Errorf("%w: %v", ErrInvalid, err)
	}
	switch {
	case e.SpecVersion != SpecVersion:
		return e, fmt.Errorf("%w: specversion %q", ErrInvalid, e.SpecVersion)
	case e.ID == "" || e.Subject == "" || e.CorrelationID == "" || e.Time.IsZero():
		return e, fmt.Errorf("%w: missing id, subject, correlationid or time", ErrInvalid)
	case e.DataContentType != ContentTypeJSON:
		return e, fmt.Errorf("%w: datacontenttype %q", ErrInvalid, e.DataContentType)
	}
	want, known := trustedSources[e.Type]
	if !known || e.Source != want {
		return e, fmt.Errorf("%w: type %q from source %q not accepted", ErrInvalid, e.Type, e.Source)
	}
	return e, nil
}

// OrderPlaced decodes and checks the payload of an already decoded envelope.
func (e Envelope) OrderPlaced() (OrderPlacedV1, error) {
	var d OrderPlacedV1
	if err := json.Unmarshal(e.Data, &d); err != nil {
		return d, fmt.Errorf("%w: data: %v", ErrInvalid, err)
	}
	if d.OrderID != e.Subject || d.Revision < 1 || len(d.Lines) == 0 {
		return d, fmt.Errorf("%w: order payload inconsistent with subject", ErrInvalid)
	}
	for _, l := range d.Lines {
		if l.SKU == "" || l.Quantity < 1 {
			return d, fmt.Errorf("%w: bad line %+v", ErrInvalid, l)
		}
	}
	return d, nil
}

// OrderCancelled decodes the cancellation payload.
func (e Envelope) OrderCancelled() (OrderCancelledV1, error) {
	var d OrderCancelledV1
	if err := json.Unmarshal(e.Data, &d); err != nil {
		return d, fmt.Errorf("%w: data: %v", ErrInvalid, err)
	}
	if d.OrderID != e.Subject || d.Revision < 1 {
		return d, fmt.Errorf("%w: cancellation inconsistent with subject", ErrInvalid)
	}
	return d, nil
}

The projection applies events by revision, so duplicates and late arrivals change nothing, keeps shipping data when a cancellation carries none, reports lag, and can be rebuilt from a replay source. Tests cover duplicates, reordering, invalid payloads and rebuild equivalence.

go
// Package projection keeps a consumer-owned local copy of order state built
// from integration events (event-carried state transfer).
package projection

import (
	"context"
	"fmt"
	"sync"
	"time"

	"academy/event-driven-architecture/after/events"
)

type Summary struct {
	OrderID     string
	Revision    int64
	Status      string // "placed" or "cancelled"
	ShipCountry string
	Lines       []events.Line
	SourceTime  time.Time // event time of the last applied change
}

// Store is the consumer's own database. A real one runs the guarded upsert
// shown in the chapter's SQL so that check-and-write is one statement.
type Store interface {
	Get(ctx context.Context, orderID string) (Summary, bool, error)
	Put(ctx context.Context, s Summary) error
}

type Outcome int

const (
	Applied Outcome = iota
	Stale           // duplicate or older revision: safe to acknowledge
)

type Projector struct {
	Store Store
	Now   func() time.Time
	mu    sync.Mutex
	lag   time.Duration
}

// Lag is the age of the newest applied event when it was applied. Expose it
// as a metric: it is how stale this consumer's view of orders is.
func (p *Projector) Lag() time.Duration {
	p.mu.Lock()
	defer p.mu.Unlock()
	return p.lag
}

// Apply is idempotent and tolerates reordering per order: a revision that is
// not newer than the stored one changes nothing. Errors other than
// events.ErrInvalid are transient (the store failed) and must not be acked.
func (p *Projector) Apply(ctx context.Context, e events.Envelope) (Outcome, error) {
	var next Summary
	switch e.Type {
	case events.TypeOrderPlaced:
		d, err := e.OrderPlaced()
		if err != nil {
			return Stale, err
		}
		next = Summary{OrderID: d.OrderID, Revision: d.Revision, Status: "placed",
			ShipCountry: d.ShipCountry, Lines: d.Lines}
	case events.TypeOrderVoided:
		d, err := e.OrderCancelled()
		if err != nil {
			return Stale, err
		}
		next = Summary{OrderID: d.OrderID, Revision: d.Revision, Status: "cancelled"}
	default:
		return Stale, fmt.Errorf("%w: unhandled type %q", events.ErrInvalid, e.Type)
	}
	cur, found, err := p.Store.Get(ctx, next.OrderID)
	if err != nil {
		return Stale, fmt.Errorf("load %s: %w", next.OrderID, err)
	}
	if found && cur.Revision >= next.Revision {
		return Stale, nil
	}
	if found && next.Status == "cancelled" {
		// Keep the shipping data learned earlier; the cancellation carries none.
		next.ShipCountry, next.Lines = cur.ShipCountry, cur.Lines
	}
	next.SourceTime = e.Time
	if err := p.Store.Put(ctx, next); err != nil {
		return Stale, fmt.Errorf("save %s: %w", next.OrderID, err)
	}
	p.mu.Lock()
	p.lag = p.Now().Sub(e.Time)
	p.mu.Unlock()
	return Applied, nil
}

// Rebuild replays a retained history into an empty store. Run it beside the
// live projection and switch readers only when it has caught up.
func Rebuild(ctx context.Context, next func() (events.Envelope, bool, error), now func() time.Time) (*MemStore, error) {
	fresh := NewMemStore()
	p := &Projector{Store: fresh, Now: now}
	for {
		e, ok, err := next()
		if err != nil {
			return nil, err
		}
		if !ok {
			return fresh, nil
		}
		if _, err := p.Apply(ctx, e); err != nil {
			return nil, fmt.Errorf("replay %s: %w", e.ID, err)
		}
	}
}

// MemStore is a test double; it is not durable.
type MemStore struct {
	mu   sync.Mutex
	rows map[string]Summary
}

func NewMemStore() *MemStore { return &MemStore{rows: map[string]Summary{}} }

func (m *MemStore) Get(_ context.Context, id string) (Summary, bool, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	s, ok := m.rows[id]
	return s, ok, nil
}

func (m *MemStore) Put(_ context.Context, s Summary) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.rows[s.OrderID] = s
	return nil
}
go
package projection

import (
	"context"
	"errors"
	"testing"
	"time"

	"academy/event-driven-architecture/after/events"
)

var t0 = time.Date(2026, 11, 26, 10, 0, 0, 0, time.UTC)

func mustEvent(t *testing.T, id, typ string, rev int64, at time.Time) events.Envelope {
	t.Helper()
	var data any = events.OrderCancelledV1{OrderID: "ord-1", Revision: rev, Reason: "customer"}
	if typ == events.TypeOrderPlaced {
		data = events.OrderPlacedV1{OrderID: "ord-1", Revision: rev, CustomerID: "cus-7",
			Currency: "EUR", TotalMinor: 4200, ShipCountry: "NL",
			Lines: []events.Line{{SKU: "SKU-1", Quantity: 1}}}
	}
	e, err := events.New(id, typ, "ord-1", at, "req-1", "", data)
	if err != nil {
		t.Fatal(err)
	}
	return e
}

func TestDuplicateDeliveryIsStale(t *testing.T) {
	p := &Projector{Store: NewMemStore(), Now: func() time.Time { return t0.Add(3 * time.Second) }}
	e := mustEvent(t, "evt-1", events.TypeOrderPlaced, 1, t0)
	if out, err := p.Apply(context.Background(), e); err != nil || out != Applied {
		t.Fatalf("first: %v %v", out, err)
	}
	if out, err := p.Apply(context.Background(), e); err != nil || out != Stale {
		t.Fatalf("redelivery: %v %v", out, err)
	}
	if p.Lag() != 3*time.Second {
		t.Fatalf("lag %v", p.Lag())
	}
}

func TestOlderRevisionCannotOverwriteNewer(t *testing.T) {
	store := NewMemStore()
	p := &Projector{Store: store, Now: time.Now}
	ctx := context.Background()
	placed := mustEvent(t, "evt-1", events.TypeOrderPlaced, 1, t0)
	cancelled := mustEvent(t, "evt-2", events.TypeOrderVoided, 2, t0.Add(time.Minute))
	for _, e := range []events.Envelope{placed, cancelled, placed} { // redelivered late
		if _, err := p.Apply(ctx, e); err != nil {
			t.Fatal(err)
		}
	}
	s, _, _ := store.Get(ctx, "ord-1")
	if s.Status != "cancelled" || s.Revision != 2 || s.ShipCountry != "NL" {
		t.Fatalf("got %+v", s)
	}
}

func TestInvalidPayloadIsPermanent(t *testing.T) {
	p := &Projector{Store: NewMemStore(), Now: time.Now}
	e := mustEvent(t, "evt-3", events.TypeOrderPlaced, 1, t0)
	e.Data = []byte(`{"orderId":"ord-1","revision":1,"lines":[]}`)
	if _, err := p.Apply(context.Background(), e); !errors.Is(err, events.ErrInvalid) {
		t.Fatalf("want ErrInvalid, got %v", err)
	}
}

func TestRebuildMatchesLive(t *testing.T) {
	history := []events.Envelope{
		mustEvent(t, "evt-1", events.TypeOrderPlaced, 1, t0),
		mustEvent(t, "evt-2", events.TypeOrderVoided, 2, t0.Add(time.Minute)),
	}
	i := 0
	next := func() (events.Envelope, bool, error) {
		if i == len(history) {
			return events.Envelope{}, false, nil
		}
		i++
		return history[i-1], true, nil
	}
	rebuilt, err := Rebuild(context.Background(), next, time.Now)
	if err != nil {
		t.Fatal(err)
	}
	s, ok, _ := rebuilt.Get(context.Background(), "ord-1")
	if !ok || s.Status != "cancelled" || len(s.Lines) != 1 {
		t.Fatalf("rebuilt %+v", s)
	}
}

The Go angle ​

Go has no event bus in the standard library: an in-process domain event is a function call or a channel send, and an integration event is a struct you marshal. Keep the contract in a small package that producer and consumers import, and treat changes to it as API changes. Each consumer owns its loop, its settlement and its client lifecycle; return errors with %w so the original cause survives to the supervisor. The broker examples below compile without a broker (main exits when the URL variable is missing) and use github.com/rabbitmq/amqp091-go, github.com/twmb/franz-go/pkg/kgo and github.com/redis/go-redis/v9. Watermill offers a higher-level router over the same brokers; see Event-Driven Go.

Laravel ​

Before ​

The controller performs every reaction inside the request and even inside the database transaction: a billing timeout rolls back an order that billing may already have charged, and an analytics "notification" is really a command.

php
<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;

// Before: one request performs every reaction synchronously. It works, but
// checkout now depends on billing, shipping and analytics being up, and the
// HTTP calls run inside the database transaction.
class PlaceOrderController
{
    public function __invoke(Request $request): JsonResponse
    {
        $order = DB::transaction(function () use ($request) {
            $order = Order::create($request->only(['customer_id', 'currency', 'total_minor']));

            // A timeout here rolls back the order although billing may have charged.
            Http::timeout(2)->post('https://billing.internal.example/charges', [
                'order_id' => $order->id,
                'amount' => $order->total_minor,
            ])->throw();

            Http::timeout(2)->post('https://shipping.internal.example/shipments', [
                'order_id' => $order->id,
            ])->throw();

            // A "notification" that is really a command to one receiver.
            Http::post('https://analytics.internal.example/order-placed', ['id' => $order->id]);

            return $order;
        });

        return response()->json(['id' => $order->id], 201);
    }
}

After ​

The domain event carries scalars and implements ShouldDispatchAfterCommit:

php
<?php

namespace App\Events;

use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Foundation\Events\Dispatchable;

// Domain event: in-process, internal vocabulary, may change with the model.
// ShouldDispatchAfterCommit orders dispatch after COMMIT (and drops it on
// rollback); it does not make delivery durable if the process dies after commit.
class OrderPlaced implements ShouldDispatchAfterCommit
{
    use Dispatchable;

    public function __construct(
        public readonly int $orderId,
        public readonly int $revision,
        public readonly int $customerId,
        public readonly int $totalMinor,
        public readonly string $currency,
        public readonly string $correlationId,
    ) {}
}

The integration envelope is a separate class built from chosen fields:

php
<?php

namespace App\Messaging;

use App\Events\OrderPlaced;
use DateTimeInterface;
use Illuminate\Support\Str;

// Integration event: a published contract with its own version. It is built
// explicitly from chosen fields, never by serializing a model or domain event.
final class IntegrationEnvelope
{
    public const SOURCE = '/services/orders';

    /**
     * @param  array<string, mixed>  $data
     */
    private function __construct(
        public readonly string $id,
        public readonly string $type,
        public readonly string $subject,
        public readonly DateTimeInterface $time,
        public readonly string $correlationId,
        public readonly ?string $causationId,
        public readonly array $data,
    ) {}

    /**
     * @param  list<array{sku: string, quantity: int}>  $lines
     */
    public static function orderPlaced(OrderPlaced $event, string $shipCountry, array $lines): self
    {
        return new self(
            id: (string) Str::uuid(),
            type: 'com.example.orders.order.placed.v1',
            subject: 'ord-'.$event->orderId,
            time: now(),
            correlationId: $event->correlationId,
            causationId: null,
            data: [
                'orderId' => 'ord-'.$event->orderId,
                'revision' => $event->revision,
                'customerId' => 'cus-'.$event->customerId,
                'currency' => $event->currency,
                'totalMinor' => $event->totalMinor,
                'shipCountry' => $shipCountry,
                'lines' => $lines,
            ],
        );
    }

    /**
     * CloudEvents 1.0 structured JSON; correlationid/causationid are extensions.
     *
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return array_filter([
            'specversion' => '1.0',
            'id' => $this->id,
            'source' => self::SOURCE,
            'type' => $this->type,
            'subject' => $this->subject,
            'time' => $this->time->format(DATE_RFC3339),
            'datacontenttype' => 'application/json',
            'correlationid' => $this->correlationId,
            'causationid' => $this->causationId,
            'data' => $this->data,
        ], fn ($value) => $value !== null);
    }
}

The action writes the order and the outbox row in one transaction, then dispatches the domain event, which Laravel holds until COMMIT:

php
<?php

namespace App\Actions;

use App\Events\OrderPlaced;
use App\Messaging\IntegrationEnvelope;
use App\Models\Order;
use Illuminate\Support\Facades\DB;

final class PlaceOrder
{
    /**
     * @param  list<array{sku: string, quantity: int}>  $lines
     */
    public function __invoke(int $customerId, string $currency, int $totalMinor, string $shipCountry, array $lines, string $correlationId): Order
    {
        return DB::transaction(function () use ($customerId, $currency, $totalMinor, $shipCountry, $lines, $correlationId) {
            $order = Order::create([
                'customer_id' => $customerId,
                'currency' => $currency,
                'total_minor' => $totalMinor,
                'ship_country' => $shipCountry,
                'revision' => 1,
            ]);

            $event = new OrderPlaced($order->id, 1, $customerId, $totalMinor, $currency, $correlationId);

            // Durable publication: the outbox row commits with the order. A relay
            // (see the outbox chapter) publishes it to the broker later.
            $envelope = IntegrationEnvelope::orderPlaced($event, $shipCountry, $lines);
            DB::table('outbox_messages')->insert([
                'id' => $envelope->id,
                'topic' => 'orders.events.v1',
                'message_key' => $envelope->subject,
                'payload' => json_encode($envelope->toArray(), JSON_THROW_ON_ERROR),
                'created_at' => now(),
            ]);

            // In-process reactions inside this service run after COMMIT.
            event($event);

            return $order;
        });
    }
}

A queued listener (one class per file, discovered from app/Listeners) updates a local read model through an idempotent projector:

php
<?php

namespace App\Listeners;

use App\Events\OrderPlaced;
use App\Models\Order;
use App\Projections\OrderSummaryProjector;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\Attributes\Tries;

// Discovered automatically: one listener class per file in app/Listeners,
// with handle() type-hinting the event. Queued listeners retry, so the
// projector itself must be idempotent; the queue does not deduplicate.
#[Tries(5)]
class RecordOrderSummary implements ShouldQueue
{
    public function __construct(private readonly OrderSummaryProjector $projector) {}

    public function handle(OrderPlaced $event): void
    {
        $order = Order::findOrFail($event->orderId);

        $this->projector->apply(
            'ord-'.$event->orderId,
            $event->revision,
            'placed',
            $order->ship_country,
            $order->created_at->toIso8601String(),
        );
    }
}
php
<?php

namespace App\Projections;

use Illuminate\Support\Facades\DB;

// A consumer-owned read model. The WHERE clause makes the upsert idempotent
// and immune to an older revision arriving late (PostgreSQL syntax).
final class OrderSummaryProjector
{
    public function apply(string $orderId, int $revision, string $status, string $shipCountry, string $sourceTime): bool
    {
        return DB::update(<<<'SQL'
            INSERT INTO order_summaries (order_id, revision, status, ship_country, source_time, updated_at)
            VALUES (?, ?, ?, ?, ?, now())
            ON CONFLICT (order_id) DO UPDATE
               SET revision = EXCLUDED.revision, status = EXCLUDED.status,
                   ship_country = EXCLUDED.ship_country, source_time = EXCLUDED.source_time,
                   updated_at = now()
             WHERE order_summaries.revision < EXCLUDED.revision
            SQL, [$orderId, $revision, $status, $shipCountry, $sourceTime]) === 1;
    }
}

The Laravel angle ​

Laravel 13's event docs say a ShouldDispatchAfterCommit event is not dispatched "until the current database transaction is committed. If the transaction fails, the event will be discarded." That is an ordering guarantee inside one process. If PHP dies between COMMIT and dispatch, nothing replays the event; that is why the integration event goes to outbox_messages in the same transaction, and a relay publishes it (see Outbox). Queued listeners have their own knob, ShouldQueueAfterCommit, and the queue connection's after_commit option.

Event discovery: "Laravel will automatically find and register your event listeners by scanning your application's Listeners directory", using handle or __invoke methods whose parameter is type-hinted with the event. That is why each listener lives in its own PSR-4 file; check with php artisan event:list. A queued listener with #[Tries(5)] can run more than once, so the projector's guarded upsert, not the queue, provides idempotency. Event::fake() asserts dispatch in tests (Testing Messaging).

Laravel featureUse hereWhat it does not do
ShouldDispatchAfterCommitDomain event after COMMITSurvive a crash after commit
ShouldQueue listenerOff-request reaction in the same appCross-service contract
ShouldQueueAfterCommit / after_commitQueue job after COMMITDurable publication to a broker
#[Tries], #[Backoff]Bounded retriesDeduplicate effects
Event::defer()Delay listeners until a block finishesTransactional outbox
BroadcastingPush projection updates to browsersReplace integration events

Broker differences ​

Producer ownsSubscriber ownsRabbitMQtopic exchange orders.eventsqueue shipping.order-events + binding order.*.v1 + DLXKafkatopic orders.events.v1 + retentionconsumer group shipping-projection + offsetsRedis Streamsstream orders.events.v1 + MAXLENgroup shipping-projection + PEL + XACKA new subscriber adds its own queue, group or binding. The producer ships no change and never lists its consumers.

RabbitMQ ​

The producer owns a durable topic exchange (orders.events); each subscriber owns its queue, its binding (order.*.v1) and its dead-letter route. A new subscriber is a new queue and binding: no producer release. The package README of vladimir-yuldashev/laravel-queue-rabbitmq puts it the same way for exchanges with routing keys: "you probably create your queues with bindings yourself." That package is a "RabbitMQ Queue driver for Laravel" for jobs, not an integration-event publisher; integration events are better published by the outbox relay with the raw client.

go
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"sync"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"

	"academy/event-driven-architecture/after/events"
)

// The producer owns only its exchange. It never declares subscriber queues:
// a new subscriber binds its own queue without a producer release.
const exchange = "orders.events"

var (
	ErrUnroutable = errors.New("broker returned message: no queue bound for routing key")
	ErrNacked     = errors.New("broker nacked publish")
)

func declareExchange(ch *amqp.Channel) error {
	return ch.ExchangeDeclare(exchange, amqp.ExchangeTopic, true, false, false, false, nil)
}

type Publisher struct {
	mu      sync.Mutex // one in-flight publish keeps return matching simple
	ch      *amqp.Channel
	returns chan amqp.Return
}

// NewPublisher puts the channel in confirm mode and registers the return
// listener before the first publish, as the broker requires.
func NewPublisher(ch *amqp.Channel) (*Publisher, error) {
	if err := ch.Confirm(false); err != nil {
		return nil, fmt.Errorf("enable confirms: %w", err)
	}
	return &Publisher{ch: ch, returns: ch.NotifyReturn(make(chan amqp.Return, 1))}, nil
}

func routingKey(e events.Envelope) string {
	switch e.Type {
	case events.TypeOrderPlaced:
		return "order.placed.v1"
	case events.TypeOrderVoided:
		return "order.cancelled.v1"
	}
	return "order.unknown"
}

func toPublishing(e events.Envelope) (amqp.Publishing, error) {
	body, err := json.Marshal(e)
	if err != nil {
		return amqp.Publishing{}, err
	}
	return amqp.Publishing{
		ContentType: "application/cloudevents+json", DeliveryMode: amqp.Persistent,
		MessageId: e.ID, CorrelationId: e.CorrelationID, Type: e.Type,
		Timestamp: e.Time, Body: body,
	}, nil
}

// Publish succeeds only after a broker ack with no basic.return. RabbitMQ
// sends basic.return before basic.ack, and the client delivers it to the
// buffered returns channel before it records the ack.
func (p *Publisher) Publish(ctx context.Context, e events.Envelope) error {
	msg, err := toPublishing(e)
	if err != nil {
		return err
	}
	p.mu.Lock()
	defer p.mu.Unlock()
	for drained := false; !drained; { // discard a late return left by a timed-out publish
		select {
		case <-p.returns:
		default:
			drained = true
		}
	}
	ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()
	dc, err := p.ch.PublishWithDeferredConfirmWithContext(ctx, exchange, routingKey(e), true, false, msg)
	if err != nil {
		return fmt.Errorf("publish %s: %w", e.ID, err)
	}
	acked, err := dc.WaitContext(ctx)
	if err != nil {
		return fmt.Errorf("confirm %s: outcome unknown: %w", e.ID, err) // keep it in the outbox
	}
	select {
	case r := <-p.returns:
		if r.MessageId == e.ID {
			return fmt.Errorf("%w: %s (%d %s)", ErrUnroutable, r.RoutingKey, r.ReplyCode, r.ReplyText)
		}
	default:
	}
	if !acked {
		return fmt.Errorf("%w: %s", ErrNacked, e.ID)
	}
	return nil
}

The publisher enables confirms and registers a return listener before publishing with mandatory=true. RabbitMQ documents that a mandatory unroutable message "will be returned to it. The publisher must have a returned message handler set up", and that "the basic.return is sent to the client before basic.ack". So an ack alone does not mean any subscriber received the event; the code treats a return as ErrUnroutable and a confirm timeout as an unknown outcome, leaving the row in the outbox. Without mandatory, an unroutable message "is discarded or republished to an alternate exchange". Choose deliberately: an alternate exchange that keeps unrouted events is often better than failing publication while no one subscribes yet.

go
package main

import (
	"context"
	"errors"
	"fmt"

	amqp "github.com/rabbitmq/amqp091-go"

	"academy/event-driven-architecture/after/events"
)

// declareSubscription is run by the SUBSCRIBER (shipping, mailer, ...). The
// queue, its binding and its dead-letter route belong to that team.
func declareSubscription(ch *amqp.Channel, service string) (string, error) {
	queue := service + ".order-events"
	dlx := service + ".dlx"
	if err := ch.ExchangeDeclare(dlx, amqp.ExchangeFanout, true, false, false, false, nil); err != nil {
		return "", err
	}
	if _, err := ch.QueueDeclare(service+".order-events.parked", true, false, false, false,
		amqp.Table{"x-queue-type": "quorum"}); err != nil {
		return "", err
	}
	if err := ch.QueueBind(service+".order-events.parked", "", dlx, false, nil); err != nil {
		return "", err
	}
	// Quorum queues cap redeliveries (RabbitMQ 4.0+ default delivery-limit 20);
	// it is set explicitly so the bound is visible and dead letters are kept.
	if _, err := ch.QueueDeclare(queue, true, false, false, false, amqp.Table{
		"x-queue-type": "quorum", "x-delivery-limit": 10, "x-dead-letter-exchange": dlx,
	}); err != nil {
		return "", err
	}
	// Bind only what this service needs; the producer is not consulted.
	if err := ch.QueueBind(queue, "order.*.v1", exchange, false, nil); err != nil {
		return "", err
	}
	return queue, nil
}

type Handler func(ctx context.Context, e events.Envelope) error

// settle maps the handler outcome to exactly one settlement call and returns
// the settlement error: an unknown ack outcome stops the consumer.
func settle(ctx context.Context, d amqp.Delivery, h Handler) error {
	e, err := events.Decode(d.Body)
	if err == nil {
		err = h(ctx, e)
	}
	switch {
	case err == nil:
		return d.Ack(false)
	case errors.Is(err, events.ErrInvalid):
		return d.Reject(false) // dead-lettered to the parking queue, never requeued
	default:
		// Transient: requeue; the quorum delivery-limit bounds a hot loop.
		// Delayed retry schedules belong to the retry chapter, not here.
		return d.Nack(false, true)
	}
}

func consume(ctx context.Context, ch *amqp.Channel, queue string, h Handler) error {
	if err := ch.Qos(20, 0, false); err != nil {
		return err
	}
	deliveries, err := ch.ConsumeWithContext(ctx, queue, "", false, false, false, false, nil)
	if err != nil {
		return err
	}
	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		case d, ok := <-deliveries:
			if !ok {
				return errors.New("delivery channel closed: reconnect and redeclare")
			}
			if err := settle(ctx, d, h); err != nil {
				return fmt.Errorf("settle tag %d: %w", d.DeliveryTag, err)
			}
		}
	}
}

The subscriber declares a quorum queue with an explicit x-delivery-limit and DLX. Invalid messages are rejected without requeue (dead-lettered), transient failures are requeued, and the delivery limit (the quorum default has been 20 "Starting with RabbitMQ 4.0") prevents an endless hot loop of a poison message. Settlement errors stop the consumer. Delayed retry belongs to Retry & Backoff; the parking workflow to DLQ.

go
package main

import (
	"context"
	"errors"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"

	"academy/event-driven-architecture/after/events"
	"academy/event-driven-architecture/after/projection"
)

// Usage: AMQP_URL=... go run ./after/rabbitmq publish|subscribe
// Publisher and subscriber are separate deployments; they share only the
// exchange name and the events package.
func main() {
	url := os.Getenv("AMQP_URL")
	if url == "" || len(os.Args) < 2 {
		log.Print("set AMQP_URL and pass publish or subscribe")
		return
	}
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	conn, err := amqp.Dial(url)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()
	ch, err := conn.Channel()
	if err != nil {
		log.Fatal(err)
	}
	if err := run(ctx, ch, os.Args[1]); err != nil && !errors.Is(err, context.Canceled) {
		log.Fatal(err)
	}
}

func run(ctx context.Context, ch *amqp.Channel, role string) error {
	switch role {
	case "publish":
		if err := declareExchange(ch); err != nil {
			return err
		}
		p, err := NewPublisher(ch)
		if err != nil {
			return err
		}
		e, err := events.New("evt-1001-1", events.TypeOrderPlaced, "ord-1001", time.Now(), "req-42", "",
			events.OrderPlacedV1{OrderID: "ord-1001", Revision: 1, CustomerID: "cus-7", Currency: "EUR",
				TotalMinor: 4200, ShipCountry: "NL", Lines: []events.Line{{SKU: "SKU-1", Quantity: 1}}})
		if err != nil {
			return err
		}
		return p.Publish(ctx, e) // in production an outbox relay calls this
	case "subscribe":
		// The subscriber checks the exchange exists instead of owning it.
		if err := ch.ExchangeDeclarePassive(exchange, amqp.ExchangeTopic, true, false, false, false, nil); err != nil {
			return err
		}
		queue, err := declareSubscription(ch, "shipping")
		if err != nil {
			return err
		}
		proj := &projection.Projector{Store: projection.NewMemStore(), Now: time.Now}
		return consume(ctx, ch, queue, func(ctx context.Context, e events.Envelope) error {
			_, err := proj.Apply(ctx, e)
			return err
		})
	}
	return errors.New("role must be publish or subscribe")
}
go
package main

import (
	"context"
	"encoding/json"
	"errors"
	"testing"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"

	"academy/event-driven-architecture/after/events"
)

type recorder struct {
	call string
	err  error
}

func (r *recorder) Ack(uint64, bool) error { r.call = "ack"; return r.err }
func (r *recorder) Nack(_ uint64, _ bool, requeue bool) error {
	r.call = map[bool]string{true: "nack-requeue", false: "nack-drop"}[requeue]
	return r.err
}
func (r *recorder) Reject(_ uint64, requeue bool) error {
	r.call = map[bool]string{true: "reject-requeue", false: "reject-dead-letter"}[requeue]
	return r.err
}

func body(t *testing.T) []byte {
	t.Helper()
	e, err := events.New("evt-1", events.TypeOrderPlaced, "ord-1", time.Now(), "req-1", "",
		events.OrderPlacedV1{OrderID: "ord-1", Revision: 1, Lines: []events.Line{{SKU: "A", Quantity: 1}}})
	if err != nil {
		t.Fatal(err)
	}
	b, _ := json.Marshal(e)
	return b
}

func TestSettlement(t *testing.T) {
	ok := func(context.Context, events.Envelope) error { return nil }
	down := func(context.Context, events.Envelope) error { return errors.New("db timeout") }
	cases := []struct {
		name string
		body []byte
		h    Handler
		want string
	}{
		{"valid", body(t), ok, "ack"},
		{"poison never requeued", []byte(`{"specversion":"1.0"}`), ok, "reject-dead-letter"},
		{"transient requeued", body(t), down, "nack-requeue"},
	}
	for _, c := range cases {
		r := &recorder{}
		if err := settle(context.Background(), amqp.Delivery{Acknowledger: r, Body: c.body}, c.h); err != nil {
			t.Fatalf("%s: %v", c.name, err)
		}
		if r.call != c.want {
			t.Fatalf("%s: got %s want %s", c.name, r.call, c.want)
		}
	}
}

func TestSettlementErrorPropagates(t *testing.T) {
	r := &recorder{err: amqp.ErrClosed}
	ok := func(context.Context, events.Envelope) error { return nil }
	if err := settle(context.Background(), amqp.Delivery{Acknowledger: r, Body: body(t)}, ok); !errors.Is(err, amqp.ErrClosed) {
		t.Fatalf("want channel error, got %v", err)
	}
}

func TestPublishingCarriesIdentity(t *testing.T) {
	var e events.Envelope
	_ = json.Unmarshal(body(t), &e)
	msg, err := toPublishing(e)
	if err != nil || msg.MessageId != "evt-1" || msg.CorrelationId != "req-1" ||
		msg.DeliveryMode != amqp.Persistent || routingKey(e) != "order.placed.v1" {
		t.Fatalf("publishing %+v err %v", msg, err)
	}
}

What is missing: replay. An exchange keeps nothing; a queue created today never sees yesterday's events. Bootstrap from a snapshot (bind first), or use RabbitMQ streams, which are outside this chapter.

Kafka ​

The producer owns the topic (partitions, retention.ms, cleanup.policy); each subscriber owns a consumer group and its committed offsets. Records are keyed by subject, so one order's events stay in one partition and in order. ProduceSync returns only after the broker acknowledges (franz-go defaults to acks=all with idempotent production).

go
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"os"
	"os/signal"
	"strings"
	"syscall"
	"time"

	"github.com/twmb/franz-go/pkg/kgo"

	"academy/event-driven-architecture/after/events"
	"academy/event-driven-architecture/after/projection"
)

const (
	topic     = "orders.events.v1"
	parkTopic = "orders.events.v1.shipping-projection.DLT"
	maxBatch  = 100
)

// toRecord keys by order so every change to one order lands in one partition
// and is read in order by one group member.
func toRecord(e events.Envelope) (*kgo.Record, error) {
	v, err := json.Marshal(e)
	if err != nil {
		return nil, err
	}
	return &kgo.Record{Topic: topic, Key: []byte(e.Subject), Value: v, Headers: []kgo.RecordHeader{
		{Key: "content-type", Value: []byte("application/cloudevents+json")},
		{Key: "ce_id", Value: []byte(e.ID)},
		{Key: "ce_type", Value: []byte(e.Type)},
	}}, nil
}

func publish(ctx context.Context, cl *kgo.Client, e events.Envelope) error {
	r, err := toRecord(e)
	if err != nil {
		return err
	}
	// ProduceSync waits for the broker's ack (acks=all is the franz-go default).
	return cl.ProduceSync(ctx, r).FirstErr()
}

func publishSample(ctx context.Context, brokers []string) error {
	cl, err := kgo.NewClient(kgo.SeedBrokers(brokers...))
	if err != nil {
		return err
	}
	defer cl.Close()
	e, err := events.New("evt-1001-1", events.TypeOrderPlaced, "ord-1001", time.Now(), "req-42", "",
		events.OrderPlacedV1{OrderID: "ord-1001", Revision: 1, CustomerID: "cus-7", Currency: "EUR",
			TotalMinor: 4200, ShipCountry: "NL", Lines: []events.Line{{SKU: "SKU-1", Quantity: 1}}})
	if err != nil {
		return err
	}
	return publish(ctx, cl, e) // in production an outbox relay calls publish
}

type parker func(ctx context.Context, r *kgo.Record, cause error) error

// applyBatch applies every record or returns the first non-parkable error.
// Nothing from a failed batch is committed; the applied prefix is replayed
// later and the projection ignores it by revision.
func applyBatch(ctx context.Context, p *projection.Projector, park parker, rs []*kgo.Record) error {
	for _, r := range rs {
		e, err := events.Decode(r.Value)
		if err == nil {
			_, err = p.Apply(ctx, e)
		}
		if errors.Is(err, events.ErrInvalid) {
			if perr := park(ctx, r, err); perr != nil {
				return fmt.Errorf("park %s/%d@%d: %w (cause: %v)", r.Topic, r.Partition, r.Offset, perr, err)
			}
			continue
		}
		if err != nil {
			return fmt.Errorf("apply %s/%d@%d: %w", r.Topic, r.Partition, r.Offset, err)
		}
	}
	return nil
}

// project owns the client for its whole life. After any failure it returns;
// the client's in-memory position is already past the failed batch, so the
// only safe continuation is a NEW client that resumes from committed offsets.
func project(ctx context.Context, brokers []string, group string, p *projection.Projector) error {
	cl, err := kgo.NewClient(
		kgo.SeedBrokers(brokers...),
		kgo.ConsumerGroup(group),
		kgo.ConsumeTopics(topic),
		// A brand-new group (or a rebuild group) starts at the oldest RETAINED
		// record, which is only full history if retention kept it.
		kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
		kgo.DisableAutoCommit(),
		kgo.BlockRebalanceOnPoll(),
		kgo.RebalanceTimeout(60*time.Second),
	)
	if err != nil {
		return err
	}
	defer cl.CloseAllowingRebalance()
	park := func(ctx context.Context, r *kgo.Record, cause error) error {
		headers := append(append([]kgo.RecordHeader(nil), r.Headers...),
			kgo.RecordHeader{Key: "dlt.reason", Value: []byte(cause.Error())})
		out := &kgo.Record{Topic: parkTopic, Key: r.Key, Value: r.Value, Headers: headers}
		return cl.ProduceSync(ctx, out).FirstErr()
	}
	for {
		fetches := cl.PollRecords(ctx, maxBatch) // bounded work while rebalances wait
		if fetches.IsClientClosed() || ctx.Err() != nil {
			cl.AllowRebalance()
			return ctx.Err()
		}
		if errs := fetches.Errors(); len(errs) > 0 {
			cl.AllowRebalance()
			return fmt.Errorf("fetch %s/%d: %w", errs[0].Topic, errs[0].Partition, errs[0].Err)
		}
		batchCtx, cancel := context.WithTimeout(ctx, 30*time.Second) // below RebalanceTimeout
		err := applyBatch(batchCtx, p, park, fetches.Records())
		if err == nil {
			err = cl.CommitRecords(batchCtx, fetches.Records()...)
		}
		cancel()
		cl.AllowRebalance()
		if err != nil {
			return err
		}
	}
}

func main() {
	brokers := os.Getenv("KAFKA_BROKERS")
	if brokers == "" {
		log.Print("set KAFKA_BROKERS to run")
		return
	}
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	if len(os.Args) > 1 && os.Args[1] == "publish" {
		if err := publishSample(ctx, strings.Split(brokers, ",")); err != nil {
			log.Fatal(err)
		}
		return
	}
	group := os.Getenv("GROUP") // e.g. shipping-projection-v2 for a rebuild
	if group == "" {
		group = "shipping-projection-v1"
	}
	p := &projection.Projector{Store: projection.NewMemStore(), Now: time.Now}
	// Restart with a fresh client after each failure; a supervisor would
	// add backoff and alerting. A cancelled context ends the loop.
	for {
		err := project(ctx, strings.Split(brokers, ","), group, p)
		if ctx.Err() != nil {
			return
		}
		log.Printf("projection stopped, restarting from committed offsets: %v", err)
		time.Sleep(2 * time.Second)
	}
}

Starting offsets are a choice, not a law. Kafka documents auto.offset.reset as "What to do when there is no initial offset in Kafka or if the current offset does not exist any more on the server", with latest as the default; the example sets earliest (NewOffset().AtStart()) because a projection must bootstrap. Even then it starts from the oldest retained record: retention "represents an SLA on how soon consumers must read their data." A compacted topic keeps "at least the last known value for each message key", which suits state transfer but loses intermediate changes.

The loop polls at most 100 records with BlockRebalanceOnPoll, applies them under a 30-second context below the 60-second rebalance timeout, commits, then calls AllowRebalance. On any failure it returns instead of continuing: the client's in-memory position has already moved past the failed batch, so continuing on the same client and committing a later batch would skip it. The caller closes the client (CloseAllowingRebalance, needed because rebalances are blocked) and starts a new one, which resumes from the last committed offsets; the applied prefix is replayed and ignored by revision. Invalid records go to a consumer-owned dead-letter topic before commit; if parking fails the batch fails and the park error wraps the original cause.

go
package main

import (
	"context"
	"errors"
	"testing"
	"time"

	"github.com/twmb/franz-go/pkg/kgo"

	"academy/event-driven-architecture/after/events"
	"academy/event-driven-architecture/after/projection"
)

func record(t *testing.T, rev int64) *kgo.Record {
	t.Helper()
	e, err := events.New("evt-x", events.TypeOrderPlaced, "ord-1", time.Now(), "req-1", "",
		events.OrderPlacedV1{OrderID: "ord-1", Revision: rev, Lines: []events.Line{{SKU: "A", Quantity: 1}}})
	if err != nil {
		t.Fatal(err)
	}
	r, err := toRecord(e)
	if err != nil {
		t.Fatal(err)
	}
	if string(r.Key) != "ord-1" {
		t.Fatalf("key %q", r.Key)
	}
	return r
}

func TestPoisonIsParkedAndBatchContinues(t *testing.T) {
	p := &projection.Projector{Store: projection.NewMemStore(), Now: time.Now}
	var parked int
	park := func(context.Context, *kgo.Record, error) error { parked++; return nil }
	rs := []*kgo.Record{record(t, 1), {Topic: topic, Value: []byte("not json")}, record(t, 2)}
	if err := applyBatch(context.Background(), p, park, rs); err != nil {
		t.Fatal(err)
	}
	s, _, _ := p.Store.Get(context.Background(), "ord-1")
	if parked != 1 || s.Revision != 2 {
		t.Fatalf("parked=%d revision=%d", parked, s.Revision)
	}
}

func TestParkFailureStopsBatchWithCause(t *testing.T) {
	p := &projection.Projector{Store: projection.NewMemStore(), Now: time.Now}
	down := errors.New("DLT unavailable")
	park := func(context.Context, *kgo.Record, error) error { return down }
	err := applyBatch(context.Background(), p, park, []*kgo.Record{{Topic: topic, Value: []byte("{}")}})
	if !errors.Is(err, down) {
		t.Fatalf("want park error preserved, got %v", err)
	}
}

For Laravel, mateusjunges/laravel-kafka publishes with Kafka::publish(...). As the DLQ chapter documents, verify delivery reports before marking an outbox row published; publishing from a request without the outbox reintroduces the crash gap.

Redis Streams ​

The producer owns the stream key and its trimming policy; each subscriber owns a consumer group, its consumers and its PEL (pending entries list). XADD appends, XREADGROUP ... > reads entries "never delivered to any other consumer", XACK removes the entry from that group's PEL. A new group created at 0 reads all retained entries; at $, only new ones.

go
package main

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"os"
	"os/signal"
	"strings"
	"syscall"
	"time"

	"github.com/redis/go-redis/v9"

	"academy/event-driven-architecture/after/events"
	"academy/event-driven-architecture/after/projection"
)

const (
	stream      = "orders.events.v1"
	invalid     = "orders.events.v1.invalid"
	group       = "shipping-projection"
	reclaimIdle = time.Minute
	// MAXLEN trims by count, and by default (KEEPREF) it removes entries even
	// if a group has not acknowledged them. Size it from the slowest group's
	// recovery SLA times the peak write rate, and alert on group lag.
	approxMaxLen = 5_000_000
)

func publish(ctx context.Context, rdb *redis.Client, e events.Envelope) (string, error) {
	body, err := json.Marshal(e)
	if err != nil {
		return "", err
	}
	return rdb.XAdd(ctx, &redis.XAddArgs{
		Stream: stream, MaxLen: approxMaxLen, Approx: true,
		Values: map[string]any{"event": body, "type": e.Type},
	}).Result()
}

// bootstrap is a consumer-owned step: "0" makes a new group read the whole
// retained stream (a rebuild); "$" would mean "only events from now on".
func bootstrap(ctx context.Context, rdb *redis.Client) error {
	err := rdb.XGroupCreateMkStream(ctx, stream, group, "0").Err()
	if err != nil && !strings.HasPrefix(err.Error(), "BUSYGROUP") {
		return err
	}
	return nil
}

func envelopeBytes(values map[string]any) ([]byte, error) {
	s, ok := values["event"].(string)
	if !ok {
		return nil, fmt.Errorf("%w: entry has no string field event", events.ErrInvalid)
	}
	return []byte(s), nil
}

type worker struct {
	rdb      *redis.Client
	consumer string // unique per process incarnation
	proj     *projection.Projector
}

// handle applies one entry, parks permanent failures, and only then XACKs.
// A transient error returns before XACK: the entry stays in the PEL.
func (w *worker) handle(ctx context.Context, m redis.XMessage) error {
	raw, err := envelopeBytes(m.Values)
	var e events.Envelope
	if err == nil {
		e, err = events.Decode(raw)
	}
	if err == nil {
		_, err = w.proj.Apply(ctx, e)
	}
	if errors.Is(err, events.ErrInvalid) {
		if perr := w.rdb.XAdd(ctx, &redis.XAddArgs{Stream: invalid, Values: map[string]any{
			"source_id": m.ID, "reason": err.Error(), "consumer": w.consumer}}).Err(); perr != nil {
			return fmt.Errorf("park %s: %w", m.ID, perr)
		}
	} else if err != nil {
		return fmt.Errorf("apply %s: %w", m.ID, err)
	}
	n, err := w.rdb.XAck(ctx, stream, group, m.ID).Result()
	if err != nil {
		return fmt.Errorf("xack %s: %w", m.ID, err)
	}
	if n == 0 {
		log.Printf("xack %s: no longer pending for %s (claimed elsewhere?)", m.ID, group)
	}
	return nil
}

// reclaim walks the whole PEL with XAUTOCLAIM. Entries trimmed before anyone
// acknowledged them are dropped from the PEL by Redis 7+ and never returned:
// that loss is what the MAXLEN sizing above must prevent.
func (w *worker) reclaim(ctx context.Context) error {
	start := "0-0"
	for {
		msgs, next, err := w.rdb.XAutoClaim(ctx, &redis.XAutoClaimArgs{
			Stream: stream, Group: group, Consumer: w.consumer,
			MinIdle: reclaimIdle, Start: start, Count: 100,
		}).Result()
		if err != nil {
			return fmt.Errorf("xautoclaim: %w", err)
		}
		for _, m := range msgs {
			if err := w.handle(ctx, m); err != nil {
				return err
			}
		}
		if next == "0-0" {
			return nil
		}
		start = next
	}
}

func (w *worker) run(ctx context.Context) error {
	lastReclaim := time.Time{}
	for ctx.Err() == nil {
		if time.Since(lastReclaim) > reclaimIdle {
			if err := w.reclaim(ctx); err != nil {
				return err
			}
			lastReclaim = time.Now()
		}
		res, err := w.rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
			Group: group, Consumer: w.consumer, Streams: []string{stream, ">"},
			Count: 50, Block: 5 * time.Second, // bounded so reclaim and shutdown run
		}).Result()
		if errors.Is(err, redis.Nil) {
			continue
		}
		if err != nil {
			return fmt.Errorf("xreadgroup: %w", err)
		}
		for _, s := range res {
			for _, m := range s.Messages {
				if err := w.handle(ctx, m); err != nil {
					return err
				}
			}
		}
	}
	return ctx.Err()
}

func main() {
	addr := os.Getenv("REDIS_ADDR")
	if addr == "" {
		log.Print("set REDIS_ADDR to run")
		return
	}
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	rdb := redis.NewClient(&redis.Options{Addr: addr})
	defer rdb.Close()
	if len(os.Args) > 1 && os.Args[1] == "publish" {
		e, err := events.New("evt-1001-1", events.TypeOrderPlaced, "ord-1001", time.Now(), "req-42", "",
			events.OrderPlacedV1{OrderID: "ord-1001", Revision: 1, CustomerID: "cus-7", Currency: "EUR",
				TotalMinor: 4200, ShipCountry: "NL", Lines: []events.Line{{SKU: "SKU-1", Quantity: 1}}})
		if err == nil {
			var id string
			id, err = publish(ctx, rdb, e)
			log.Printf("XADD id=%s", id)
		}
		if err != nil {
			log.Fatal(err)
		}
		return
	}
	if err := bootstrap(ctx, rdb); err != nil {
		log.Fatal(err)
	}
	suffix := make([]byte, 8)
	if _, err := rand.Read(suffix); err != nil {
		log.Fatal(err)
	}
	host, _ := os.Hostname()
	w := &worker{rdb: rdb, consumer: host + "-" + hex.EncodeToString(suffix),
		proj: &projection.Projector{Store: projection.NewMemStore(), Now: time.Now}}
	if err := w.run(ctx); err != nil && !errors.Is(err, context.Canceled) {
		log.Fatal(err)
	}
}

MAXLEN is the trap. By default (KEEPREF) trimming "removes entries from the stream according to the specified strategy (MAXLEN or MINID), regardless of whether they are referenced by any consumer groups". A slow or broken group therefore loses unprocessed bodies; when XAUTOCLAIM later meets such an entry it "does not claim it, and deletes it from the PEL" (Redis 7.0+). Size MAXLEN or MINID from the slowest group's recovery SLA, alert on group lag, or on Redis 8.2+ consider ACKED, which trims only entries acknowledged by all groups (at the cost of unbounded growth while a group is stuck). The Go worker uses a unique consumer name per process incarnation, bounds its blocking read to 5 s, checks the XACK result, and runs an XAUTOCLAIM sweep over the full cursor as its recovery hook.

Laravel talks to streams through the Redis facade (Laravel's redis queue driver uses lists and sorted sets, not streams). The publisher is called by the outbox relay; the consumer is an Artisan command:

php
<?php

namespace App\Messaging;

use Illuminate\Support\Facades\Redis;
use RuntimeException;

// Called by the outbox relay, not by the request: the outbox row stays
// unpublished until XADD has returned an entry ID.
final class RedisStreamPublisher
{
    public const STREAM = 'orders.events.v1';

    // Approximate trim (~). By default trimming also removes entries that a
    // consumer group has not acknowledged yet: size it from the recovery SLA.
    private const APPROX_MAXLEN = 5_000_000;

    /**
     * @param  array<string, mixed>  $envelope
     */
    public function publish(array $envelope): string
    {
        $id = Redis::connection('streams')->xadd(
            self::STREAM,
            '*',
            ['event' => json_encode($envelope, JSON_THROW_ON_ERROR), 'type' => $envelope['type']],
            self::APPROX_MAXLEN,
            true,
        );

        if (! is_string($id) || $id === '') {
            throw new RuntimeException('XADD did not return an entry ID');
        }

        return $id;
    }
}
php
<?php

namespace App\Console\Commands;

use App\Projections\OrderSummaryProjector;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
use JsonException;
use RuntimeException;

// The group is created by this service's deployment, not by the producer:
//   XGROUP CREATE orders.events.v1 shipping-projection 0 MKSTREAM
// (remember the connection prefix when you run that by hand).
// Recovery of entries left pending by a crashed incarnation is a separate
// sweep (XAUTOCLAIM in the Go example); this loop only reads new entries.
class ConsumeOrderEvents extends Command
{
    protected $signature = 'orders:consume-events';

    protected $description = 'Project order integration events from Redis Streams';

    private const STREAM = 'orders.events.v1';

    private const GROUP = 'shipping-projection';

    public function handle(OrderSummaryProjector $projector): int
    {
        $redis = Redis::connection('streams');
        // Unique per process incarnation, so a restarted worker never inherits
        // the identity (and PEL) of a stale one by accident.
        $consumer = gethostname().'-'.bin2hex(random_bytes(8));

        while (true) {
            $batch = $redis->xreadgroup(self::GROUP, $consumer, [self::STREAM => '>'], 50, 5000);

            if (! is_array($batch) || $batch === []) {
                continue; // block timed out; connection errors throw instead
            }

            // Iterate the returned streams: the reply's keys can carry the
            // connection prefix, so never index by the bare stream name.
            foreach ($batch as $entries) {
                foreach ($entries as $id => $fields) {
                    $this->project($projector, $fields);

                    $acked = $redis->xack(self::STREAM, self::GROUP, [(string) $id]);
                    if ($acked === false) {
                        throw new RuntimeException("XACK failed for {$id}");
                    }
                    if ($acked === 0) {
                        $this->warn("{$id} was no longer pending for this group");
                    }
                }
            }
        }
    }

    /**
     * @param  array<string, string>  $fields
     */
    private function project(OrderSummaryProjector $projector, array $fields): void
    {
        try {
            $event = json_decode($fields['event'] ?? '', true, 32, JSON_THROW_ON_ERROR);
        } catch (JsonException $e) {
            // A real consumer parks the raw entry (see the DLQ chapter) before XACK.
            throw new RuntimeException('Undecodable entry; park it, do not ack blindly', previous: $e);
        }

        if (($event['source'] ?? null) !== '/services/orders'
            || ($event['type'] ?? null) !== 'com.example.orders.order.placed.v1') {
            throw new RuntimeException('Event from an unexpected source or of an unknown type');
        }

        $data = $event['data'];
        $projector->apply($data['orderId'], (int) $data['revision'], 'placed', $data['shipCountry'], $event['time']);
    }
}

The command iterates the streams it receives instead of indexing $batch['orders.events.v1']: "Laravel prefixes every key it stores in Redis using the prefix option", and the reply carries the stored key name. It acknowledges with the unprefixed name it passed (the client adds the prefix), treats false from XACK as an error, and leaves recovery of a dead incarnation's PEL to a separate XAUTOCLAIM sweep like the Go one.

In production systems ​

  • RabbitMQ documents that unroutable non-mandatory messages are dropped or sent to an alternate exchange and exposes unroutable dropped/returned rates as metrics; watch those when a new event type ships before its subscribers.
  • Kafka documents retention.ms as an SLA for consumers and auto.offset.reset defaulting to latest; the Kafka 4.4 consumer documentation also lists by_duration: resets and warns that latest can skip records produced on newly added partitions before discovery.
  • Redis documents KEEPREF as the default trimming behaviour and the PEL cleanup by XAUTOCLAIM; a stuck consumer group plus MAXLEN is silent data loss for that group.
  • Laravel documents that ShouldDispatchAfterCommit discards the event on rollback and dispatches immediately when no transaction is open, which is why a missing DB::transaction changes behaviour.

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

PlaceOrder commits the order and dispatches OrderPlaced after commit; listeners update a summary table and queue a confirmation mail. No broker exists, yet the same rules apply: listeners must be idempotent (queues retry), and "after commit" is not durable, so anything that must not be lost (an invoice request) is written to a table in the same transaction and processed from there.

Modular monolith: modules with their own tables ​

Orders, Billing and Shipping live in one deployment but own separate schemas. Modules talk through published module events (integration events in-process): Billing's listener translates orders.OrderPlaced into its own command CreateInvoice. Keep the module event contract explicit even without a broker; that boundary is what later becomes a topic. Avoid one module reading another's tables "because it is faster": it is a hidden shared-database coupling.

Microservices: facts on a broker ​

Orders writes an outbox row order.placed.v1; the relay publishes it to Kafka keyed by order id. Shipping projects it into order_summaries; Payments captures and emits payment.captured.v1 with causationid set to the order event's id; Mail keeps a customer projection from customer.changed.v1 and needs no call to Customers. Cancellation with refunds is an orchestrated saga, not a cascade. Each consumer owns its group or queue, DLQ and lag alert.

Distributed data: replicas, caches and regions ​

A projection is one more replica, with lag. A user who writes in region A and reads a projection in region B can miss their own write; pass minRevision or pin the user's reads to the write region briefly. Caches fed by events need the same revision guard, or a late event will overwrite a newer cached value. Multi-region Kafka (MirrorMaker 2, cluster linking) translates offsets; rebuild projections from revision-guarded data rather than trusting translated offsets blindly. For database-level consistency menus see Eventual Consistency in Databases.

Scaling path ​

LoadDesignExample
1×Domain events + after-commit listeners in one app100 orders/day, one database
10×Outbox + one broker; a few subscribers with projections and lag alertsShipping and Mail as separate services
100×Partitioned topics keyed by aggregate, schema registry + AsyncAPI, rebuild groups, per-consumer DLQs, retention sized from recovery SLAs20 subscribing teams; replays run beside live traffic

At 100× the expensive part is not throughput but ownership: an inventory of subscribers, contract compatibility checks in CI, and a runbook for rebuilding any projection.

Lab ​

Everything that needs a broker or a Laravel app below is "expected, not run". Use a disposable environment you already have; this chapter starts no Docker or Compose. The Go tests run without a broker.

1. Projection idempotency and reordering (runs locally) ​

bash
cd docs/snippets/messaging/event-driven-architecture/go
go test ./after/... -run 'Duplicate|OlderRevision|Rebuild|Ingress' -v
# expected: PASS for TestDuplicateDeliveryIsStale, TestOlderRevisionCannotOverwriteNewer,
#           TestRebuildMatchesLive, TestIngressRejections (5 subtests)

Read TestOlderRevisionCannotOverwriteNewer: the placed event is redelivered after the cancellation and changes nothing.

2. RabbitMQ: publish before any subscriber exists ​

bash
# expected, not run. Terminal 1:
AMQP_URL=amqp://guest:guest@localhost:5672/ go run ./after/rabbitmq publish
# expected: error "broker returned message: no queue bound for routing key: order.placed.v1 (312 NO_ROUTE)"
# Terminal 2: create the subscriber (queue + binding), then repeat terminal 1:
AMQP_URL=amqp://guest:guest@localhost:5672/ go run ./after/rabbitmq subscribe
# expected: publish returns nil; rabbitmqctl list_queues shows shipping.order-events consumed

3. Kafka: a new group bootstraps from retention ​

bash
# expected, not run.
KAFKA_BROKERS=localhost:9092 go run ./after/kafka publish
GROUP=shipping-projection-v2 KAFKA_BROKERS=localhost:9092 go run ./after/kafka
kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group shipping-projection-v2
# expected: LAG falls to 0; records older than retention.ms are not replayed.

4. Redis Streams: MAXLEN trims unprocessed entries ​

bash
# expected, not run.
redis-cli XGROUP CREATE demo g 0 MKSTREAM
redis-cli XADD demo MAXLEN 3 '*' n 1 ; redis-cli XADD demo MAXLEN 3 '*' n 2
redis-cli XREADGROUP GROUP g c1 COUNT 2 STREAMS demo '>'
redis-cli XADD demo MAXLEN 3 '*' n 3 ; redis-cli XADD demo MAXLEN 3 '*' n 4 ; redis-cli XADD demo MAXLEN 3 '*' n 5
redis-cli XPENDING demo g          # expected: 2 pending (KEEPREF keeps PEL references)
redis-cli XAUTOCLAIM demo g c2 0 0-0
# expected: entries 1 and 2 are gone from the stream; XAUTOCLAIM returns them as deleted IDs
# and removes them from the PEL: the group lost two events it never acknowledged.

5. Laravel: after-commit is not durable ​

bash
# expected, not run, in a scratch Laravel 13 app with the snippets installed.
php artisan event:list | grep OrderPlaced     # expected: App\Listeners\RecordOrderSummary
php artisan tinker --execute="DB::transaction(function () { event(new App\Events\OrderPlaced(1,1,7,4200,'EUR','req-1')); throw new RuntimeException('rollback'); });"
# expected: RuntimeException; no listener job queued (event discarded on rollback).
# Now kill the PHP process right after COMMIT in PlaceOrder (e.g. a breakpoint) and observe:
# the order and its outbox_messages row exist, the listener job does not.

Common misconceptions ​

BeliefReality
Events are asynchronous commandsIntent differs: commands have an owner and may be refused; events record facts
Event-driven means event-sourcedEvent sourcing is a persistence choice inside one service
Thin events remove couplingCallbacks keep run-time coupling to the source
The event should carry everythingCarry what known projections need; each field is a contract
A consumer must accept every messageIt must accept the fact, but may reject malformed, unauthorised or unknown messages
A new consumer group gets all historyIt gets retained history, from its reset policy (Kafka default latest)
A RabbitMQ publisher ack means subscribers got itUnroutable messages are acked too; use mandatory and returns
ShouldDispatchAfterCommit makes publishing reliableIt orders dispatch after commit; a crash still loses it
Queue retries make consumers idempotentRetries cause duplicates; idempotency is the consumer's code
MAXLEN only removes processed entriesDefault KEEPREF trims regardless of groups
Choreography is always more decoupled than orchestrationThe flow's coupling moves into subscriptions and timing
Correlation id and causation id are the sameOne follows the flow; the other names the direct parent message
Eventual consistency is invisible to usersUsers see stale lists and double submissions unless UX handles it

Cheat sheet ​

TopicRemember
IntentCommand = do this (one owner); event = this happened (anyone); query = tell me
FowlerNotification, state transfer, event sourcing, CQRS: four different things
NotificationCarry id and revision; beware callback load and outages
State transferCarry what projections need; own bootstrap, lag, rebuild
Domain vs integrationTranslate explicitly; integration events are versioned contracts
PublicationOutbox in the same transaction; after-commit is ordering only
IngressValidate size, envelope, source, version; park invalid; never "refuse" a fact
ProjectionGuarded upsert on revision; source_time for lag
UXReturn accepted state, show pending, read-your-writes by revision
EnvelopeCloudEvents id+source for dedup; correlationid, causationid
RabbitMQProducer owns exchange; subscriber owns queue, binding, DLX; confirms + mandatory
KafkaProducer owns topic; subscriber owns group/offsets; earliest + retention SLA; recreate client on failure
Redis StreamsProducer owns stream; subscriber owns group/PEL; size MAXLEN from recovery SLA; XAUTOCLAIM sweep
ChoreographyFine for independent reactions; orchestrate flows with compensation

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A message is named InvoiceShouldBeCreated and Orders waits for InvoiceCreated. What is wrong? Must-know ​

Answer

Answer: It is a passive-aggressive command: the sender expects one receiver to act. Send a CreateInvoice command to Billing (with a reply event) and keep real facts as events.

2 — Why can a thin OrderChanged {id} lead to a consumer acting on the wrong data? Must-know ​

Answer

Answer: The callback returns the current state, which may be a newer revision than the event announced, or fail if the source is down. Carry the revision and handle "newer than announced" explicitly.

3 — Mail needs the customer's e-mail but OrderPlaced only has customerId. Should you add the e-mail to the order event? Must-know ​

Answer

Answer: Usually not: the e-mail belongs to the customer context. Mail keeps a customer projection from the customer service's events, or calls it. Event-carried state transfer carries what the order owner owns and the projection needs.

4 — What does ShouldDispatchAfterCommit guarantee and what does it not? Must-know ​

Answer

Answer: The event is dispatched only after the transaction commits and is discarded on rollback. It does not survive a crash between commit and dispatch; durable publication needs an outbox row in the same transaction.

5 — A new Kafka consumer group shows no historical orders. Name two possible causes. Important ​

Answer

Answer: auto.offset.reset is latest (the default), or the history is older than the topic's retention (or compacted away). Use earliest for projections and a snapshot for older history.

6 — Why must the Kafka projection stop and recreate its client after a failed batch? Important ​

Answer

Answer: The client's fetch position has advanced past the failed records. Continuing and committing a later batch would commit past them. A new client resumes from the last committed offsets.

7 — RabbitMQ acked a publish. Did any subscriber receive it? Must-know ​

Answer

Answer: Not necessarily. Unroutable messages are confirmed too. With mandatory=true the broker sends basic.return (312 NO_ROUTE) before the ack; the publisher must handle it.

8 — How can a Redis Streams group lose events it never acknowledged? Important ​

Answer

Answer: XADD ... MAXLEN (default KEEPREF) trims old entries regardless of group references. XAUTOCLAIM then drops the missing entries from the PEL. Size trimming from the recovery SLA or use ACKED on Redis 8.2+.

9 — Shipping receives a valid OrderPlaced for an embargoed country. Should it reject the event? Must-know ​

Answer

Answer: No. The order was placed; that fact stands. Shipping records it and emits its own fact (ShipmentBlocked) or a command to the owner, which decides on cancellation or refund.

10 — What is the difference between correlationid and causationid? Important ​

Answer

Answer: Correlation id is shared by every message in one business flow; causation id is the id of the specific message that directly caused this one. Together they rebuild the cascade.

11 — A user places an order and the "My orders" list is empty. Give two fixes. Must-know ​

Answer

Answer: Show the accepted order from the POST response (optimistic or pending state), and read with minRevision so the server waits briefly for the projection or reads the write model for that user.

Glossary ​

TermMeaning
CommandMessage asking one owner to perform an action; may be refused
EventMessage recording a fact that already happened, owned by its producer
QueryRequest for data without side effects
Command Message / Event Message / Document MessageEIP names for messages carrying an invocation, a notification, or data
Publish-subscribe / fan-outDelivering a copy of each event to every subscriber
Event notificationFowler: thin event; receivers call back for details
Event-carried state transferFowler: event carries state so receivers keep a local copy
Event sourcingStoring state as an append-only sequence of events
CQRSSeparate models for writing and reading
Event collaboration / event cascadeServices cooperating via events; chains A to B to C nobody sees whole
Domain eventIn-process fact inside one bounded context
Integration eventVersioned, published fact crossing a service boundary
ChoreographyServices react to each other's events with no coordinator
OrchestrationA coordinator sends commands and tracks flow state
Temporal couplingOne component must be available or run before another for correctness
Passive-aggressive commandAn event used where the sender really expects a specific action
Ingress validationChecking a message's envelope, source and schema before any effect
Projection / read model / local copyConsumer-owned state derived from events
BootstrapInitial fill of a projection from history or a snapshot
Replay / rebuildRe-applying retained events into a fresh projection
Consumer lagHow far a consumer is behind the source (offsets or time)
RevisionAggregate version number used to discard stale or duplicate events
Idempotent consumerConsumer whose repeated processing has no extra effect
OutboxTable written in the same transaction; a relay publishes its rows
Eventual consistencyCopies converge after updates stop; reads may be stale meanwhile
Read-your-writesA user always sees their own completed writes
Optimistic UIShowing the expected result before confirmation
Event envelopeMetadata wrapper around the payload
CloudEventsCNCF specification for event envelopes (id, source, type, specversion, ...)
AsyncAPISpecification for describing message-driven APIs
Correlation idIdentifier shared by all messages of one flow
Causation idIdentifier of the message that directly caused this one
Exchange / bindingRabbitMQ router owned by the producer / subscriber's routing rule to its queue
Publisher confirm / mandatory / basic.returnRabbitMQ acceptance signal / flag requesting return of unroutable messages / the return
Delivery limitRabbitMQ quorum queue cap on redeliveries before dead-lettering
Consumer groupKafka or Redis set of consumers sharing a subscription's progress
OffsetKafka position in a partition; committed per group
auto.offset.resetKafka start position for a group without a valid committed offset
Retention / compactionKafka deletion by age/size / keeping the latest value per key
XADD / XREADGROUP / XACKRedis append / group read / acknowledge
MAXLEN / MINID / KEEPREF / ACKEDRedis trimming by count / by ID / default ignore groups / only acknowledged
PELRedis pending entries list: delivered but unacknowledged entries per group
XAUTOCLAIMRedis cursor-based transfer of idle pending entries
ShouldDispatchAfterCommitLaravel event interface delaying dispatch until COMMIT
ListenerLaravel class handling an event, discovered from app/Listeners
EventStormingWorkshop that maps domain events on a timeline to find boundaries

References ​

Built by Morteza Negahi