Control Flow & Event Handling in Design
"Event handling is concerned with how to organize control flow as well as how to handle reactive and temporal events through various mechanisms including synchronization, implicit invocation and callbacks." — SWEBOK v4.0, Software Design KA, section 3.2 "Control and Event Handling", IEEE Computer Society, 2024
Summary: Every program answers one question: who decides what runs next? In call-return code you do; in event-driven code something else does, and your handler runs when it is told to. This chapter shows how to choose between the control styles, how to design events, and what breaks when events cross a transaction, a thread or a network. Focus: Control flow styles (call-return, event-driven, reactive/dataflow, state machine, interrupt-driven), inversion of control, event loop vs thread-per-request vs goroutine-per-connection, observer/pub-sub/event bus/event queue, Fowler's four meanings of "event-driven", sync vs async handling and its consistency price, event naming/payload/versioning, ordering, idempotency, reentrancy, cancellation and timeouts, callbacks vs promises vs coroutines vs channels, domain vs integration events, after-commit dispatch, error handling, testing and correlation IDs, in Go and Laravel. Learning goal: Look at a feature, decide which control style fits, design the events as facts with a stable payload, put each handler on the right side of the transaction and the sync/async line, and prove it with a test and a correlation ID in the logs.
This page is the complete reference for the "Control and Event Handling" topic of the SWEBOK design KA. It owns control flow and event design inside one application and at its edges. It does not re-teach what its siblings own: threads, locks and data races live in Designing for Concurrency; the Observer and State patterns in Behavioral Patterns; error and exception policy in Error & Exception Handling and Fault Tolerance; repositories and transactions in Data Persistence in Design; remote-call latency in Distribution of Components; MVC and view updates in Interaction & Presentation. Broker mechanics (outbox, dead-letter queues, ordering, schema evolution) are one sentence and one link each into the messaging section.
Page map
| If you are looking for | Go to |
|---|---|
| The five control styles and the four meanings of "event-driven" in a few tables | Everything in one minute |
| Why control flow is a design decision at all | Why it matters |
| SWEBOK, the Hollywood principle, Observer, Fowler 2005 and 2017 | Where it comes from |
| Call-return, event-driven, reactive, state machine, interrupt | Control styles, event-driven, reactive, state machine, interrupts |
| Frameworks, "don't call us, we'll call you" | Inversion of control |
| Event loop, thread per request, goroutine per connection, epoll/kqueue | Execution models |
| Observer, publish/subscribe, event bus, event queue | Event handling patterns |
| Event notification vs event-carried state transfer vs event sourcing vs CQRS | Four meanings |
| Sync vs async handlers and what each does to consistency | Sync vs async |
| Naming, payload, versioning | Event design |
| Ordering, duplicates, idempotent handlers | Ordering and idempotency |
| A handler that publishes events | Reentrancy |
| Timeouts, cancellation, shutdown | Cancellation and timeouts |
| Callbacks, promises, coroutines, channels | Async styles |
| Browser and mobile events | UI events |
| Domain events vs integration events; commit boundary | Domain vs integration, Transactional boundary |
| Handler failures, testing, correlation IDs | Errors in handlers, Testing, Observability |
| Code | Go, Laravel |
| Monolith to distributed | In architecture |
| Hands-on | Lab |
| Wrong beliefs, cheat sheet, self-check, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The five control styles. Every row is unpacked in the concepts section.
| Style | Who decides what runs next | Tiny example | What goes wrong when misused |
|---|---|---|---|
| Call-return | The caller | total := price(order) | Caller waits for slow work it does not need |
| Event-driven | An event plus a registered handler | OrderPlaced runs SendEmail | Invisible flow; nobody knows what reacts |
| Reactive / dataflow | A changed value propagates to dependents | Spreadsheet cell, Vue ref | Update storms, hard-to-trace glitches |
| State machine | Current state plus incoming event | placed + payment.captured gives paid | Illegal transitions scattered in if chains |
| Interrupt-driven | The environment, preempting current work | SIGTERM, a timer, a socket becoming readable | Handler does too much and is itself interrupted |
The vocabulary.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Inversion of control (IoC) | The framework calls your code, not the other way round | http.HandleFunc, a Laravel listener | You cannot reuse or test the skeleton |
| Hollywood principle | "Don't call us, we'll call you" | Registering a callback | Same as above, as a slogan |
| Event | A fact that already happened | OrderPlaced | Commands disguised as events |
| Command | A request to do something | ShipOrder | Event used as a "passive-aggressive command" |
| Domain event | An event inside one bounded context | In-process OrderPlaced | Used as a cross-service contract by accident |
| Integration event | An event that crosses a service boundary | order.placed on a broker | Internal fields leak and freeze |
| Idempotent handler | Safe to run twice | Dedupe on event_id | Double emails, double charges |
| Reentrancy | A handler that triggers its own event again | Listener updates the model it listens to | Infinite loop, stack overflow |
| Cancellation | A signal that work should stop | context.Context, SIGTERM | Zombie work after the caller left |
| Correlation ID | One id carried through every hop | X-Correlation-Id header | Cannot reconstruct what one request caused |
Sync or async, and what it costs.
| Handling | Runs where | Caller waits? | Failure reaches caller? | Consistency with the caller's data |
|---|---|---|---|---|
| Synchronous (in-process call) | Caller's goroutine/process, often caller's transaction | Yes | Yes | Immediate, can share a transaction |
| Asynchronous in-process (goroutine) | Another goroutine, same process | No | No (hook/log) | Eventual; lost if the process dies |
| Asynchronous queued (Laravel queue worker) | Another process | No | No (retry, failed jobs) | Eventual; survives a restart |
| Asynchronous across services (broker) | Another service | No | No (DLQ) | Eventual; needs idempotency |
Where each idea lives in your tools.
| Level | Go | Laravel |
|---|---|---|
| Control entry | main, net/http server loop | HTTP kernel, artisan, queue worker |
| Handler registration | mux.HandleFunc, Subscribe on your bus | Event discovery (handle/__invoke), Event::listen, #[ObservedBy] |
| In-process event | Typed struct on a channel or bus | Event::dispatch(), ShouldDispatchAfterCommit |
| Async handler | goroutine with its own context | Listener with ShouldQueue, #[Tries], #[Backoff] |
| Cancellation | context.Context, signal.NotifyContext | Queue timeout, retry_after, job failed() |
| Correlation | context.WithValue | Context::add() (survives the queue) |
| Test double | Fake bus, httptest | Event::fake(), Queue::fake() |
Why control flow and events matter
Control flow is the decision that is hardest to see in code and hardest to change later. A function call is visible: you read the caller and you know the callee. A handler registered at startup is invisible: you can read OrderService for an hour and never learn that placing an order also sends an email, reserves points and warms a cache. The gain is decoupling (the order code does not know about email); the price is that the flow is no longer in any one place. Design is choosing, on purpose, where each reaction sits on that line.
| Direct calls (call-return) | Events (inversion of control) |
|---|---|
| Flow is readable in one place | Flow is spread over registrations |
| Caller knows every consequence | Publisher does not know its listeners |
| Adding a consequence edits the caller (violates OCP) | Adding a listener edits nothing existing |
| Failure of a callee is the caller's failure | Failure of a listener is somebody else's problem |
| Easy to step through in a debugger | Needs logs, traces and a correlation ID |
| Latency of every step adds up | Slow work moves off the critical path |
| Everything shares one transaction | Each reaction needs its own consistency story |
The analogy we reuse on this page: a newspaper subscription. A phone call is call-return: you dial one person and wait for the answer. A newspaper is event-driven: the publisher prints once, does not know who reads it, and each subscriber does their own thing with the paper. Add a subscriber and the printing press does not change. But if you want to know whether the mayor actually read the story, you cannot ask the press; you have to look at the mayor. That is the trade: free to extend, hard to follow.
Three common misunderstandings, up front
- "Event-driven means asynchronous." It does not. Fowler: "There's no need for event processing to be asynchronous." Laravel's default listener, Go's
http.HandlerFuncand a UI click handler are all synchronous. - "Event-driven means microservices and Kafka." An event is a design idea you can have inside one process. Laravel's own docs call events "a simple observer pattern implementation".
- "Events decouple everything." They decouple the publisher's code from the listener's code. They do not decouple the data, the order of effects or the transaction: those couplings only become invisible.
Where it comes from
SWEBOK. The Software Design KA of SWEBOK v4.0 lists "Control and Event Handling" among the key issues in design (section 3.2, next to concurrency, persistence, distribution, error handling and security) and defines it in the sentence quoted at the top of this page. Section 5.7 of the same KA names the design method:
"Event-driven design is an approach where a system or component invokes its operations in reaction to events (indirect invocation)" — SWEBOK v4.0, Software Design KA, section 5.7 "Event-Driven Design"
and adds that publish/subscribe "keeps the producers and consumers decoupled using a message broker with channels called topics", in contrast to point-to-point messaging where senders and receivers know each other. It also names three kinds of event processing: simple event processing, event stream processing and complex event processing.
Inversion of control and the Hollywood principle. Martin Fowler's 2005 bliki entry starts from a command-line program (my code asks, my code reads) and a windowing program (my code registers a callback, then hands control to Tk.mainloop):
"The control is inverted - it calls me rather me calling the framework. This phenomenon is Inversion of Control (also known as the Hollywood Principle - “Don't call us, we'll call you”)." — Martin Fowler, Inversion Of Control, 26 June 2005
He quotes Ralph Johnson and Brian Foote on why it defines a framework:
"This inversion of control gives frameworks the power to serve as extensible skeletons." — Ralph Johnson and Brian Foote, as quoted by Martin Fowler in Inversion Of Control
Observer, 1994. The Gang of Four's Observer is the object-level form. We read refactoring.guru's catalogue entry:
"Observer is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing." — refactoring.guru, Observer
Fowler, 2005. His draft patterns Domain Event and Event Sourcing (both marked by him as unfinished) define the vocabulary: Event Sourcing is "Capture all changes to an application state as a sequence of events." Domain Event is a record of "something interesting which affects the domain".
Fowler, 2017. After a Thoughtworks workshop he wrote that people mean different things by "event":
"when people talk about “events”, they actually mean some quite different things." — Martin Fowler, What do you mean by “Event-Driven”?, 7 February 2017
and split it into four patterns: event notification, event-carried state transfer, event sourcing and CQRS (below).
Messaging vocabulary. Hohpe and Woolf's Enterprise Integration Patterns put it in one sentence: "Messaging does not change the event notification, just makes sure that the notification gets to the observer." Their Idempotent Receiver is "one that can safely receive the same message multiple times". The Reactive Manifesto (2014) names the style "Reactive Systems": "we want systems that are Responsive, Resilient, Elastic and Message Driven."
The kernel underneath. Linux's epoll(7) page says the API "can be used either as an edge-triggered or a level-triggered interface and scales well to large numbers of watched file descriptors"; BSD and macOS offer kqueue/kevent for the same job. Node.js's event loop guide says the loop "is what allows Node.js to perform non-blocking I/O operations — despite the fact that a single JavaScript thread is used by default — by offloading operations to the system kernel whenever possible." Go's runtime has a network poller built on the same primitives (netpoll in runtime/netpoll_epoll.go on Linux), which is why a goroutine that blocks on a socket costs little. Go's net/http documents that Serve accepts connections, "creating a new service goroutine for each".
The concepts, one by one
Each block follows the same order: plain words, the usual wrong belief, a definition, a timeline, real scenarios, what a tool provides, and the fix.
Call-return Must-know
In plain words: you call a function, it does its work, it hands you the answer, and you carry on. The caller decides everything.
Common misunderstanding: "Call-return is old-fashioned; modern systems should be event-driven." Most code in every event-driven system is call-return. An event handler is itself a function that calls other functions. Events are for the places where the caller should not know the callee.
Definition: control passes down the call stack and back; the call stack is the record of who is waiting for whom.
Caller (HTTP handler) Callee (PlaceOrder) Callee (Stock.Reserve)
1 handle(request) ------------>
2 reserve(sku, qty) -------------->
3 UPDATE stock ...
4 <------------------------------- ok
5 <------------ order, nil
-- the caller is blocked in steps 2-4; any error returns on the same pathReal scenario: price calculation, stock reservation that must succeed before the order exists, validation, anything where the caller needs the answer to continue.
What provides it: every language. Go: result, err := f(ctx, x). Laravel: $order = $placeOrder($customerId, $lines).
Fix when it hurts: if a call is slow and its result is not needed, move it behind an event or a queue; if it is needed, keep the call and add a timeout (cancellation).
Event-driven Must-know
In plain words: something happened; whoever cares is told. The thing that happened does not know who cares.
Common misunderstanding: "If I publish an event, the other part is decoupled." Only the code is. The data shape you put in the event is now a contract; the order in which listeners run may now matter; the transaction no longer covers them.
Definition: SWEBOK 5.7: the system "invokes its operations in reaction to events (indirect invocation)". A publisher announces a fact; zero or more subscribers react; the publisher does not wait for or depend on any particular reaction.
Publisher (PlaceOrder) Dispatcher Listener A Listener B
1 OrderPlaced{id=7} ------------>
2 find listeners for "OrderPlaced"
3 call -------------------> send email
4 call ------------------------------------------> add loyalty points
5 <----------- returns (sync) -- in a queued setup, steps 3-4 happen later, elsewhereReal scenario: send a confirmation email, update a search index, bump a counter, invalidate a cache, notify the warehouse, push a status to the browser.
What provides it:
| Product | Mechanism |
|---|---|
| Go stdlib | Channels, select, callbacks you pass to http.HandleFunc; no built-in event bus |
| Laravel 13 | Event::dispatch(), listeners found by event discovery, ShouldQueue, observers, broadcasting |
| Node.js | EventEmitter, the event loop |
| Spring | ApplicationEventPublisher, @EventListener, @TransactionalEventListener |
| Django | Signals; transaction.on_commit for after-commit work |
| Kafka, RabbitMQ, Redis Streams, NATS, SQS | Brokers for events between processes (EDA) |
Fix when it hurts: write down the listeners of every important event in the event's doc comment or an ADR, and log "event X delivered to listener Y" with the correlation ID.
Reactive and dataflow Good to know
In plain words: you declare that B is computed from A; when A changes, B updates itself. A spreadsheet works this way.
Common misunderstanding: "Reactive means non-blocking I/O." The Reactive Manifesto's "Reactive Systems" is about responsiveness, resilience, elasticity and message passing. "Reactive programming" (Rx, signals, Vue ref, Livewire properties) is about propagating changes through a dependency graph. The two share a word, not a mechanism.
Definition: a graph of values and the functions that derive them; the runtime re-evaluates dependents when a source changes.
source derived effect
1 price = 10 --> total = price * qty --> render(total)
2 qty = 3 --> total = 30 --> render(30)
3 price = 12 --> total = 36 --> render(36) -- nobody called "recompute"Real scenario: form totals and validation in a front-end, live dashboards, stream processing, build systems (a changed file rebuilds dependents).
What provides it: Vue/Svelte/Solid signals, RxJS, Livewire and Alpine in the Laravel world; Go has no built-in dataflow type, you build it with channels and goroutines (pipelines); backend streams belong to stream processing.
Fix when it hurts: glitches and update storms come from long chains and cycles: batch updates, keep the graph acyclic and shallow.
State machine Important
In plain words: a thing is always in exactly one state, and an event moves it to another state only along allowed arrows.
Common misunderstanding: "A status column plus a few if checks is a state machine." Until the legal transitions are written in one place and enforced, it is a status column; illegal moves happen from whichever code path forgot the check.
Definition: a set of states, a set of events, and a transition function (state, event) -> state, optionally with guards and actions. Draw it as a UML state diagram (UML in Practice); implement it as a table; use the State pattern (Behavioral Patterns) when behaviour differs per state.
state event result
1 placed payment.captured paid
2 paid shipment.sent shipped
3 shipped cancel.requested ERROR: illegal transition (see go/statemachine)
4 placed cancel.requested cancelledReal scenario: order lifecycle, subscription billing states, document approval, connection handshakes, UI wizards.
What provides it: Go: a map[State]map[Event]State plus a method; Laravel: a backed enum for the status and a transition method on the model or an action, Order::transitionTo() which throws on illegal moves; packages exist but the table is the design.
Fix when it hurts: one table, one function that every writer goes through, tests that list every legal and every illegal pair.
Interrupt-driven and signals Important
In plain words: the environment taps you on the shoulder: a timer fired, a socket has data, the operator pressed Ctrl-C.
Common misunderstanding: "Interrupts are a hardware topic." Your server meets them as SIGTERM during a deploy, as a socket readiness event, as a deadline. They are the origin of every event your code handles; the Linux kernel's generic IRQ layer exists to give drivers one abstraction over many interrupt controllers.
Definition: an asynchronous notification from outside the current flow of control that preempts or wakes it. In user space, signals and I/O readiness (epoll, kqueue) are the equivalents.
Main goroutine Signal machinery
1 running server ...
2 SIGTERM arrives
3 NotifyContext cancels ctx
4 <-ctx.Done() unblocks
5 srv.Shutdown(grace) -> drain in-flight requests
6 exit 0Real scenario: rolling deploys in Kubernetes (SIGTERM, then SIGKILL after the grace period), Ctrl-C in a CLI, SIGHUP to reload config, PHP workers told to restart by queue:restart (a flag the worker checks between jobs, not a signal).
What provides it: Go: signal.NotifyContext(parent, signals...) returns a context cancelled on the first signal; Laravel queue workers handle SIGTERM by finishing the current job (see Queues).
Fix when it hurts: keep signal handlers tiny: turn the signal into a value (a cancelled context, a flag) and let normal code react (go/server).
Inversion of control and frameworks Must-know
In plain words: with a library you call it; with a framework it calls you. You hand over main and fill in the blanks.
Common misunderstanding: "IoC is dependency injection." Dependency injection is one technique for IoC (the container builds and wires your objects, see DIP). Inversion of control is the broader reversal of who calls whom: event handlers, template methods, plugins and frameworks are all IoC without a container.
Definition: Fowler: "In order to use it you need to insert your behavior into various places in the framework either by subclassing or by plugging in your own classes. The framework's code then calls your code at these points." A library returns control after each call; a framework keeps it.
Library (you in control) Framework (framework in control)
1 your main() your main(): register handlers
2 x = lib.parse(input) server.ListenAndServe() <- never returns
3 y = lib.format(x) framework loop: accept, route, call YOUR handler
4 your code continues your handler returns; framework continuesReal scenario: http.HandleFunc, Laravel controllers, listeners, middleware and service providers, Eloquent model hooks, test frameworks calling your test_* methods.
What provides it: all frameworks. In Go it is lighter: a Handler interface and a server loop; in Laravel it is heavy: the container, the kernel and the event dispatcher.
Fix when it hurts: a framework's control is a cost: your code is hard to run outside it. Keep business rules in plain functions or classes that the handlers call (the hexagonal shape), so the framework is a thin shell.
Execution models: event loop, thread per request, goroutine per connection Must-know
In plain words: three ways to serve many users at once. Give each one a worker that waits (thread or process per request); give everyone one shared worker that never waits (event loop); or give each one a very cheap worker that the runtime parks while waiting (goroutines).
Common misunderstanding: "Event loop means fast, threads mean slow." An event loop wins when most time is spent waiting on I/O and handlers are short. It loses when a handler computes for a long time: one slow callback delays every other connection. Thread- or process-per-request gives true isolation per request at a memory cost.
Definition:
| Model | How a request is served | Blocking code? | Many connections | Typical products |
|---|---|---|---|---|
| Process/thread per request | One OS process or thread owns the request until done | Natural: it just waits | Limited by workers you can afford | PHP-FPM (a pool of worker processes), Apache prefork, classic Java servlet containers |
| Event loop | One thread waits in epoll/kqueue, runs the ready callback to completion, repeats | Forbidden: a blocking call stalls the loop | Thousands per thread | Node.js (libuv), Python asyncio, Nginx workers, Redis (command loop) |
| Goroutine per connection | net/http starts a goroutine per accepted connection; the runtime parks it on the network poller while it waits | Natural: the goroutine parks, the OS thread is reused | Tens of thousands, spread over GOMAXPROCS threads | Go net/http |
| Long-running PHP workers | The app boots once and serves many requests from memory | Natural, one request per worker at a time | Worker count | Laravel Octane (Swoole, RoadRunner, FrankenPHP) |
Event loop (one thread) Goroutine per connection
1 epoll_wait() -> conn 7 readable goroutine 7: conn.Read() blocks
2 run handler 7 to completion (no blocking!) runtime parks goroutine 7 on the poller,
3 epoll_wait() -> conn 3 readable runs goroutine 3 on the same OS thread
4 run handler 3 to completion data arrives: poller wakes goroutine 7Real scenario: a Node.js API that suddenly serves requests slowly because one handler does synchronous JSON parsing of 50 MB; a PHP-FPM site that returns 502 when all workers wait on a slow third-party API; a Go service that happily holds 50,000 idle websockets.
What each exposes:
| Product | Key knobs | Failure sign |
|---|---|---|
| PHP-FPM | pm.max_children, request_terminate_timeout | All workers busy, requests queue, 502/504 |
| Node.js | One loop; worker_threads or cluster for CPU | Event-loop lag, p99 latency jumps for everyone |
Go net/http | ReadHeaderTimeout, IdleTimeout, Server.Shutdown, GOMAXPROCS | Goroutine growth, memory growth |
| Laravel Octane | --workers, --max-requests | State leaking between requests |
Fix: pick the model your workload suits and do not fight it: blocking I/O in an event loop is the classic mistake; unbounded goroutines per event is its Go cousin (backpressure). Concurrency details: Designing for Concurrency.
Event handling patterns: observer, publish/subscribe, event bus, event queue Must-know
In plain words: four ways to wire "when this happens, tell those": the object keeps a list of listeners (Observer); a middleman holds the list by topic (publish/subscribe); one shared middleman for the whole app (event bus); events wait in line and a worker takes them one at a time (event queue).
Common misunderstanding: "Observer, pub/sub and event bus are three names for one thing." They differ in who knows whom. In Observer the subject holds its observers. In publish/subscribe a channel or broker sits between and neither side knows the other. An event bus is a pub/sub channel inside one process. An event queue adds storage and ordering: events are not delivered "now" but "when the consumer takes them".
Definition:
| Pattern | Who holds the subscriber list | Publisher knows subscribers? | Delivery | Typical scope |
|---|---|---|---|---|
| Observer | The subject itself | Yes (an interface) | Synchronous call | One object graph |
| Publish/subscribe | A broker or channel | No | Sync or async, by topic | Process or network |
| Event bus | A shared in-process dispatcher | No | Usually sync, optionally async | One process |
| Event queue | A queue; consumers pull | No | Async, ordered per queue | Process or network, durable if backed by a store |
| Event stream (Kafka-style log) | A log with consumer offsets | No | Async, replayable | Network |
Observer Event bus / pub-sub Event queue
1 subject.attach(o1, o2) bus.subscribe("order.placed", h) queue.push(event)
2 subject.state changes publisher.publish(event) worker: event = queue.pop()
3 subject -> o1.update() bus -> h(event) worker: handle(event); ack
4 subject -> o2.update() (publisher never named h) (a crash before ack: redelivery)Real scenario: Eloquent model events and observers (Observer); Laravel Event::dispatch with queued listeners (bus plus queue); a Go service where a bus.Publish triggers an audit log (event bus); RabbitMQ topic exchange to many services (pub/sub across the network).
What provides it:
| Product | Observer | Pub/sub / bus | Queue / stream |
|---|---|---|---|
| Go | Interface plus slice of observers | Your own bus (go/bus), channels | Buffered channel, database/sql job table |
| Laravel 13 | Eloquent observers (#[ObservedBy]) | Event dispatcher | Queued listeners (Redis, database, SQS, Beanstalkd) |
| Brokers | n/a | RabbitMQ exchanges, Redis Pub/Sub, NATS subjects | Kafka topics, SQS, Redis Streams, RabbitMQ queues |
Fix when it hurts: use Observer for tightly related objects, a bus inside a process, a broker between services. Do not add a broker to solve an in-process problem.
Fowler's four meanings of "event-driven" Must-know
In plain words: when a colleague says "we are event-driven", ask which of four things they mean.
Common misunderstanding: "Event sourcing, CQRS and event-driven are one architecture." Fowler's 2017 note says they are four patterns that people confuse, and he reports a project manager who said "event sourcing had been a disaster" when the pain was really in CQRS's two models and in asynchronous communication, "certainly a known complexity-booster, but not one that's a necessary part of either event-sourcing or CQRS".
Definition:
| Meaning | What the event carries | Source of truth | Receiver needs the sender later? | Main cost |
|---|---|---|---|---|
| Event notification | An id and a link back | The sender's database | Yes: asks the sender for details | Flow invisible; the "passive-aggressive command" trap |
| Event-carried state transfer | The changed data | The sender; receivers keep copies | No | Copies can be stale; more receiver logic |
| Event sourcing | Each state change | The event log | No (rebuilds from the log) | Event schema evolution; replay with side effects |
| CQRS | Not about events | Write model vs read model | n/a | Two models to keep in step |
Notification Event-carried state transfer Event sourcing
1 CustomerMoved{id=9} CustomerMoved{id=9, address=...} append Deposited{100}
2 receiver: GET /customers/9 receiver: UPDATE local copy append Withdrawn{30}
3 (call back for details) (no call back) state = fold(events) = 70Real scenario: notification: "order shipped" prompting the email service to fetch the order; state transfer: the catalogue service copying price changes so checkout never calls it; event sourcing: Fowler's own example, a version control system whose log of commits is the event store and whose working copy is the state; CQRS: a write model for orders and a denormalised read model for the dashboard, with or without events.
What provides it: pointers only; this page does not re-teach them. Event-driven architecture and Event Sourcing & CQRS own the depth; Data Persistence in Design owns the read/write model split.
Fix when it hurts: name the pattern you are using in the design doc, per event: "OrderPlaced is a notification; PriceChanged is state transfer." Do not adopt event sourcing to get decoupling, and do not adopt CQRS to get an audit trail.
Synchronous vs asynchronous handling and the consistency price Must-know
In plain words: a synchronous listener finishes before the publisher continues; an asynchronous one finishes sometime later. Later means the rest of the system can look at half-finished data.
Common misunderstanding: "Making a listener async only makes it faster." It also makes it eventually consistent: for a moment the order exists and the loyalty points do not. It also separates failure: the publisher no longer sees the error.
Definition: sync = same call stack (and possibly the same transaction); async = different goroutine, thread, process or machine, with its own failure mode and its own timing.
Customer API DB Queue worker
1 POST /orders --->
2 BEGIN; INSERT order; COMMIT ---->
3 dispatch OrderPlaced -> queue
4 <--- 201 Created
5 GET /orders/7 --> (order visible)
6 GET /points ----> (points NOT yet there) worker: add points <- eventual
7 GET /points ----> (points visible now)Real scenario: the customer sees the order but no email for a minute (fine); the customer sees the order but not the stock reservation (not fine: that must be sync and in the transaction); a dashboard that lags by seconds (fine).
What decides it:
| Question about the reaction | If yes | If no |
|---|---|---|
| Must it succeed for the use case to be valid? | Sync, inside the transaction | Async |
| Must the user see its result in the very next response? | Sync | Async |
| Is it slow or calls an external system? | Async | Either |
| Can it be retried safely? | Async with retries | Sync, or make it idempotent first |
| Does a failure need to roll back the main change? | Sync | Async with compensation |
Fix: keep the consistency-critical reactions inside the use case as plain calls (like Stock::reserve in the Laravel example); publish an event for the rest. Use the Laravel queue or a Go goroutine with its own timeout for async ones, and design the UI for the gap (a "processing" state).
Event design: naming, payload, versioning Must-know
In plain words: an event is a short note about something that already happened. Write it so a stranger can read it a year later.
Common misunderstanding: "Put the whole model in the event so listeners never need anything else." That is event-carried state transfer, and it freezes your model into a contract. Conversely, an event with only an id forces every listener to call back. Choose on purpose (four meanings).
Definition: a good event has (1) a past-tense name that states a business fact: OrderPlaced, not PlaceOrder (a command) and not OrderEvent; (2) a stable identity: event_id, so receivers can deduplicate; (3) occurred_at and, for ordering, a per-aggregate version or sequence number; (4) a small payload of ids and facts that will not change meaning; (5) a schema version of its own shape; (6) the correlation ID, usually in metadata and not in the business payload.
| Field | Why | Example |
|---|---|---|
| Name, past tense | A fact cannot be refused, a command can | order.placed |
event_id | Deduplicate, trace | UUID |
occurred_at | Order by time, audit | RFC 3339 UTC |
| Aggregate id + sequence | Detect gaps and stale events | order_id=7, seq=3 |
| Payload | Facts, ids, amounts as integers (cents) | {customer_id, total_cents} |
Schema version | Evolve without breaking consumers | 1 |
| Correlation/causation ids | Follow one request across hops | header or metadata |
Schema evolution Producer v2 Consumer v1 (not upgraded yet)
1 add optional field --> sends {version:2, coupon_code: "X"} ignores unknown field (compatible)
2 rename customer_id --> sends {customer: 9} breaks (incompatible)
3 safe rename: send BOTH for a release, migrate consumers, then drop the old oneReal scenario: an OrderPlaced event that carried the whole Order model and broke three listeners when a column was renamed; a UserUpdated event nobody could interpret because it did not say what changed.
What provides it: Laravel events are plain PHP classes: constructor-promoted readonly properties are the payload (SerializesModels re-fetches models when queued, which is state at handle time, not at publish time). Go: a struct with JSON tags. Across services: schema registry, Protobuf or JSON Schema and compatibility rules, owned by Message Design & Schema Evolution.
Fix when it hurts: treat an event class as a public API: additive changes only, deprecate before removal, version the payload.
Ordering and idempotent handlers Must-know
In plain words: events can arrive twice, late or in the wrong order. A good handler gives the same result either way.
Common misunderstanding: "My queue guarantees exactly-once, so I need no dedupe." Brokers and Laravel queues give at-least-once delivery in practice; a worker can crash after doing the work and before acknowledging it, and the job runs again. See Delivery Guarantees.
Definition: a handler is idempotent if applying the same event twice has the same effect as once. An aggregate's events are processed in order if a later version is never overwritten by an earlier one. Two tools: dedupe by event_id (a unique key in a processed_events table) and a version check (WHERE version < :new).
Arrival order Event Naive handler Idempotent handler (go/idempotent)
1 e1 v1 placed apply placed placed
2 e3 v3 shipped apply shipped shipped
3 e2 v2 paid apply paid (WRONG) ignored: stale, v3 already applied
4 e3 v3 shipped apply shipped ignored: duplicate event_idReal scenario: a payment confirmation processed twice credits the account twice; an out-of-order "address changed" event overwrites the newer address; a retry of a failed email handler sends two emails.
What prevents it:
| Mechanism | Prevents | Cost |
|---|---|---|
Unique key (listener, event_id) | Duplicates | One insert per delivery |
| Version check on the row | Stale overwrite | Needs a sequence per aggregate |
Natural idempotence (SET status='paid') | Duplicates for free | Only for assignments, not increments |
Partition by key (Kafka key, ShouldBeUnique in Laravel) | Reordering per key | Limits parallelism |
| Resequencer | Reordering | Buffers and delay (ordering) |
Fix: the Go and Laravel examples below; full pattern in Idempotent Consumers & the Inbox Pattern.
Reentrancy Important
In plain words: a handler runs, and while running, causes the same event (or another that leads back) to be published again.
Common misunderstanding: "A listener that updates a model cannot loop." If the listener saves the model and the model's saved event has this listener attached, it does loop. In a bus that holds its lock while calling handlers, a handler that publishes deadlocks.
Definition: reentrancy is a handler being invoked again before its first invocation finished, on the same call stack or via an event chain. Cycles in the event graph are reentrancy at design level.
Event Listener Effect
1 OrderUpdated SyncToSearch saves order.search_synced_at
2 OrderUpdated (again) SyncToSearch saves again ...
3 ... ... stack overflow or endless queueReal scenario: an Eloquent updated observer that calls $order->save(); a bus where handler A publishes B and B publishes A; a Go bus that holds a mutex during dispatch.
What provides protection:
| Technique | Where |
|---|---|
| Do not hold locks while calling handlers (copy the list first) | go/bus |
saveQuietly() or Model::withoutEvents() for writes that must not fire model events | Laravel Eloquent |
| Distinguish the cause: handler writes a different field or a different event type | Design |
| Depth guard in the dispatcher | Any |
| Draw the event graph; cycles are bugs | Design review |
Fix: break the cycle by design first; guards are the last line.
Cancellation and timeouts as control flow Must-know
In plain words: "stop, nobody needs this any more" is an event too, and every long operation must listen for it.
Common misunderstanding: "A timeout only makes the caller give up." If the callee does not look at the cancellation signal, it keeps working, holding a connection and a lock, for nobody. Cancellation has to travel down the chain.
Definition: In Go, context.Context "carries deadlines, cancellation signals, and other request-scoped values across API boundaries"; the docs add: "Incoming requests to a server should create a Context, and outgoing calls to servers should accept a Context." Cancelling a parent cancels every derived context. select waits on several channel operations at once, so a worker waits for "result or ctx.Done()".
Client Server handler DB / downstream call
1 request (timeout 2s) --> ctx (deadline 2s)
2 db.QueryContext(ctx) -----> running
3 -- 2s pass; client gives up --
4 ctx.Done() closes
5 <------ cancelled, query aborted, connection returned to the pool
6 handler returns, goroutine endsReal scenario: an HTTP request cancelled by the client while a 20 s report query runs; a deploy sending SIGTERM while jobs are in flight; an async listener that must not outlive the application.
What provides it:
| Need | Go | Laravel |
|---|---|---|
| Per-call deadline | context.WithTimeout, WithDeadline | Http::timeout(5), DB statement timeouts, job timeout |
| Cancel on client gone | r.Context() | Not automatic in PHP-FPM (the request ends; ignore_user_abort rules apply) |
| Cancel on signal | signal.NotifyContext | Worker finishes the job, then exits on SIGTERM |
| Keep values, drop cancellation | context.WithoutCancel | Not needed: queued jobs are separate processes |
| Callback when cancelled | context.AfterFunc | failed() after the last attempt |
| Graceful stop | http.Server.Shutdown(ctx) | queue:restart, Horizon terminate |
| Why it was cancelled | context.Cause, WithCancelCause | Exception message |
Fix: pass ctx as the first parameter everywhere; defer cancel() right after every WithTimeout/WithCancel (go vet checks it); never store a context in a struct. See go/server and Timeouts, Retries & Jitter.
Callbacks, promises, coroutines and channels Important
In plain words: four ways to say "do this, and when it is done, continue with that".
Common misunderstanding: "async/await is a different kind of concurrency." It is syntax over promises, which are syntax over callbacks. Under all of them is the same event loop (or scheduler) running continuations.
Definition:
| Style | You write | Where control goes | Errors | Cancel | Home |
|---|---|---|---|---|---|
| Callback | fetch(id, function(result, err) {...}) | Handed to the callee | A parameter you must check | Manual | Node (old style), Tk, browser events |
| Promise / future | fetch(id).then(f).catch(g) | A value that resolves later | .catch | AbortController (JS) | JavaScript, Java CompletableFuture, PHP ReactPHP |
| Coroutine / async-await | result = await fetch(id) | Suspended at await, resumed by the loop | try/catch | Task cancel | JavaScript, Python asyncio, C#, PHP Fibers (since 8.1) |
| Channel + goroutine | v := <-ch, select | The goroutine blocks, the runtime reschedules | Return error through the channel | context | Go |
Callback Future by channel (go/callbacks) Blocking style (go)
1 fetchCB(ctx, 1, func(v, err){}) ch := fetchFuture(ctx, 2) v, err := fetch(ctx, 3)
2 go on; callback fires later r := <-ch (or select with ctx) reads like normal code
3 nesting grows with each step composes with select/timeouts runtime parks the goroutineReal scenario: Node code that grew to five nested callbacks ("callback hell") and was rewritten with await; Go code that returns a channel and leaks a goroutine because nobody reads it (buffer the channel by 1, or take a ctx).
What provides it: Go: goroutines, channels and select (spec: a "select" statement chooses which of a set of possible send or receive operations will proceed). PHP 8.1+: Fibers are the low-level primitive; Laravel itself stays synchronous per request and gets concurrency from queues, Concurrency::run and Octane. JavaScript: promises and async/await.
Fix: in Go prefer the blocking style plus goroutines at the edges; use callbacks only where a framework demands them (e.g. http.HandlerFunc, AfterFunc).
UI and front-end events Good to know
In plain words: a click, a key press, a network reply: the browser puts them in a queue and a single thread handles them one by one.
Common misunderstanding: "A UI handler can take a moment." While a handler runs, the page cannot repaint or respond; the browser's model is run to completion. Long work needs to move off the main thread or be split.
Definition: the browser's event loop takes tasks from queues (input, timers, network) and runs each handler to completion; frameworks (Vue, React, Livewire, Alpine) layer reactive updates on top. The server pushes events to the page with SSE or WebSockets (Real-Time Communication).
Browser main thread Server
1 click -> handler: POST /orders ------------>
2 (handler returns at once) place order, dispatch OrderPlaced
3 UI shows "processing" queued listener updates status
4 <------------- broadcast: OrderStatusUpdated (WebSocket)
5 handler: re-render the order rowReal scenario: a checkout page that shows "processing" until a broadcast says "paid"; a dashboard updated by Laravel broadcasting (ShouldBroadcast, Reverb, Pusher, Ably).
What provides it: Laravel broadcasting: an event implements ShouldBroadcast and defines broadcastOn(); the docs describe broadcasting as sending server-side events to the client; MVC and presentation patterns are in Interaction & Presentation.
Fix: treat the UI as one more listener that sees events late and sometimes twice; render from the latest state, not from a sequence of messages.
Domain events vs integration events Must-know
In plain words: a domain event is a note you pass inside your own house; an integration event is a letter you post to another house.
Common misunderstanding: "I can publish my internal domain event on the broker as it is." Then every internal refactor breaks other teams. Translate: the domain event stays internal and free to change; the integration event is a deliberate, versioned public contract.
Definition:
| Aspect | Domain event | Integration event |
|---|---|---|
| Audience | Same bounded context / same deployable | Other services |
| Transport | In-process dispatcher | Broker (Kafka, RabbitMQ, SQS, ...) |
| Payload | Rich, may reference internal types | Small, stable, versioned, no internal ids by accident |
| Delivery | Sync or queued | At-least-once, async |
| Change cost | Low (one repo) | High (many consumers) |
| Transaction | Often same transaction | Needs an outbox |
Order module (domain) Translator / outbox Other services
1 OrderPlaced (internal, rich)
2 ----> ReserveLoyaltyPoints (sync listener)
3 ----> MapToIntegrationEvent -----> outbox row: order.placed v1 ----> relay ----> broker
4 consumers: billing, shippingReal scenario: a monolith whose OrderPlaced event is fine inside, and whose order.placed.v1 message to billing is a separate, documented schema.
What provides it: Laravel: the OrderPlaced event class (domain) plus a listener that writes the outbox row; Go: the in-process bus plus an outbox package. Bounded contexts decide which events may cross.
Fix: one translation point per boundary; consumers depend only on integration events.
Transactional boundary for events Must-know
In plain words: do not announce something that might still be rolled back, and do not lose an announcement for something that did commit.
Common misunderstanding: "Dispatching after commit solves it." It prevents announcing a rollback, but not loss: if the process crashes between COMMIT and dispatch, the event is gone and nobody retries. Only an outbox (event row in the same transaction) removes that gap, at the price of duplicates.
Definition: three placements for the dispatch (see the diagram): inside the transaction (a queued listener can run before COMMIT and not find the row), after commit (no phantom events, but a crash gap) and via an outbox row (no loss, possible duplicates; consumers must be idempotent).
App DB Queue worker
1 BEGIN ------------------->
2 INSERT order ------------->
3 dispatch(OrderPlaced) -----------------------------> picks job at once
4 SELECT order -> NOT FOUND (tx not committed)
5 COMMIT ------------------->
-- fix: ShouldDispatchAfterCommit / after_commit => dispatch only at step 5Real scenario: a confirmation email job that fails with "model not found" one time in fifty; a cache invalidated before the new value is visible, so the next reader re-caches the old value.
What provides it in Laravel 13 (three different interfaces, three different places):
| Interface (namespace) | Put it on | Effect |
|---|---|---|
Illuminate\Contracts\Events\ShouldDispatchAfterCommit | The event class | Event is dispatched only after the open transaction commits; discarded if it rolls back; dispatched at once if no transaction is open |
Illuminate\Contracts\Queue\ShouldQueueAfterCommit | A queued listener | Listener is pushed to the queue after commit (useful when the queue connection's after_commit is false) |
Illuminate\Contracts\Events\ShouldHandleEventsAfterCommit | An Eloquent observer | Observer methods run after the transaction commits |
'after_commit' => true | A queue connection in config/queue.php | Every job and queued listener on it waits for commit |
Go has no framework to do this for you: either commit first and then publish (with the crash gap) or use the outbox code.
Fix: use ShouldDispatchAfterCommit for in-process side effects; use an outbox for anything that must not be lost, such as integration events.
Error handling in handlers Important
In plain words: when a listener fails, someone must be told and the other listeners must still run.
Common misunderstanding: "If a listener throws, the publisher fails." True only for synchronous listeners: in Laravel, an exception from a sync listener propagates to dispatch() and stops later listeners. For queued listeners it does not; the job is retried and eventually lands in failed_jobs.
Definition: decide per listener: propagate (it is part of the use case), isolate (log and continue), or retry with backoff and then dead-letter. Panics in Go handlers must be recovered at the bus, never allowed to kill the process (go/bus turns them into errors).
| Failure | Sync listener | Async in-process goroutine | Queued listener / broker |
|---|---|---|---|
| Exception / error | Propagates to publisher | Error hook, no caller | Retried (#[Tries], #[Backoff]), then failed() and failed_jobs / DLQ |
| Panic | Recover and convert | Recover, else process dies | Worker catches, job fails |
| Timeout | Caller's deadline | Handler's own context.WithTimeout | Job timeout, worker kills the job |
| Poison event (always fails) | Fails the use case forever | Logs forever | Dead-letter it, alert, replay after the fix |
Queue worker Job: SendOrderConfirmation
1 pop job, attempt 1 ------------------> handle() throws (SMTP down)
2 release, backoff 1s
3 attempt 2 ---------------------------> throws
4 release, backoff 5s ... attempt 5 ----> throws
5 attempts exhausted -> failed($event, $e) -> row in failed_jobs -> alert, replay laterReal scenario: a payment provider outage making every ChargeCustomer listener retry; a malformed event that crashes the consumer on every delivery and blocks the partition behind it.
What provides it: Laravel: #[Tries], #[Backoff] (an array gives progressive delays), #[MaxExceptions], failed(), release() via InteractsWithQueue, php artisan queue:retry. Go: errors.Join, recover, your own retry. Broker side: Dead-Letter Queue, Retry, Backoff & Delayed Delivery. Policy: Error & Exception Handling.
Fix: every async listener needs a retry budget, a final failed path and an alert.
Testing event-driven code Important
In plain words: test two things separately: that the right event is published, and that each listener does the right thing when given an event.
Common misunderstanding: "Event::fake() tests the listener." It does the opposite: after Event::fake() "no event listeners will be executed". You are asserting the publisher, not the reaction.
Definition: three levels: (1) publisher test with a fake bus; (2) listener test: construct the event, call handle(); (3) wiring test: assert the listener is registered for the event (Event::assertListening); plus an end-to-end test that runs the real bus once.
| Need | Laravel 13 | Go |
|---|---|---|
| Capture events, skip listeners | Event::fake(), Event::fake([OrderPlaced::class]) | A fake Publisher interface that records |
| Assert published | Event::assertDispatched, assertDispatchedOnce, assertNotDispatched, assertNothingDispatched | Compare recorded slice |
| Assert wiring | Event::assertListening(Event::class, Listener::class) | Test the registration function |
| Fake only some events | Event::fake([...]) or Event::fakeFor(fn) | n/a |
| Queued side effects | Queue::fake(), Bus::fake() | Drain the bus in the test (Close) |
| Async determinism | Run listeners synchronously with the sync queue driver | Close(ctx) waits for async handlers; use channels, not time.Sleep |
| Race detection | n/a | go test -race |
Test What it proves
1 Event::fake([OrderPlaced]); PlaceOrder() the use case publishes exactly one OrderPlaced
2 new SendOrderConfirmation()->handle($event) the listener sends one mail, and a second call sends none
3 Event::assertListening(OrderPlaced, Send..) the wiring exists (renaming a class breaks the test)
4 one real run with sync queue the pieces work togetherReal scenario: a refactor renames a listener and the email silently stops: only the assertListening test catches it. Laravel's docs warn: call Event::fake() after using factories that rely on model events (for example a UUID set in creating).
Fix: keep listeners thin (call an application service), so listener tests are trivial and business tests do not need events.
Observability: correlation IDs Important
In plain words: give each request a number and stamp it on everything it causes: logs, events, jobs, outgoing calls.
Common misunderstanding: "Logs from the listener are enough." A listener log line says "sent email to 42" and nothing about the request that caused it. Without a shared ID, the flow that events hid cannot be reconstructed.
Definition: a correlation ID is generated at the edge (or taken from the incoming header), carried in context, written in every log line and copied into every event and outgoing request. A causation ID names the parent event. Distributed tracing (OpenTelemetry trace IDs) generalises it.
Edge (HTTP) Use case Event Queue worker Billing service
1 X-Correlation-Id: a1 Context::add(a1) --> OrderPlaced --> job restored: a1 --> header a1
2 log: "order 7 placed" corr=a1 log: dispatch corr=a1 log: "email sent" corr=a1 log corr=a1
3 grep corr=a1 across all services = the whole storyReal scenario: a customer says "I got two emails": one search by correlation ID shows two worker deliveries of the same job.
What provides it: Laravel's Context facade adds data to log entries and shares it "across the HTTP request / queued job boundary"; our middleware sets correlation_id (php/Http/CorrelationId.php). Go: store it with context.WithValue (go/bus) and keep it when you detach cancellation with context.WithoutCancel. Beyond one app: OpenTelemetry (see observability).
Fix: one middleware at the edge, one helper to read it, a lint rule that every log call includes it.
Per-language and per-framework view
| Platform | Control model | Event facility | Transaction-aware events | Cancellation |
|---|---|---|---|---|
| Go | Goroutine per connection, channels, select | None built in (channels); write a bus or use a library | Manual (commit, then publish) | context.Context |
| Laravel 13 (PHP-FPM) | One process per request; queue workers for async | Events, listeners, observers, broadcasting | ShouldDispatchAfterCommit, ShouldQueueAfterCommit, ShouldHandleEventsAfterCommit, after_commit | Job timeout, failed() |
| Laravel Octane | Long-lived workers serving many requests | Same, but static state persists between requests | Same | Same |
| Node.js | Event loop (libuv) | EventEmitter, streams | Manual | AbortController |
| Spring (Java) | Thread per request (or reactive/WebFlux) | ApplicationEventPublisher, @EventListener | @TransactionalEventListener (phase AFTER_COMMIT) | Future, reactive cancel |
| Django | Process/thread per request | Signals | transaction.on_commit | Request timeout |
| .NET | Thread pool + async/await | event delegates, MediatR notifications | Manual / outbox | CancellationToken |
| Browser | Single main thread, run to completion | DOM events, custom events | n/a | AbortController |
Mechanics
From a socket to your handler Important
When data arrives on a socket, the kernel marks the file descriptor ready. epoll (Linux) holds an interest list of descriptors and a ready list; epoll_wait blocks until the ready list has entries. kqueue with kevent is the BSD/macOS equivalent. epoll can be edge-triggered (told once when state changes, you must drain the socket) or level-triggered (told as long as data remains). Node's libuv and Go's netpoll call these primitives; the Go runtime parks the goroutine that waited on the socket and wakes it when the poller reports readiness. Node's loop cycles through phases (timers, pending callbacks, poll, check, close callbacks); since libuv 1.45.0 (Node.js 20) timers run after the poll phase in each iteration.
| Layer | Primitive | What it gives |
|---|---|---|
| Kernel | epoll, kqueue, IOCP (Windows) | Readiness notification for many descriptors |
| Runtime | libuv loop, Go netpoll | Turns readiness into "run this callback" or "wake this goroutine" |
| Framework | net/http server, Laravel HTTP kernel | Turns a connection into a request and calls your handler |
| Your code | Handler, listener | Business reaction |
Laravel's dispatch path Important
Event::dispatch() finds listeners registered for the event class: by event discovery (public handle or __invoke methods in app/Listeners whose first parameter is type-hinted with the event), or manually with Event::listen. Sync listeners run in order in the same process; returning false stops propagation. A listener implementing ShouldQueue is not called at once: Laravel pushes a queued job carrying the event, a worker later resolves the listener through the container and calls it. Events and queued listeners are serialised, which is why models are re-fetched by SerializesModels.
| Knob (Laravel 13) | Where | Meaning |
|---|---|---|
ShouldQueue | Listener | Run on a queue worker |
ShouldDispatchAfterCommit | Event | Dispatch after the open transaction commits |
ShouldQueueAfterCommit | Queued listener | Queue after commit |
ShouldHandleEventsAfterCommit | Observer | Run after commit |
after_commit | config/queue.php connection | Default for all jobs on that connection |
#[Tries(n)] | Listener | Max attempts |
#[Backoff(...)] | Listener | Delay between attempts (an array gives progressive delays) |
#[MaxExceptions(n)] | Listener | Fail after n unhandled exceptions even if more tries remain |
retryUntil() | Listener | Time-based retry window; wins over tries |
ShouldBeUnique, uniqueId() | Listener | Only one instance of the listener on the queue at a time |
ShouldBeUniqueUntilProcessing | Listener | Release the unique lock when processing starts |
WithoutOverlapping | Job middleware | Limit concurrent processing |
#[DebounceFor] | Listener | Collapse bursts into one run (not combinable with ShouldBeUnique) |
failed(Event, Throwable) | Listener | Called after attempts are exhausted |
retry_after | Queue connection | Seconds before a reserved job is released again (set above the longest job) |
Go's building blocks Important
| Primitive | What it does here |
|---|---|
| Goroutine | One flow of control per handler or connection |
| Channel | Delivers an event to one consumer; blocking handoff or buffer |
select | Waits for the first of several events, including ctx.Done() and timers |
sync.WaitGroup | Waits for in-flight async handlers on shutdown |
context.WithTimeout / WithCancel | Deadline and cancellation per handler |
context.WithoutCancel | Keeps values (correlation ID) and drops the caller's cancellation |
context.AfterFunc(ctx, f) | Runs f when ctx is cancelled: ties a handler to bus shutdown |
signal.NotifyContext | Turns SIGINT/SIGTERM into a cancelled context |
http.Server.Shutdown(ctx) | Stops accepting, drains, returns ErrServerClosed to ListenAndServe |
errors.Join | Collects errors from several sync listeners |
recover | Converts a handler panic to an error |
Error and signal reference Good to know
| Symptom | Meaning | Look at |
|---|---|---|
context canceled | The caller or a signal cancelled the work | Who called cancel() |
context deadline exceeded | A timeout fired | The deadline chain; slowest hop |
http: Server closed (http.ErrServerClosed) | Normal result of Shutdown | Not an error; check with errors.Is |
Laravel ModelNotFoundException in a queued listener | Job ran before commit, or row deleted | ShouldDispatchAfterCommit, after_commit |
MaxAttemptsExceededException | Job used all attempts (or was released too often) | #[Tries], retry_after, job duration |
SIGTERM (15), SIGKILL (9) | Polite stop, then forced stop after the grace period | Shutdown time vs terminationGracePeriodSeconds |
SIGINT (2) | Ctrl-C | Same handling as SIGTERM in dev |
Go
Example: an in-process bus with sync and async listeners
Go has no event framework in the standard library, and does not need one: a bus is a map from event name to listeners plus a few rules. This one has two modes. Sync listeners run inside Publish, in order, on the caller's goroutine, and their errors come back to the caller. Async listeners run on their own goroutine with their own timeout, keep the caller's correlation ID but not its cancellation, and are cancelled when the bus closes. The lock is released before handlers run, so a handler may publish again (reentrancy); a panic becomes an error.
// Package bus is a small in-process event bus for a monolith.
//
// Sync listeners run inside Publish, in registration order, on the caller's
// goroutine: they share the caller's context, deadline and (if you pass one)
// transaction. Async listeners run on their own goroutine with their own
// timeout and are cancelled when the bus shuts down.
package bus
import (
"context"
"errors"
"fmt"
"sync"
"time"
)
// Event is a fact that already happened. Name is past tense: "order.placed".
type Event interface {
Name() string
}
// Handler reacts to one event. It must be idempotent (see the idempotent snippet).
type Handler func(ctx context.Context, e Event) error
// Mode says where a listener runs.
type Mode int
const (
// Sync runs inside Publish; its error is returned to the publisher.
Sync Mode = iota
// Async runs on its own goroutine; its error goes to the error hook.
Async
)
type subscription struct {
name string
mode Mode
h Handler
}
// Bus routes events to listeners.
type Bus struct {
mu sync.RWMutex
subs map[string][]subscription
wg sync.WaitGroup
root context.Context
stop context.CancelFunc
timeout time.Duration
onError func(e Event, listener string, err error)
}
// New creates a bus. asyncTimeout bounds every async handler run.
func New(asyncTimeout time.Duration, onError func(Event, string, error)) *Bus {
root, stop := context.WithCancel(context.Background())
if onError == nil {
onError = func(Event, string, error) {}
}
return &Bus{
subs: make(map[string][]subscription),
root: root,
stop: stop,
timeout: asyncTimeout,
onError: onError,
}
}
// Subscribe registers a listener for an event name.
func (b *Bus) Subscribe(eventName, listener string, mode Mode, h Handler) {
b.mu.Lock()
defer b.mu.Unlock()
b.subs[eventName] = append(b.subs[eventName], subscription{name: listener, mode: mode, h: h})
}
// Publish delivers e. Sync errors are joined and returned; async errors are
// reported through the error hook. The lock is NOT held while handlers run,
// so a handler may publish further events (re-entrancy) or subscribe.
func (b *Bus) Publish(ctx context.Context, e Event) error {
b.mu.RLock()
list := append([]subscription(nil), b.subs[e.Name()]...)
b.mu.RUnlock()
var errs []error
for _, s := range list {
if s.mode == Async {
b.runAsync(ctx, e, s)
continue
}
if err := safeCall(ctx, s.h, e); err != nil {
errs = append(errs, fmt.Errorf("%s: %w", s.name, err))
}
if ctx.Err() != nil { // cancellation is control flow: stop delivering
errs = append(errs, ctx.Err())
break
}
}
return errors.Join(errs...)
}
func (b *Bus) runAsync(ctx context.Context, e Event, s subscription) {
// Keep the values of the caller (correlation id) but not its cancellation:
// the HTTP request may finish long before the listener does.
hctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), b.timeout)
// Bus shutdown must still reach the handler.
stopAfter := context.AfterFunc(b.root, cancel)
b.wg.Add(1)
go func() {
defer b.wg.Done()
defer cancel()
defer stopAfter()
if err := safeCall(hctx, s.h, e); err != nil {
b.onError(e, s.name, err)
}
}()
}
// Close cancels running async handlers and waits for them, or for ctx.
func (b *Bus) Close(ctx context.Context) error {
b.stop()
done := make(chan struct{})
go func() { b.wg.Wait(); close(done) }()
select {
case <-done:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func safeCall(ctx context.Context, h Handler, e Event) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic in handler: %v", r)
}
}()
return h(ctx, e)
}
type ctxKey struct{}
// WithCorrelationID stores the id that ties a request to every event it causes.
func WithCorrelationID(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, ctxKey{}, id)
}
// CorrelationID reads it back ("" when absent).
func CorrelationID(ctx context.Context) string {
id, _ := ctx.Value(ctxKey{}).(string)
return id
}The tests pin the behaviour: a sync error reaches the publisher; Close cancels a slow async handler; an async handler still sees the correlation ID after the request is cancelled; a panic is an error. Run them with the race detector.
package bus_test
import (
"context"
"errors"
"sync/atomic"
"testing"
"time"
"academy/control-and-event-handling/bus"
)
type placed struct{ ID string }
func (placed) Name() string { return "order.placed" }
func TestSyncErrorReachesPublisher(t *testing.T) {
b := bus.New(time.Second, nil)
b.Subscribe("order.placed", "reserve-stock", bus.Sync, func(context.Context, bus.Event) error {
return errors.New("out of stock")
})
if err := b.Publish(context.Background(), placed{ID: "o1"}); err == nil {
t.Fatal("expected the sync listener error")
}
}
func TestAsyncRunsAfterPublishAndIsCancelledOnClose(t *testing.T) {
var cancelled atomic.Bool
started := make(chan struct{})
b := bus.New(time.Minute, nil)
b.Subscribe("order.placed", "slow", bus.Async, func(ctx context.Context, _ bus.Event) error {
close(started)
<-ctx.Done()
cancelled.Store(true)
return ctx.Err()
})
if err := b.Publish(context.Background(), placed{ID: "o1"}); err != nil {
t.Fatal(err)
}
<-started
ctx, stop := context.WithTimeout(context.Background(), time.Second)
defer stop()
if err := b.Close(ctx); err != nil {
t.Fatalf("close: %v", err)
}
if !cancelled.Load() {
t.Fatal("async handler was not cancelled by Close")
}
}
func TestAsyncKeepsCorrelationIDButNotCancellation(t *testing.T) {
got := make(chan string, 1)
b := bus.New(time.Second, nil)
b.Subscribe("order.placed", "audit", bus.Async, func(ctx context.Context, _ bus.Event) error {
time.Sleep(20 * time.Millisecond) // request context is already cancelled by now
if ctx.Err() != nil {
return ctx.Err()
}
got <- bus.CorrelationID(ctx)
return nil
})
req, cancel := context.WithCancel(bus.WithCorrelationID(context.Background(), "req-42"))
_ = b.Publish(req, placed{ID: "o1"})
cancel() // the HTTP request ends
if id := <-got; id != "req-42" {
t.Fatalf("correlation id = %q", id)
}
_ = b.Close(context.Background())
}
func TestPanicIsAnError(t *testing.T) {
b := bus.New(time.Second, nil)
b.Subscribe("order.placed", "bad", bus.Sync, func(context.Context, bus.Event) error { panic("boom") })
if err := b.Publish(context.Background(), placed{}); err == nil {
t.Fatal("expected an error for a panicking listener")
}
}The Go angle
Control and inversion of control. net/http is the framework: you register handlers and ListenAndServe never returns until shutdown. Compare the two shapes:
// Library vs framework: who owns the main loop?
package main
import (
"fmt"
"net/http"
"strings"
)
// Call-return: my code is in control and calls a library.
func callReturn() {
name := strings.ToUpper("ada") // library call, returns at once
fmt.Println("call-return:", name)
}
// Inversion of control: I register a callback and hand control to the framework.
// net/http is the framework here; it decides when (and on which goroutine) to call me.
func inverted() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /hello/{name}", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello %s\n", r.PathValue("name"))
})
return mux
}
func main() {
callReturn()
// "Don't call us, we'll call you": ListenAndServe never returns until shutdown.
// Uncomment to run: _ = http.ListenAndServe(":8080", inverted())
_ = inverted()
}One goroutine owns the state. Instead of locking, send events to a goroutine that owns the data and wait for it in a select together with timers and cancellation. This is the Go form of an event loop ("share memory by communicating"); the full treatment of races and locks is in Designing for Concurrency.
// A single-goroutine event loop: one owner of the state, events arrive on channels.
// No locks are needed because only the loop goroutine touches `balance`.
package main
import (
"context"
"fmt"
"time"
)
type deposit struct{ cents int64 }
type query struct{ reply chan int64 }
func loop(ctx context.Context, deposits <-chan deposit, queries <-chan query) {
var balance int64
tick := time.NewTicker(50 * time.Millisecond) // temporal event
defer tick.Stop()
for {
select {
case d := <-deposits: // reactive event
balance += d.cents
case q := <-queries:
q.reply <- balance
case <-tick.C:
fmt.Println("tick: balance =", balance)
case <-ctx.Done(): // cancellation is an event too
fmt.Println("loop stopped:", ctx.Err())
return
}
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 180*time.Millisecond)
defer cancel()
deposits := make(chan deposit)
queries := make(chan query)
done := make(chan struct{})
go func() { loop(ctx, deposits, queries); close(done) }()
deposits <- deposit{cents: 500}
deposits <- deposit{cents: 250}
q := query{reply: make(chan int64, 1)}
queries <- q
fmt.Println("balance via query:", <-q.reply)
<-done
}State machine as a table. The legal flows are data, so a reviewer can read them in one screen and a test can enumerate them.
// A state machine as control flow: the current state plus an event decides the next state.
package main
import (
"errors"
"fmt"
)
type State string
type Event string
const (
Placed State = "placed"
Paid State = "paid"
Shipped State = "shipped"
Cancelled State = "cancelled"
PaymentCaptured Event = "payment.captured"
ShipmentSent Event = "shipment.sent"
CancelRequested Event = "cancel.requested"
)
var ErrIllegal = errors.New("illegal transition")
// The table IS the design: a reviewer reads the legal flows in one place.
var transitions = map[State]map[Event]State{
Placed: {PaymentCaptured: Paid, CancelRequested: Cancelled},
Paid: {ShipmentSent: Shipped, CancelRequested: Cancelled},
}
func Next(s State, e Event) (State, error) {
if to, ok := transitions[s][e]; ok {
return to, nil
}
return s, fmt.Errorf("%w: %s on %s", ErrIllegal, e, s)
}
func main() {
s := Placed
for _, e := range []Event{PaymentCaptured, ShipmentSent, CancelRequested} {
next, err := Next(s, e)
fmt.Printf("%-9s + %-16s -> %-9s err=%v\n", s, e, next, err)
s = next
}
}Idempotent, order-tolerant handler. Dedupe by event ID and ignore events older than the version already applied. In production the seen set is a table with a unique key (see the SQL in Solving the classic problems).
// An idempotent, order-tolerant handler: dedupe by event ID, ignore stale versions.
package main
import (
"fmt"
"sync"
)
type OrderStatusChanged struct {
EventID string // unique per event, stable across redelivery
OrderID string
Version int64 // per-aggregate sequence number
Status string
}
type Projection struct {
mu sync.Mutex
seen map[string]struct{}
version map[string]int64
status map[string]string
}
func NewProjection() *Projection {
return &Projection{
seen: map[string]struct{}{},
version: map[string]int64{},
status: map[string]string{},
}
}
// Handle may be called twice, or out of order, with the same final result.
func (p *Projection) Handle(e OrderStatusChanged) (applied bool) {
p.mu.Lock()
defer p.mu.Unlock()
if _, dup := p.seen[e.EventID]; dup {
return false // duplicate delivery
}
p.seen[e.EventID] = struct{}{}
if e.Version <= p.version[e.OrderID] {
return false // stale: a newer fact was already applied
}
p.version[e.OrderID] = e.Version
p.status[e.OrderID] = e.Status
return true
}
func main() {
p := NewProjection()
events := []OrderStatusChanged{
{"e1", "o1", 1, "placed"},
{"e3", "o1", 3, "shipped"}, // arrives before e2
{"e2", "o1", 2, "paid"}, // late: ignored, shipped wins
{"e3", "o1", 3, "shipped"}, // redelivery: ignored
}
for _, e := range events {
fmt.Printf("%s v%d %-8s applied=%v\n", e.EventID, e.Version, e.Status, p.Handle(e))
}
fmt.Println("final:", p.status["o1"])
}Timeouts, signals and graceful shutdown. signal.NotifyContext turns an OS interrupt into a cancelled context; Server.Shutdown drains in-flight requests; the per-request timeout is derived from r.Context(), so a client that leaves cancels the work. BaseContext uses context.WithoutCancel so that in-flight requests are allowed to finish during the grace period instead of being cancelled the moment the signal arrives.
// Timeouts and cancellation as control flow: signal -> context -> graceful shutdown.
package main
import (
"context"
"errors"
"log"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func slow(w http.ResponseWriter, r *http.Request) {
// r.Context() is cancelled when the client disconnects or the server shuts down hard.
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
select {
case <-time.After(5 * time.Second): // pretend downstream call
_, _ = w.Write([]byte("done\n"))
case <-ctx.Done():
http.Error(w, ctx.Err().Error(), http.StatusGatewayTimeout)
}
}
func main() {
if os.Getenv("RUN") == "" {
log.Println("set RUN=1 to start the server")
return
}
// SIGINT/SIGTERM become a cancelled context: an OS event turned into control flow.
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
mux := http.NewServeMux()
mux.HandleFunc("GET /slow", slow)
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
IdleTimeout: 60 * time.Second,
// Not ctx itself: we want in-flight requests to finish on a graceful shutdown.
BaseContext: func(net.Listener) context.Context { return context.WithoutCancel(ctx) },
}
go func() {
<-ctx.Done()
grace, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(grace); err != nil { // stops accepting, drains, or gives up
log.Println("shutdown:", err)
}
}()
if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
log.Println("bye")
}Callbacks, futures and blocking style side by side. The buffered channel (size 1) means the goroutine never leaks if nobody reads the result.
// The same asynchronous call in three shapes: callback, future-by-channel, blocking goroutine.
package main
import (
"context"
"fmt"
"sync"
"time"
)
func fetch(ctx context.Context, id int) (string, error) {
select {
case <-time.After(20 * time.Millisecond):
return fmt.Sprintf("user-%d", id), nil
case <-ctx.Done():
return "", ctx.Err()
}
}
// 1. Callback: control is handed away; errors and ordering are your problem.
func fetchCB(ctx context.Context, id int, done func(string, error)) {
go func() { done(fetch(ctx, id)) }()
}
// 2. Future by channel: a value you can select on, compose, and cancel.
type result struct {
val string
err error
}
func fetchFuture(ctx context.Context, id int) <-chan result {
ch := make(chan result, 1) // buffered: the goroutine never leaks if nobody reads
go func() {
v, err := fetch(ctx, id)
ch <- result{v, err}
}()
return ch
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
var wg sync.WaitGroup
wg.Add(1)
fetchCB(ctx, 1, func(v string, err error) {
defer wg.Done()
fmt.Println("callback:", v, err)
})
wg.Wait()
r := <-fetchFuture(ctx, 2)
fmt.Println("future: ", r.val, r.err)
// 3. Coroutine style: just block; the runtime parks the goroutine, not a thread.
v, err := fetch(ctx, 3)
fmt.Println("blocking:", v, err)
}Transactional boundary: outbox. The order row and the event row commit together; a relay publishes later. A crash between publish and the UPDATE re-sends the row, so consumers must be idempotent. The pattern itself is in Transactional Outbox.
// Package outbox shows the transactional boundary for events: the state change and
// the event row commit together; a relay publishes later (at-least-once).
// Full pattern: /messaging/outbox-pattern. Compiles without a driver.
package outbox
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"time"
)
type OrderPlaced struct {
EventID string `json:"event_id"`
Version int `json:"version"` // schema version of THIS payload
OrderID int64 `json:"order_id"`
CustomerID int64 `json:"customer_id"`
CorrelationID string `json:"correlation_id"`
OccurredAt string `json:"occurred_at"`
}
// PlaceOrder writes the order and the event in ONE transaction.
func PlaceOrder(ctx context.Context, db *sql.DB, customerID int64, corr string) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback() //nolint:errcheck // no-op after Commit
var orderID int64
if err := tx.QueryRowContext(ctx,
`INSERT INTO orders (customer_id, status) VALUES ($1, 'placed') RETURNING id`,
customerID).Scan(&orderID); err != nil {
return err
}
payload, err := json.Marshal(OrderPlaced{
EventID: fmt.Sprintf("order-%d-placed", orderID), Version: 1,
OrderID: orderID, CustomerID: customerID, CorrelationID: corr,
OccurredAt: time.Now().UTC().Format(time.RFC3339),
})
if err != nil {
return err
}
if _, err := tx.ExecContext(ctx,
`INSERT INTO outbox (aggregate_id, type, payload) VALUES ($1, 'order.placed', $2)`,
orderID, payload); err != nil {
return err
}
return tx.Commit() // both rows or neither
}
// RelayOnce publishes unpublished rows. A crash after publish and before the
// UPDATE re-sends the row: consumers must be idempotent.
func RelayOnce(ctx context.Context, db *sql.DB, publish func(context.Context, string, []byte) error) error {
rows, err := db.QueryContext(ctx,
`SELECT id, type, payload FROM outbox WHERE published_at IS NULL ORDER BY id LIMIT 100`)
if err != nil {
return err
}
type row struct {
id int64
typ string
payload []byte
}
var batch []row
for rows.Next() {
var r row
if err := rows.Scan(&r.id, &r.typ, &r.payload); err != nil {
rows.Close()
return err
}
batch = append(batch, r)
}
if err := rows.Close(); err != nil {
return err
}
for _, r := range batch {
if err := publish(ctx, r.typ, r.payload); err != nil {
return err // stop at the first failure to keep order
}
if _, err := db.ExecContext(ctx, `UPDATE outbox SET published_at = now() WHERE id = $1`, r.id); err != nil {
return err
}
}
return nil
}The Go habits that matter: pass ctx first and honour it; defer cancel(); recover panics at the edge of a handler, not inside business code; never start a goroutine without knowing how it ends (a WaitGroup, a Close, a context).
Laravel
Before
The use case calls every consequence by hand, inside the transaction. A slow mail server holds the database transaction open; if the commit fails after the mail was sent, the customer holds a confirmation for an order that does not exist; every new reaction edits this class.
<?php
declare(strict_types=1);
namespace App\Services;
use App\Mail\OrderConfirmation;
use App\Models\Order;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
/**
* Bad design: the use case calls every consequence directly, inside the transaction.
* - a slow SMTP/HTTP call holds the database transaction open;
* - if the mail succeeds and the commit fails, the customer got a mail for no order;
* - adding "notify the warehouse" means editing this class again (closed to extension).
*/
final class OrderService
{
public function place(int $customerId, array $lines): Order
{
return DB::transaction(function () use ($customerId, $lines): Order {
$order = Order::create(['customer_id' => $customerId, 'status' => 'placed']);
$order->lines()->createMany($lines);
Mail::to($order->customer)->send(new OrderConfirmation($order)); // slow, inside the tx
Http::post('https://warehouse.internal/api/orders', ['id' => $order->id]); // remote, inside the tx
return $order;
});
}
}After
Three moves. (1) The consistency-critical work (Stock::reserve) stays in the transaction as a plain call. (2) Everything else becomes a listener of a past-tense event that is dispatched only after commit. (3) Slow listeners are queued, retried and idempotent.
The event is a small public contract:
<?php
declare(strict_types=1);
namespace App\Events;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Support\Str;
/**
* A fact, named in the past tense. Carries ids and a few stable values, not live models:
* listeners re-read current state, and the payload stays small and serialisable.
*/
final class OrderPlaced implements ShouldDispatchAfterCommit
{
use Dispatchable;
public const int VERSION = 1; // bump when the payload shape changes
public readonly string $eventId;
public function __construct(
public readonly int $orderId,
public readonly int $customerId,
public readonly int $totalCents,
public readonly string $occurredAt,
?string $eventId = null,
) {
$this->eventId = $eventId ?? (string) Str::uuid();
}
}The use case announces the fact and does not know who listens:
<?php
declare(strict_types=1);
namespace App\Actions;
use App\Events\OrderPlaced;
use App\Models\Order;
use App\Models\Stock;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
final class PlaceOrder
{
/**
* @param list<array{sku: string, qty: int, unit_cents: int}> $lines
*/
public function __invoke(int $customerId, array $lines): Order
{
return DB::transaction(function () use ($customerId, $lines): Order {
// The consistency-critical part stays in the transaction (same process, same database).
foreach ($lines as $line) {
Stock::reserve($line['sku'], $line['qty']); // throws when stock is short -> rollback
}
$order = Order::create(['customer_id' => $customerId, 'status' => 'placed']);
$order->lines()->createMany($lines);
// ShouldDispatchAfterCommit: held until COMMIT, discarded on rollback.
OrderPlaced::dispatch(
$order->id,
$customerId,
(int) collect($lines)->sum(fn (array $l): int => $l['qty'] * $l['unit_cents']),
Carbon::now()->toIso8601String(),
);
return $order;
});
}
}An asynchronous listener with a retry budget, a dedupe key and a failed path. Context::get brings the correlation ID across the queue boundary.
<?php
declare(strict_types=1);
namespace App\Listeners;
use App\Events\OrderPlaced;
use App\Mail\OrderConfirmation;
use App\Models\Order;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;
/**
* Asynchronous side effect: runs on a queue worker, may run twice, so it dedupes.
*/
#[Tries(5)]
#[Backoff([1, 5, 30])]
final class SendOrderConfirmation implements ShouldQueue
{
use InteractsWithQueue;
public function handle(OrderPlaced $event): void
{
// Context carries the correlation id from the HTTP request into this worker.
Log::info('sending order confirmation', [
'order_id' => $event->orderId,
'correlation_id' => Context::get('correlation_id'),
]);
// Idempotency: the unique key (listener, event_id) turns the second run into a no-op.
$first = DB::table('processed_events')->insertOrIgnore([
'listener' => self::class,
'event_id' => $event->eventId,
'processed_at' => now(),
]);
if ($first === 0) {
return;
}
$order = Order::findOrFail($event->orderId);
Mail::to($order->customer)->send(new OrderConfirmation($order));
}
public function failed(OrderPlaced $event, Throwable $e): void
{
// After the last retry: alert, and keep the failed job for replay (see /messaging/dead-letter-queue).
Log::error('order confirmation gave up', ['order_id' => $event->orderId, 'error' => $e->getMessage()]);
}
}A synchronous listener, for work that must be done before dispatch() returns:
<?php
declare(strict_types=1);
namespace App\Listeners;
use App\Events\OrderPlaced;
use App\Models\LoyaltyAccount;
/**
* Synchronous listener: runs inside dispatch(), on the caller's process.
* Use it only for work that must finish before the use case returns.
* If it throws, the exception reaches whoever called OrderPlaced::dispatch().
*/
final class ReserveLoyaltyPoints
{
public function handle(OrderPlaced $event): void
{
LoyaltyAccount::where('customer_id', $event->customerId)
->increment('pending_points', intdiv($event->totalCents, 100));
}
}The Laravel angle
Discovery and registration. Laravel scans app/Listeners and registers any public handle or __invoke method whose first parameter is a type-hinted event (a union type listens to several). Registered by discovery, a rename of the event class is a silent break, hence the wiring test below. In production run php artisan event:cache; the docs describe event discovery in production.
Observers are the Observer pattern for Eloquent lifecycle events (created, updated, deleted...). Register with #[ObservedBy([OrderObserver::class])]. By default they run inside the model operation, possibly inside a transaction; implement ShouldHandleEventsAfterCommit to wait for the commit. saveQuietly() and Model::withoutEvents() silence model events for a write.
<?php
declare(strict_types=1);
namespace App\Observers;
use App\Models\Order;
use Illuminate\Contracts\Events\ShouldHandleEventsAfterCommit;
use Illuminate\Support\Facades\Cache;
/**
* Observers listen to model lifecycle events (created, updated, deleted ...).
* ShouldHandleEventsAfterCommit makes them wait for the surrounding transaction.
* Register on the model with #[ObservedBy([OrderObserver::class])].
*/
final class OrderObserver implements ShouldHandleEventsAfterCommit
{
public function updated(Order $order): void
{
// Cache invalidation must not run before the new row is visible to other connections.
Cache::forget("orders.{$order->id}.summary");
}
}Correlation ID. One middleware sets it; Context adds it to log entries and to the queued job's payload.
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
/**
* One id per request, reused if the caller sent one. Laravel's Context adds it to every
* log line and carries it across the queue boundary to the listener that runs later.
*/
final class CorrelationId
{
public function handle(Request $request, Closure $next): Response
{
$id = $request->header('X-Correlation-Id') ?: (string) Str::uuid();
Context::add('correlation_id', $id);
$response = $next($request);
$response->headers->set('X-Correlation-Id', $id);
return $response;
}
}Testing. Event::fake() records dispatches and skips listeners; assertListening checks the wiring; a rollback produces no event.
<?php
declare(strict_types=1);
namespace Tests\Feature;
use App\Actions\PlaceOrder;
use App\Events\OrderPlaced;
use App\Listeners\SendOrderConfirmation;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
use Tests\TestCase;
final class PlaceOrderTest extends TestCase
{
use RefreshDatabase;
public function test_placing_an_order_announces_a_fact(): void
{
Event::fake([OrderPlaced::class]); // listeners do NOT run
$order = app(PlaceOrder::class)(customerId: 7, lines: [
['sku' => 'A-1', 'qty' => 2, 'unit_cents' => 1500],
]);
Event::assertDispatchedOnce(OrderPlaced::class);
Event::assertDispatched(
fn (OrderPlaced $e): bool => $e->orderId === $order->id && $e->totalCents === 3000,
);
}
public function test_the_wiring_exists(): void
{
Event::fake(); // assertListening is a method of the fake
Event::assertListening(OrderPlaced::class, SendOrderConfirmation::class);
}
public function test_a_rolled_back_order_announces_nothing(): void
{
Event::fake([OrderPlaced::class]);
try {
app(PlaceOrder::class)(customerId: 7, lines: [
['sku' => 'OUT-OF-STOCK', 'qty' => 1, 'unit_cents' => 100],
]);
} catch (\Throwable) {
// expected: stock reservation failed, transaction rolled back
}
Event::assertNotDispatched(OrderPlaced::class);
}
}Broadcasting sends the same idea to the browser: ShouldBroadcast plus broadcastOn().
<?php
declare(strict_types=1);
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
/**
* The same event idea, pushed to the browser: the front-end is just another listener.
*/
final class OrderStatusUpdated implements ShouldBroadcast
{
use Dispatchable;
use InteractsWithSockets;
public function __construct(public readonly int $orderId, public readonly string $status) {}
public function broadcastOn(): PrivateChannel
{
return new PrivateChannel("orders.{$this->orderId}");
}
}Outbox tables and relay. The migration creates outbox and processed_events; the command is a relay that locks rows with FOR UPDATE SKIP LOCKED so several relays can run.
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('outbox', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('aggregate_id');
$table->string('type'); // e.g. order.placed
$table->json('payload'); // includes event_id and version
$table->timestamp('created_at')->useCurrent();
$table->timestamp('published_at')->nullable()->index();
});
Schema::create('processed_events', function (Blueprint $table): void {
$table->string('listener');
$table->string('event_id');
$table->timestamp('processed_at');
$table->primary(['listener', 'event_id']); // the dedupe guarantee
});
}
};<?php
declare(strict_types=1);
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
/**
* Integration events leave the monolith through an outbox row written in the same
* transaction as the state change. This relay is the publisher; run it every second.
* Pattern details: /messaging/outbox-pattern.
*/
final class PublishOutbox extends Command
{
protected $signature = 'outbox:publish {--batch=100}';
protected $description = 'Publish unpublished outbox rows to the broker (at-least-once)';
public function handle(): int
{
DB::transaction(function (): void {
$rows = DB::table('outbox')
->whereNull('published_at')
->orderBy('id')
->limit((int) $this->option('batch'))
->lock('for update skip locked') // several relays can run side by side
->get();
foreach ($rows as $row) {
$this->publish($row->type, $row->payload); // broker client: Kafka, RabbitMQ, SQS ...
DB::table('outbox')->where('id', $row->id)->update(['published_at' => now()]);
}
});
return self::SUCCESS;
}
private function publish(string $type, string $payload): void
{
// Left to the broker client of your choice; must be safe to call twice.
}
}Laravel habits that matter: events carry ids and facts, not live models; a listener that must not run twice dedupes; after-commit is a property of the event, the listener or the connection, so know which one you set; do not dispatch events from inside a loop of thousands of model saves without thinking about the queue.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limit |
|---|---|---|---|---|
| Invisible flow ("what reacts to this?") | Document and log the graph | Listener list in the event's doc comment; log delivery with the correlation ID | Cheap, immediate | Needs discipline |
| Event announced for a rolled-back change | After-commit dispatch | ShouldDispatchAfterCommit, after_commit | One interface | Crash gap remains |
| Event lost between commit and dispatch | Transactional outbox | Row in the same transaction, relay publishes | No loss | Duplicates, relay to run |
| Duplicate delivery | Idempotent handler | Unique (listener, event_id) | Safe retries | One write per event |
| Out-of-order delivery | Version check or partition by key | WHERE version < :v; Kafka key; ShouldBeUnique | Correct final state | Limits parallelism |
| Slow listener blocks the request | Queue the listener | ShouldQueue; goroutine with timeout | Fast responses | Eventual consistency |
| Handler leaks work after the caller left | Cancellation | context; job timeout | Resources freed | Every layer must honour it |
| Poison event | Retry budget, DLQ | #[Tries], failed(), dead-letter | Pipeline keeps moving | Needs alert and replay |
| Event cycle | Break by design; saveQuietly | Draw the graph | No loop | Review effort |
| Unbounded fan-out in Go | Bounded worker pool | Semaphore or fixed workers | Stable memory | Backpressure choice (Backpressure) |
The dedupe table in SQL, for PostgreSQL (the same shape works in MySQL with INSERT IGNORE):
-- one row per (listener, event) that has been handled
CREATE TABLE processed_events (
listener text NOT NULL,
event_id text NOT NULL,
processed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (listener, event_id)
);
-- the handler's first statement: 1 row inserted = first time, 0 = duplicate
INSERT INTO processed_events (listener, event_id)
VALUES ('send-order-confirmation', 'a1b2c3')
ON CONFLICT DO NOTHING;
-- outbox written in the same transaction as the order
CREATE TABLE outbox (
id bigserial PRIMARY KEY,
aggregate_id bigint NOT NULL,
type text NOT NULL,
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz
);
CREATE INDEX outbox_unpublished ON outbox (id) WHERE published_at IS NULL;
-- relay: several relays can run without taking the same rows
SELECT id, type, payload FROM outbox
WHERE published_at IS NULL ORDER BY id LIMIT 100
FOR UPDATE SKIP LOCKED;Event spaghetti
Symptom: ten listeners, three of which publish further events, and nobody can say what a click does. Moves: keep a one-page event catalogue (event, producers, listeners, sync/async, owner); put orchestration that really is a flow into one explicit place (a use case or a saga) and keep events for notifications. Fowler's warning: "it's very easy to make nicely decoupled systems with event notification, without realizing that you're losing sight of that larger-scale flow".
The passive-aggressive command
Symptom: SendInvoiceRequested is published and exactly one listener is expected to act. That is a command wearing an event's name. Move: name it as a command (SendInvoice), send it to its one handler, and expect a result or a failure; keep events for facts.
Choosing: which control style and which handling
| Situation | Recommended | Extra technique | Reason |
|---|---|---|---|
| Caller needs the result to continue | Call-return | Timeout via context | Simplest, most debuggable |
| Reaction must be atomic with the change | Plain call in the same transaction | DB::transaction | Consistency over decoupling |
| Side effect, same app, can wait | Domain event + queued listener | ShouldDispatchAfterCommit, idempotency | Decoupled and off the request path |
| Side effect that must never be lost | Outbox + relay | Idempotent consumers | Event row commits with the data |
| Another team's service needs to react | Integration event on a broker | Versioned schema, DLQ | Contract between deployables |
| Legal flow of a lifecycle | State machine table | Transition tests | Illegal moves become impossible |
| UI shows live status | Broadcast + "processing" state | Render from latest state | UI is a late listener |
| Many I/O-bound connections, short handlers | Event loop or goroutine per connection | Timeouts, backpressure | Cheap concurrency |
| CPU-heavy work in a request | Move off the loop; a worker pool or queue | Bounded concurrency | Do not stall others |
| Shutdown or deploy | Signal to context, graceful drain | Grace period larger than longest request | No dropped work |
In architecture: from a single process to a distributed system
Monolith: one process, one database
Everyday example. A shop in Laravel: PlaceOrder reserves stock in the transaction, dispatches OrderPlaced after commit, a queued listener sends the email, a sync listener adds loyalty points. The Go equivalent is the bus: sync reserve-stock, async send-email.
Production example. Same app under load: the confirmation email provider is slow; with the Before design every request held a transaction open for the SMTP call, exhausting the database connection pool (Connection Pooling); after the change the request ends at commit and the queue absorbs the provider's latency. This is the typical first win of events and costs one queue worker.
Rules: events are an internal design tool; keep the number of listeners per event small and documented; one database means after-commit dispatch is enough for most side effects.
Modular monolith and multiple databases
Modules (Composing Objects, SRP) talk through events instead of reaching into each other's tables. The Billing module listens to Orders\Events\OrderPlaced; it must not read orders directly. Public events are the module's API: version them, keep them in a Contracts namespace, test them with contract tests. If modules have separate schemas or databases, the transaction no longer spans both: the listener runs in its own transaction, so you now live with eventual consistency between modules, and the outbox starts to matter even inside the monolith when two databases are involved.
Everyday example. Orders publishes OrderPlaced; Inventory listens and decrements its own stock table in its own transaction.
Production example. A modular monolith whose modules each have their own migrations folder and database schema; a CI rule forbids importing another module's models, so the only coupling is its events and read interfaces.
Microservices: events across a network
Everything in the table "domain vs integration" now applies. The domain event stays inside the service; an integration event leaves through an outbox, over a broker (Kafka, RabbitMQ, Redis Streams, NATS, SQS), with at-least-once delivery, so consumers are idempotent, and with a versioned schema (Message Design & Schema Evolution). Dead-letter queues and retries replace the in-process failed(). A multi-step business flow needs a saga, not a chain of hopeful events.
Orders service Broker (topic orders.v1) Billing service Shipping service
1 BEGIN; INSERT order; INSERT outbox(order.placed v1); COMMIT
2 relay reads outbox -----> order.placed {event_id, version:1, order_id, total_cents, corr}
3 -------------------------> dedupe(event_id); create invoice
4 ------------------------------------------------------> dedupe; create shipment
5 <----- invoice.created ------ (its own outbox)
6 all hops log corr=a1 -- one search shows the whole flowEveryday example. Orders announces order.placed; Billing and Shipping each react independently.
Production example. Event-carried state transfer for read models: the catalogue service publishes price.changed with the new price; checkout keeps its own copy, so a catalogue outage does not stop checkout (Fowler's trade: more copies, more resilience).
Distributed data: replicas, caches and multi-region
Events meet replication lag. A listener that reads from a replica right after the event may not see the row yet (Replication & Failover): read from the primary, or carry the needed data in the event. A cache invalidated by an event can be repopulated by a concurrent reader with the old value; invalidate after commit and with a short TTL as a safety net. Across regions, ordering is per partition at best; use per-aggregate sequence numbers and idempotent handlers. Clock skew makes occurred_at untrustworthy for ordering across machines; use the sequence, not the timestamp.
Everyday example. A "profile updated" event that invalidates a cache entry before the replica has applied the update: the next read re-caches the old profile.
Production example. Per-partition ordering on Kafka by keying events with the aggregate id, so all events for one order go to one partition; consumers scale by partitions (Ordering & Partitioning).
Scaling path: 1x, 10x, 100x
| Load | What breaks first | Move |
|---|---|---|
| 1x: one app, tens of events/s | Slow side effect on the request path | Queue the listener, ShouldDispatchAfterCommit |
| 10x: hundreds/s | Queue backlog, duplicate emails, hot rows | More workers, idempotency table, ShouldBeUnique, rate limits, batch jobs |
| 100x: thousands/s | Database as queue, ordering across workers, one slow consumer | Broker with partitions, outbox relay with SKIP LOCKED, consumer groups, backpressure |
| Multi-team | Event contracts change under consumers | Schema registry, versioning, consumer-driven contract tests |
| Multi-region | Cross-region latency, duplicate processing | Regional topics, idempotent consumers, per-key ordering |
Lab: events in Go and Laravel
You run the Go bus, break it on purpose, and read the Laravel wiring. Everything runs offline; PHP is reviewed, not run, in this repository.
Setup (Go).
cd docs/snippets/design/control-and-event-handling/go
gofmt -l . # no output
go vet ./... # clean
go test -race ./bus/ # okStep 1: run the lab. Expected output (the 100 ms delay in send-email keeps the order stable):
go run ./lab
# publish:
# sync reserve-stock order=o-1001 corr=req-7f3a
# publish returned (async listeners still running)
# async send-email order=o-1001 corr=req-7f3a
# shutdown:
# [error hook] slow-report failed: context canceled
# donereserve-stock ran on the caller's goroutine before Publish returned; send-email finished 100 ms later with the same correlation ID; slow-report never ends by itself and was cancelled by Close.
Step 2: make the sync listener fail. Change reserve-stock to return errors.New("out of stock"). Expected: publish failed: reserve-stock: out of stock; the async listeners still start (in this bus every listener sees the event; change Publish to stop at the first sync error if you want a hard stop, and note the trade-off).
Step 3: cancel the caller. In main, cancel the request context before Publish. Expected: publish failed: context canceled. The bus checks the context after each sync listener, and because reserve-stock is registered first, the loop stops before the async listeners are started. Now subscribe the async listeners first and repeat: they start, and because they run on context.WithoutCancel(ctx) they are not affected by the caller's cancellation.
Step 4: prove reentrancy safety. Add a sync listener for order.placed that publishes a second event name from inside the handler. Expected: it works. Now hold b.mu while calling handlers (move the RUnlock after the loop): the same program deadlocks as soon as a handler calls Subscribe (a write lock), and a nested Publish can deadlock whenever another goroutine is waiting for the write lock. That is why the list is copied and the lock released first.
Step 5: dedupe. go run ./idempotent. Expected: e1 applied, e3 applied, e2 ignored (stale), second e3 ignored (duplicate); final status shipped.
Step 6: graceful shutdown. RUN=1 go run ./server in one terminal; curl -m 10 localhost:8080/slow in another (returns 504 after 2 s); press Ctrl-C while a request is in flight. Expected: the process waits for the in-flight request, then logs bye.
Step 7 (Laravel, read and reason). In PlaceOrder, remove ShouldDispatchAfterCommit from OrderPlaced and use database queue with a fast worker. Expected failure mode: now and then ModelNotFoundException in SendOrderConfirmation because the worker ran before COMMIT. Restore the interface; the failure disappears. Then run the test class: php artisan test --filter=PlaceOrderTest expects three passing tests.
Common misconceptions
| Belief | Reality |
|---|---|
| Event-driven means asynchronous | No: "There's no need for event processing to be asynchronous" (Fowler); Laravel and Go handlers are sync by default |
| Event-driven means microservices and a broker | An event is a design idea; Laravel calls its events "a simple observer pattern implementation" |
| Events decouple everything | They hide code coupling; data, order and transaction coupling stay |
Event::fake() tests my listener | It prevents listeners from running; it tests the publisher |
| After-commit dispatch means events cannot be lost | A crash between COMMIT and dispatch loses the event; use an outbox |
| My queue delivers exactly once | Plan for at-least-once; make handlers idempotent |
| A timeout stops the work | Only if the callee honours the cancellation signal |
| IoC is dependency injection | DI is one technique; IoC is the whole reversal of who calls whom |
| An event loop is always faster than threads | Only for I/O-bound work with short handlers; a blocking call stalls everyone |
| Observer, pub/sub and event bus are the same | They differ in who holds the subscriber list and who knows whom |
| CQRS needs event sourcing | "Strictly CQRS isn't really about events" (Fowler) |
| Publishing my internal event on the broker is fine | It turns a private model into a public contract; translate to an integration event |
Cheat sheet
| Topic | What to remember |
|---|---|
| Control style | Who decides what runs next: caller, event, value change, state, environment |
| IoC | Library: you call it; framework: it calls you; keep business rules out of the shell |
| Event naming | Past tense, business fact: OrderPlaced; commands are imperative |
| Event payload | Ids and facts, event_id, occurred_at, schema version, no live models |
| Sync vs async | Sync for what must be atomic; async for the rest, with a "processing" state |
| Four meanings | Notification, state transfer, sourcing, CQRS: name which one per event |
| After commit | ShouldDispatchAfterCommit (event), ShouldQueueAfterCommit (listener), ShouldHandleEventsAfterCommit (observer) |
| No-loss | Outbox row in the same transaction, relay, idempotent consumers |
| Idempotency | Unique (listener, event_id) plus a version check |
| Cancellation | ctx first parameter, defer cancel(), signal.NotifyContext, Server.Shutdown |
| Reentrancy | Never hold a lock while calling handlers; draw the event graph; saveQuietly() |
| Errors | #[Tries], #[Backoff], failed(), dead-letter, alert |
| Testing | Event::fake() for publishers, call handle() for listeners, assertListening for wiring |
| Observability | Correlation ID at the edge, in context, in logs, in events |
| Execution model | Process/thread per request, event loop, goroutine per connection: do not block a loop |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What question decides the control style of a feature? Must-know
Answer
Answer: Who decides what runs next: the caller (call-return), an event with a registered handler (event-driven), a value change (reactive), the current state plus an event (state machine) or the environment (interrupt). See Everything in one minute.
2 — Why is "event-driven" not the same as "asynchronous"? Must-know
Answer
Answer: Event-driven is about who triggers the code (a published fact), not when it finishes. A sync listener runs inside dispatch(). Fowler: "There's no need for event processing to be asynchronous." See Sync vs async.
3 — What is the Hollywood principle and where does it show in Go and Laravel? Important
Answer
Answer: "Don't call us, we'll call you": the framework owns control and calls your code. In Go, http.HandleFunc then ListenAndServe; in Laravel, listeners, controllers and middleware. See Inversion of control.
4 — Name Fowler's four meanings of event-driven and say which one does not need events. Good to know
Answer
Answer: Event notification, event-carried state transfer, event sourcing, CQRS. CQRS: "Strictly CQRS isn't really about events". See Four meanings.
5 — Why does a queued listener sometimes throw "model not found", and how do you fix it in Laravel 13? Important
Answer
Answer: The event was dispatched inside a transaction and the worker ran before COMMIT. Implement ShouldDispatchAfterCommit on the event (or ShouldQueueAfterCommit on the listener, or set after_commit on the queue connection). See Transactional boundary.
6 — After-commit dispatch is on. Can an event still be lost? How do you stop that? Important
Answer
Answer: Yes: the process can crash between COMMIT and the dispatch. Write an outbox row in the same transaction and publish it with a relay; accept duplicates and make consumers idempotent.
7 — How do you make a handler safe against duplicates and reordering? Must-know
Answer
Answer: Dedupe on a unique (listener, event_id) key and ignore events whose version is not newer than the applied one. See go/idempotent.
8 — Why does Event::fake() not test a listener, and what does? Must-know
Answer
Answer: After Event::fake() listeners are not executed. Test the listener by calling handle() with an event, and test the wiring with Event::assertListening.
9 — In Go, why does the bus copy the subscriber list before calling handlers? Important
Answer
Answer: So the lock is not held while handlers run. A handler may publish again or subscribe; holding the lock would deadlock. See Reentrancy.
10 — What does context.WithoutCancel give the async listener, and why does the bus also use context.AfterFunc? Good to know
Answer
Answer: It keeps the caller's values (the correlation ID) but not its cancellation, so the listener outlives a finished request. AfterFunc ties the handler to the bus's own shutdown so Close can still cancel it.
11 — Why is a node event loop bad at CPU-heavy handlers while Go is not? Important
Answer
Answer: The loop runs one callback to completion at a time on one thread, so a long computation delays every connection. Go schedules goroutines across GOMAXPROCS OS threads, so other goroutines keep running.
12 — What is the difference between a domain event and an integration event? Must-know
Answer
Answer: A domain event is internal to one bounded context and may be rich and change freely; an integration event crosses a service boundary and is a versioned public contract delivered at-least-once. See Domain vs integration.
Glossary
| Term | Meaning |
|---|---|
| Control flow | The order in which a program's operations run |
| Call-return | Control style where the caller invokes a callee and waits for its return |
| Event-driven design | Design where components invoke operations in reaction to events (SWEBOK 5.7) |
| Indirect (implicit) invocation | Calling code without naming it: the dispatcher finds the handler |
| Reactive / dataflow | Style where changed values propagate to dependent values |
| State machine | States, events and a transition function from (state, event) to state |
| Interrupt | Asynchronous signal from the environment that preempts or wakes current work |
| Signal (SIGTERM, SIGINT) | OS notification to a process; SIGTERM asks it to stop |
| Inversion of control (IoC) | A framework, not your code, owns the flow and calls your code |
| Hollywood principle | "Don't call us, we'll call you"; another name for IoC |
| Dependency injection | Technique where a container supplies a component's dependencies |
| Event loop | Single thread that waits for readiness and runs callbacks to completion |
epoll / kqueue | Linux / BSD-macOS kernel facilities to wait on many descriptors |
| netpoller | Go runtime component that parks and wakes goroutines on I/O readiness |
| Thread/process per request | One OS worker owns each request until done (PHP-FPM, servlet) |
| Goroutine per connection | net/http model: one cheap goroutine per accepted connection |
| Observer | Pattern where a subject notifies the observers it holds |
| Publish/subscribe | Publishers and subscribers meet through a channel or broker, without knowing each other |
| Event bus | In-process publish/subscribe dispatcher |
| Event queue | Queue where events wait until a consumer takes them |
| Event | A fact about something that already happened, named in the past tense |
| Command | A request to do something; imperative, may be refused |
| Domain event | Event inside one bounded context |
| Integration event | Versioned event that crosses a service boundary |
| Event notification | Event with minimal data; receiver calls back for details |
| Event-carried state transfer | Event carrying the changed data so receivers keep their own copy |
| Event sourcing | Storing every state change as an event; state is derived from the log |
| CQRS | Separate models for writing and reading; not inherently about events |
| Passive-aggressive command | A command disguised as an event |
| Idempotent handler | Handler whose repeated application has the effect of one |
| Reentrancy | A handler invoked again while its first run is still in progress |
| Correlation ID | Identifier carried through every hop of one request |
ShouldDispatchAfterCommit | Laravel event interface: dispatch only after the transaction commits |
ShouldQueueAfterCommit | Laravel listener interface: push to the queue after commit |
ShouldHandleEventsAfterCommit | Laravel observer interface: handle model events after commit |
context.Context | Go carrier of deadlines, cancellation and request-scoped values |
signal.NotifyContext | Go helper that cancels a context on OS signals |
| Outbox | Table written in the same transaction as the state change and published by a relay |
| Dead-letter queue | Holding place for messages that keep failing |
| Backpressure | Slowing producers when consumers cannot keep up |
References
- SWEBOK v4.0, Software Design KA (sections 3.2 and 5.7), IEEE Computer Society. PDF
- Martin Fowler, Inversion Of Control, 2005
- Martin Fowler, What do you mean by "Event-Driven"?, 2017
- Martin Fowler, Event Sourcing and Domain Event (draft patterns, 2005); CQRS; Event Collaboration
- Refactoring.guru, Observer and State
- Hohpe and Woolf, Enterprise Integration Patterns: Publish-Subscribe Channel, Event Message, Idempotent Receiver
- Chris Richardson, Transactional outbox
- The Reactive Manifesto, v2.0, 2014
- Linux man-pages, epoll(7); FreeBSD kqueue(2); Linux kernel docs, Linux generic IRQ handling
- Node.js, The Node.js Event Loop; MDN, The event loop
- Go: package context, package os/signal, package net/http, language specification: select statements, Go Concurrency Patterns: Pipelines and cancellation, Go Concurrency Patterns: Context, Effective Go, runtime netpoll_epoll.go
- PHP: Fibers
- Laravel 13: Events, Queues, Broadcasting, Eloquent: Observers, Context, Mocking (Event fake), Octane
- Sibling chapters: Designing for Concurrency, Behavioral Patterns, Error & Exception Handling, Data Persistence in Design, Distribution of Components, Interaction & Presentation, DIP, OCP, SRP; messaging: Outbox, DLQ, Message Design, Idempotent Consumers, Ordering, EDA, Event Sourcing & CQRS, Delivery Guarantees