Data Patterns: Shared Database, Database per Service, CQS → CQRS, Read-Side Replication
"At its heart is the notion that you can use a different model to update information than the model you use to read information. For some situations, this separation can be valuable, but beware that for most systems CQRS adds risky complexity." — Martin Fowler, CQRS (bliki, 14 July 2011)
Summary: Once every context owns its data there are no joins and no transactions across services, so reads that span contexts need a deliberate pattern: compose at query time, or keep a read model fed by the owners' events; CQS at the method level grows into CQRS at the model level, and each step right on that spectrum buys read independence at the price of lag and machinery. Focus: The data problem in microservices, shared database and its few acceptable transitional uses, database per service (instance, schema, private tables, polyglot persistence), Meyer's CQS in Go and Laravel, CQRS from two objects to separate stores (synchronous vs asynchronous projection, when it is not worth it), read models and projections (denormalised, per screen, rebuildable, versioned, idempotent, catch-up and rebuild), read-side replication options (replicas, logical replication, CDC with Debezium, event-driven projections, materialized views), API composition vs read model, read-your-writes (version token, wait-for-projection, sticky reads, UI optimism), eventual-consistency failures, reporting, task-based UIs, event sourcing as a write-side option, testing and observing projections. Learning goal: Given a screen that needs data from Sales, Fulfilment and Billing, choose between API composition and a read model, then build the OrderSummary projection in Go and Laravel so that it survives duplicates, out-of-order events and a full rebuild, returns read-your-writes with a version token, and exposes its lag as a metric.
This chapter opens group DD 03 (Data & APIs in Microservices). It assumes the tactical chapters: an aggregate is the unit of consistency (Aggregates & Factories), it is saved through a repository (Repositories), and it publishes facts that other contexts consume (Domain Events vs Integration Events). The decision of who owns which tables and how to carve data out of a monolith belongs to Data Ownership in Microservices; this page takes that decision as given and shows the data patterns a developer implements on top of it. The plumbing has its own pages: the outbox table and relay (Outbox), log-based capture (Change Data Capture), event stores and replay (Event Sourcing & CQRS), dedup tables (Idempotent Consumer & Inbox), cross-service writes (Saga), and the consistency models themselves (Eventual Consistency in Databases, Replication & Failover). Where the service lines are drawn is Service Boundaries; how services call each other (timeouts, retries, idempotency keys) is Service Communication; events vs commands and event-carried state transfer are Event-Driven Architecture; and mapping one aggregate to tables, ORMs and transactions is Data Persistence Design.
The running example is the one used across the DDD path: an online ordering and fulfilment business with the Sales, Fulfilment, Billing, Catalog and Identity contexts. Sales owns the Order aggregate. The customer's "My orders" screen and the support tool both need one row per order that shows what Sales knows (total, lines), what Fulfilment knows (dispatched, carrier, tracking) and what Billing knows (paid). That row is the OrderSummary read model, fed by OrderPlaced (Sales), ParcelDispatched (Fulfilment) and InvoicePaid (Billing).
Page map
| If you are looking for | Go to |
|---|---|
| The page in three tables | Everything in one minute |
| Why "just join the tables" stops working | Why data patterns exist |
| Meyer 1988 to Young 2010 to microservices.io | Where it comes from |
| No joins, no distributed transactions | The data problem |
| One database for all services, and when it is tolerable | Shared database |
| Instance, schema or private tables; polyglot persistence | Database per service |
| Commands return nothing, queries change nothing | CQS |
| Separate write and read models; the spectrum | CQRS |
| Projections: per screen, rebuildable, idempotent | Read models and projections |
| Replicas, logical replication, CDC, events, materialized views | Read-side replication options |
| Ask the owners at query time or keep a copy | API composition vs read model |
| "I placed the order and it is not in my list" | Read-your-writes |
| Stale lists, phantom deletes, missing parents | Eventual-consistency failures |
| Finance wants everything | Reporting and analytics |
| Commands as intents, not PUT | Task-based UIs |
| Events as the write model | Event sourcing as an option |
| Replay fixtures, snapshot tests, lag metrics | Testing, Observability |
| Schema, algorithm, rebuild, knobs, errors, products | Mechanics |
| Full code | Go, Laravel |
| Six classic problems | Solving the classic problems |
| Which pattern for which query | Choosing |
| Monolith to distributed data | In architecture |
| Hands-on | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked in the concept catalogue.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Shared database | Several services read and write the same tables | Sales and Billing both UPDATE orders | Nobody can change a column alone; locks cross teams |
| Database per service | Each service's data is private, reachable only through its API or events | Billing's invoices has one writer and no foreign readers | Hidden coupling through tables |
| CQS | A method either changes state or returns data, not both | Dispatch() error and Status() Status | Reads with side effects; "just looking" changes data |
| CQRS | Separate objects (then models, then stores) for writes and reads | PlaceOrderHandler vs OrderSummary | One model bent to serve both screens and rules |
| Read model | A copy shaped for one screen or query | order_summary: one row per order | N joins or N service calls per page |
| Projection / projector | The code that turns events into read-model rows | ParcelDispatched sets dispatched_at, carrier | Read model drifts from the facts |
| Projection lag | How far the read model is behind the write side | Order placed 300 ms ago, not yet listed | Users repeat actions; support tickets |
| Read-your-writes | After my change, my next read shows it | Return version: 1; read with min_version=1 | "Did my order go through?" |
| API composition | Query the owners and join in memory | BFF calls Sales, then Fulfilment | Slow, fragile pages for big joins |
The CQS → CQRS spectrum (drawn in CQRS):
| Step | What is separated | Store | Consistency of reads | Cost |
|---|---|---|---|---|
| 1 CQS | Methods | One model, one DB | Immediate | Free: a coding rule |
| 2 CQRS, two objects | Command service vs query service | Same tables, thin read layer | Immediate | Low |
| 3 Read tables, same DB | Read schema | Same DB, projected in the same transaction | Immediate | Slower writes |
| 4 Separate read store | Read storage | Other DB, index or cache, async projector | Eventual (lag) | Projector, replay, lag monitoring |
| 5 Event-sourced write side | Write storage too | Event store + projections | Eventual for reads | Highest; new skills |
Ways to get data to the read side (compared in Read-side replication options):
| Option | Ownership respected? | Typical lag | Shape of copy |
|---|---|---|---|
| Read replica of the owner's DB | Only if the replica is the owner's own | ms to s | Same schema as the owner |
| Logical replication of selected tables | Yes, if the owner publishes a documented table | ms to s | Selected tables, columns, rows |
| CDC (Debezium) into a read store | Yes, through an outbox or published table | ms to s | Row-change events, reshaped by a consumer |
| Event-driven projection | Yes: events are the contract | ms to s | Anything the screen needs |
| Materialized view | Only inside one DB (modular monolith) | Until the next REFRESH | A query result stored as a table |
Why data patterns exist
Inside one database a screen that needs orders, shipments and invoices is a three-way JOIN, and a change that touches two of them is one transaction. Split the system into services that each own their data and both tools disappear: Sales cannot JOIN fulfilment.shipments without reading another service's private tables, and it cannot COMMIT a change in Billing. Richardson's Database per Service lists exactly these drawbacks: "Implementing business transactions that span multiple services is not straightforward" and "Implementing queries that join data that is now in multiple databases is challenging." Writes across services are a saga's job (Saga). This chapter is mostly about the other half: reads that span owners, and about how the write side and read side of one context relate (CQS and CQRS).
| Keep one model and one database | Separate write and read sides |
|---|---|
| Every read is fresh | Reads can lag behind writes |
| One model must serve rules and screens | The write model only protects rules; read models only serve screens |
| Joins across contexts reach into others' tables | Each read model holds its own copy, fed by events |
| Simple to build, test and debug | Projector, replay, lag metric, rebuild tooling |
| Fits most CRUD-shaped contexts | Fits a few contexts with heavy, varied reads or complex rules |
The analogy we reuse on this page: a hospital. Each department keeps its own records: the pharmacy its dispensing log, the lab its results, the ward its charts. Nobody from the lab writes in the pharmacy's book (database per service). The doctor on the ward does not walk to three departments for every patient (API composition); a nurse keeps a whiteboard at the ward desk with one line per patient, updated whenever a department phones up a result (a projection into a read model). The whiteboard can be a few minutes behind and it can be wiped and rewritten from the departments' call log (rebuild). The department records decide what is true; the whiteboard is only for looking.
Three common misunderstandings, up front
- "CQRS means two databases and Kafka." Greg Young: "CQRS is simply the creation of two objects where there was previously only one." Separate stores, events and eventual consistency are options around it, not the pattern itself.
- "Database per service means one database server per service." Richardson lists private tables per service, schema per service and database server per service; the first two "have the lowest overhead". The rule is private, not physically separate.
- "A read model is a cache." A cache is filled on demand from the same model and expires. A read model is a different, denormalised shape, filled by events, owned by the reader, and rebuildable from a log; it never expires and is never read-through.
Where it comes from
Meyer, 1988. Bertrand Meyer's Object-Oriented Software Construction introduced command-query separation. We did not read the book; we take the principle from Fowler's 2005 summary: "Queries: Return a result and do not change the observable state of the system (are free of side effects). Commands: Change the state of a system but do not return a value." Fowler adds the exception he keeps: "Popping a stack is a good example of a query that modifies state."
Reporting databases. Fowler's ReportingDatabase (dated 2 April 2014 on the bliki) describes the older idea that read-heavy reporting deserves "a completely different database to the operational database": "You don't need to normalize a reporting database, because it's read-only."
Young, 2010. Greg Young's CQRS Documents (PDF, cqrsinfo.com) and his February 2010 post CQRS, Task Based UIs, Event Sourcing agh! named Command and Query Responsibility Segregation. The documents trace it to Meyer and explain why one model fails: "It is not possible to create an optimal solution for searching, reporting, and processing transactions utilizing a single model." The post narrows it on purpose: "CQRS is not eventual consistency, it is not eventing, it is not messaging, it is not having separated models for reading and writing, nor is it using event sourcing."
Fowler, 2011. The bliki entry CQRS (14 July 2011) gave the mainstream definition and the warning: "In particular CQRS should only be used on specific portions of a system (a BoundedContext in DDD lingo) and not the system as a whole."
Vernon, 2013; Khononov, 2021. Vaughn Vernon's Implementing Domain-Driven Design treats CQRS in chapter 4 (Architecture) next to event-driven architecture and event sourcing; Vlad Khononov's Learning Domain-Driven Design places CQRS among the architectural patterns and pairs it with polyglot persistence (several read stores per write model). We did not have the books' text; we summarise their placement, not their wording.
microservices.io. Chris Richardson's catalogue made the data patterns the core of microservices: Database per Service, Shared Database, API Composition, CQRS ("Define a view database, which is a read-only ‘replica’ that is designed specifically to support that query"), Event Sourcing and Saga.
Change data capture and logical replication. PostgreSQL added built-in "Logical replication using publish/subscribe" in version 10 (release date 2017-10-05 in the release notes); Debezium turned the database log into a stream of row-change events for Kafka Connect. Both became standard ways to feed read stores without hand-written events (the PostgreSQL pages we quote are the current, version 19, docs).
Year Idea What it changed for reads
1 1988 Meyer: command-query separation Methods either change or answer
2 2005 Fowler's CQS summary, pop() exception The rule meets practice
3 2010 Young: CQRS, task-based UI, thin read layer Two objects, then two models
4 2011 Fowler: CQRS, "specific portions" only CQRS is per bounded context
5 2013 Vernon IDDD ch. 4 CQRS inside DDD architecture
6 2014+ microservices.io data patterns View databases fed by events
7 2017 PostgreSQL 10 logical replication Table-level copies across DBs
8 later Debezium CDC on Kafka Connect The log becomes an event streamThe concept catalogue
Each block follows the same order: plain words, the usual misunderstanding, the definition, a timeline, real scenarios, a comparison, and how to do it in SQL, Go and Laravel. Full code is in Go and Laravel.
The data problem in microservices Must-know
In plain words: when each service keeps its own data, the database can no longer join across services or wrap a change to two of them in one transaction; the application has to do both jobs, and it can only do them more slowly and less strictly.
Common misunderstanding: "We will just call the other service inside our transaction." A remote call inside BEGIN … COMMIT is not part of the transaction: if the commit fails after the call succeeded, the other service has already acted, and while you wait for it you hold locks.
Definition: with private data per service, (1) queries that need data from several owners must be implemented by API composition or by a read model, and (2) business transactions that change several owners must be implemented as sagas of local transactions with compensations. Two-phase commit (2PC) across services is avoided: Richardson notes "Distributed transactions are best avoided because of the CAP theorem. Moreover, many modern (NoSQL) databases don’t support them."
Monolith (one DB) Services (three DBs)
1 SELECT o.*, s.carrier, i.paid_at Sales DB has orders, Fulfilment DB shipments,
2 FROM orders o JOIN shipments s ... JOIN invoices i Billing DB invoices: no JOIN reaches all three
3 BEGIN; UPDATE orders ...; UPDATE invoices ...; COMMIT; Sales COMMIT; publish OrderPlaced -> Billing COMMIT later
4 -> one answer, one atomic change -> compose or project; saga; eventual consistencyReal scenario: the "My orders" list (data from Sales, Fulfilment, Billing); a support search by tracking number (Fulfilment data, Sales display); "cancel an order and refund it" (Sales and Billing writes); a finance month-end report (everything).
| Need | In a monolith | Across services | Pattern on this page or a sibling |
|---|---|---|---|
| Join for one record | JOIN | Call each owner, join in memory | API composition |
| Join, filter, sort, page many records | JOIN … WHERE … ORDER BY … LIMIT | Local copy shaped for the query | Read model |
| Change two owners atomically | One transaction | Saga of local transactions | Saga |
| Publish a change reliably | Not needed | Outbox in the same local transaction | Outbox |
| Analytics over everything | Reporting queries on the OLTP DB (bad already) | Warehouse fed by CDC or batch | Reporting |
Fix / how to use it: accept the two rules early. In Go and Laravel this shows up as a code-review rule: a repository or Eloquent model may only touch tables of its own context, and any SQL that names another context's schema is rejected (the Data Ownership chapter enforces it with database roles).
-- The query that must disappear from Sales' code once the contexts are split:
SELECT o.id, o.total_minor, s.carrier, i.paid_at
FROM sales.orders o
LEFT JOIN fulfilment.shipments s ON s.order_id = o.id -- Fulfilment's private table
LEFT JOIN billing.invoices i ON i.order_id = o.id -- Billing's private table
WHERE o.customer_id = $1;Shared database Must-know
In plain words: several services read and write the same tables; the database does the joins and the transactions for them, and in exchange every table becomes a contract nobody owns.
Common misunderstanding: "It is fine as long as each service only reads the other's tables." Reads couple too: the reader breaks when the owner renames a column, and a long reporting query can hold locks or bloat the owner's tables.
Definition: Richardson's Shared database pattern: "Each service freely accesses data owned by other services using local ACID transactions." Benefit: "A developer uses familiar and straightforward ACID transactions to enforce data consistency." Drawbacks: "Development time coupling - a developer working on, for example, the OrderService will need to coordinate schema changes with the developers of other services that access the same tables", and "Runtime coupling - because all services access the same database they can potentially interfere with one another."
Sales service Billing service (same database)
1 ALTER TABLE orders RENAME total TO total_minor; -- deployed Tuesday 10:00
2 SELECT total FROM orders WHERE id = $1;
3 ERROR: column "total" does not exist -- invoices stop
4 Monthly report in Billing: SELECT ... FROM orders (12 min, long snapshot)
5 UPDATE orders SET status = 'paid' ... -- waits / dead tuples pile up behind the reportReal scenario: a renamed column breaking another team's job at night; two services both writing orders.status with different meanings; a reporting query slowing checkout; a schema migration that needs three teams in one meeting.
| Use of a shared database | Acceptable? | Condition |
|---|---|---|
| Two services writing the same table | No | Pick one owner (single writer) |
| Reading another service's internal tables | No | Use its API, its events, or a published table |
| One physical server, separate schemas and credentials | Yes | This is database per service with low overhead |
| Transitional: the monolith still writes, the new service reads through a view owned by the monolith | Yes, temporarily | Dated plan to remove; view is a contract |
| Transitional: a published, insert-only "integration table" replicated or CDC-captured | Yes | Documented schema, versioned like an event |
| A modular monolith with module-owned schemas | Yes | Modules never touch each other's tables |
Fix / how to use it: if you must share during a migration, share a contract, not tables: a view or an insert-only table the owner maintains, read by a role that can read nothing else (details and brownfield moves in Data Ownership).
-- Owner-maintained contract: Billing reads this view, never sales.orders.
CREATE VIEW sales_public.orders_v1 AS
SELECT id AS order_id, customer_id, total_minor, currency, placed_at FROM sales.orders;
GRANT SELECT ON sales_public.orders_v1 TO billing_reader;Database per service Must-know
In plain words: each service's data is private to it; others get it only through the service's API or the events it publishes. "Database" means "the set of data only this service may touch", not necessarily a separate server.
Common misunderstanding: "Database per service forbids running two services on one PostgreSQL server." Richardson: "You do not need to provision a database server for each service." What is forbidden is another service reaching into the tables.
Definition: "Keep each microservice’s persistent data private to that service and accessible only via its API. A service’s transactions only involve its database." The three granularities, all from the pattern page: "Private-tables-per-service – each service owns a set of tables that must only be accessed by that service", "Schema-per-service – each service has a database schema that’s private to that service", and "Database-server-per-service – each service has it’s own database server." The first two "have the lowest overhead"; schema per service "makes ownership clearer". Private data also allows polyglot persistence: each service picks the store that fits its access pattern (the page mentions MongoDB for "complex, unstructured data" and Neo4J for graph data).
Granularity What is separate Enforcement
1 private tables naming convention only code review, architecture tests
2 schema per service schema + role + credentials GRANT/REVOKE: other roles get "permission denied"
3 server per service instance, backups, scaling network + credentials
-> each step up costs more to run and removes one more way to cheatReal scenario: Sales and Billing as two schemas on one managed PostgreSQL (cheap, clear ownership); Catalog moved to its own server because search traffic dwarfs everything else; Fulfilment's route optimiser using a graph store; the OrderSummary read side using PostgreSQL for the table and a search engine for free-text search (polyglot persistence on the read side).
| Granularity | Cost | Isolation of load | Blocks cross-service SQL? | Good for |
|---|---|---|---|---|
| Private tables | Lowest | None | No (convention) | Modular monolith, early services |
| Schema per service | Low | None (same instance) | Yes, with roles | Most teams' default |
| Database per service (logical DB) | Low to medium | None (same instance) | Yes (\c needed) | Strong isolation, same ops |
| Server per service | Highest | Full | Yes | Very high throughput, different engines |
Fix / how to use it: one schema and one login role per context, with the role's search_path set to its own schema, plus a test that fails if any context's SQL names another schema.
CREATE SCHEMA sales; CREATE ROLE sales_svc LOGIN; GRANT USAGE, CREATE ON SCHEMA sales TO sales_svc;
CREATE SCHEMA billing; CREATE ROLE billing_svc LOGIN; GRANT USAGE, CREATE ON SCHEMA billing TO billing_svc;
ALTER ROLE sales_svc SET search_path = sales;
-- billing_svc: SELECT * FROM sales.orders; -> ERROR: permission denied for schema sales (SQLSTATE 42501)// config/database.php: one connection per owner (Laravel). Sales models use 'sales'.
'sales' => [...$pg, 'search_path' => 'sales', 'username' => env('SALES_DB_USER')],
'read_model' => [...$pg, 'search_path' => 'read_model', 'username' => env('READ_DB_USER')],CQS: commands and queries at the method level Must-know
In plain words: a method either does something (a command) or tells you something (a query), never both. Asking a question must not change the answer.
Common misunderstanding: "A command must return void, so returning an error or an id breaks CQS." Fowler's summary says commands "do not return a value", but the point is observable state: returning a failure (Go's error, a PHP exception) carries no data about the object. Returning the new version as a consistency token is a pragmatic, widely used deviation; returning the whole updated record is where CQS is really lost.
Definition: Meyer's command-query separation, as summarised by Fowler: "Queries: Return a result and do not change the observable state of the system (are free of side effects). Commands: Change the state of a system but do not return a value." Young's documents add the CQRS reading: "If you have a return value you cannot mutate state. If you mutate state your return type must be void." Known exceptions: pop(), iterators' next(), atomic "dequeue and return" operations.
Caller Order (CQS) Order (violates CQS)
1 o.CanDispatch() -> true, nothing changed NextShipmentAndMark() -> "o-1", status=picking
2 o.CanDispatch() (dashboard poll) -> true, nothing changed NextShipmentAndMark() -> "o-2", status=picking
3 o.Dispatch() -> nil, status=dispatched, version 3 the dashboard "looked" and moved two ordersReal scenario: a dashboard polling "next order to pick" and moving orders as a side effect; a getter that lazily recalculates and saves totals; an Eloquent accessor that writes; a repository find() that also bumps a "last viewed" column on the aggregate (move it to an event or a separate command).
| Method shape | CQS? | Comment |
|---|---|---|
func (o *Order) Dispatch() error | Yes | Command; error is not state |
func (o *Order) Status() Status | Yes | Query; safe to call anywhere, any order |
func (h Handler) Handle(cmd) (Ack, error) with Ack{Version} | Pragmatic | Token for read-your-writes, no read data |
public function dispatch(): Order returning $this | Grey | Fluent style; fine if nothing else is returned |
UPDATE … RETURNING * behind a "get next" method | No | Query with side effects |
Stack.pop() | No, accepted | Fowler: "I'm prepared to break it to get my pop" |
Fix / how to use it: in the domain model, make commands return only error (Go) or void with exceptions (PHP); make queries side-effect free; move "dequeue and mark" into an explicitly named command.
func (o *Order) Dispatch() error { // COMMAND
if o.status != Paid {
return ErrNotPaid
}
o.status, o.version = Dispatched, o.version+1
return nil
}
func (o *Order) CanDispatch() bool { return o.status == Paid } // QUERYpublic function dispatch(): void // command
{
if (! $this->canDispatch()) {
throw new DomainException('An unpaid order cannot be dispatched.');
}
$this->status = 'dispatched';
$this->version++;
}
public function canDispatch(): bool { return $this->status === 'paid'; } // queryCQRS: separate write and read models Must-know
In plain words: take the commands and the queries that used to live on one object and put them on two; once they are apart, the read side is free to use a different model, then different tables, then a different store, as far as the problem needs and no further.
Common misunderstanding: "CQRS requires event sourcing, a message broker and eventual consistency." Young: "CQRS is not eventual consistency, it is not eventing, it is not messaging, it is not having separated models for reading and writing, nor is it using event sourcing." Each of those is a separate decision you may make after splitting.
Definition: Young: "CQRS is simply the creation of two objects where there was previously only one. The separation occurs based upon whether the methods are a command or a query." His example splits CustomerService into CustomerWriteService and CustomerReadService. Fowler describes the full form: "split that conceptual model into separate models for update and display", where "The in-memory models may share the same database, in which case the database acts as the communication between the two models. However they may also use separate databases, effectively making the query-side's database into a real-time ReportingDatabase." The command side keeps the domain model and aggregates; the query side becomes a thin read layer that "reads directly from the database and projects DTOs" (Young).
The picture is the spectrum from the one-minute table: every step to the right separates one more thing and costs one more piece of machinery. Steps 1 to 3 keep reads immediately consistent; step 4 introduces lag; step 5 changes the write side too.
Synchronous vs asynchronous projection. At step 3 the read table is updated in the same transaction as the aggregate: no lag, but every write pays for every read model, and the read model can only live in the same database. At step 4 a projector updates the read store after commit, from events (or CDC): writes stay fast and the read store can be anything, but reads lag.
Synchronous (step 3) Asynchronous (step 4)
1 BEGIN BEGIN
2 UPDATE sales.orders SET ... version = 2 UPDATE sales.orders SET ... version = 2
3 UPDATE read.order_summary SET ... (same tx) INSERT INTO sales_outbox (OrderPaid ...)
4 COMMIT -> list shows the change at once COMMIT -> 202 {version: 2}
5 relay -> broker -> projector (50-500 ms)
6 UPDATE order_summary ... -> list shows it nowWhen it is not worth it. Fowler: "Many systems do fit a CRUD mental model, and so should be done in that style." "Usually there's enough overlap between the command and query sides that sharing a model is easier. Using CQRS on a domain that doesn't match it will add complexity, thus reducing productivity and increasing risk." He sees benefit in two directions: complex domains and "high performance applications" with very different read and write loads; and if only some queries are heavy, "you can still use a ReportingDatabase".
Real scenario: Sales' order screen needs data from three contexts and paging by date (step 4 justified); Identity's user admin is CRUD (step 1 is enough); Catalog search needs a search engine (step 4 into a search index); a ledger whose auditors want the history of every change (step 5 may be justified, see event sourcing).
| Context in the running example | Read needs | Step chosen | Why |
|---|---|---|---|
| Identity (users, roles) | Admin lists | 1 (CQS only) | CRUD-shaped; Fowler's warning applies |
| Catalog (products) | Free-text search, facets | 4: search index fed by events | Search engines answer what SQL cannot |
| Sales (orders) | "My orders" with Fulfilment and Billing facts | 4: OrderSummary read model | Cross-owner data, paging, high read ratio |
| Billing (invoices, payments) | Audit trail, statements | 2 or 3; 5 only if audit demands it | Strong consistency matters more than read scale |
| Fulfilment (shipments) | Warehouse pick lists | 3: read table in the same DB | Needs fresh data, single owner |
Fix / how to use it: split the application service first (step 2): commands go through handlers that load aggregates; queries go through a read service that runs SQL and returns DTOs, never aggregates. Move right only when a measured need appears.
// Step 2 in Go: two objects over the same tables.
type OrderCommands struct{ Repo sales.Repository } // Place, Pay, Ship
type OrderQueries struct{ DB *pgxpool.Pool } // thin read layer
func (q OrderQueries) ByCustomer(ctx context.Context, customerID string) ([]OrderRow, error) { /* SELECT ... */ return nil, nil }// Step 2 in Laravel: an action for each command, a query class for reads.
final class PlaceOrderAction { public function __invoke(PlaceOrder $cmd): int { /* ... */ } }
final class OrderQueries { public function byCustomer(string $id): Collection { return DB::table('order_summary')->where('customer_id', $id)->get(); } }Read models and projections Must-know
In plain words: a read model is a table (or index, or document) built for one screen or one family of queries; a projector keeps it up to date by applying events to it, one at a time, safely enough that duplicates, reordering and a full replay all end in the same rows.
Common misunderstanding: "The read model should be normalised like the write model, so it is reusable." Young: the query side "would want data in a denormalized way to minimize the number of joins needed". A read model that tries to serve every screen becomes a second write model.
Definition: a read model (view model, query model, projection) is a denormalised, query-shaped copy owned by the reader. A projection is the function from an ordered stream of events to that copy; a projector (projection handler) is the code that runs it. Properties a production read model needs:
- Per screen or query family: one row per order for "My orders", not a generic order graph.
- Idempotent updates: delivery is at-least-once, so applying the same event twice must change nothing; we record the event id in the same transaction as the row update.
- Order-tolerant: events from different contexts arrive in any order; each event writes only the columns its context owns, the row is upserted, and Sales' columns are guarded by the Sales version.
- Rebuildable: the read model can be deleted and recreated from a log of events (a replay); the projector keeps that log (
received_events) because other contexts' databases are not ours to re-read. - Versioned: a new shape is built side by side (
order_summary_v2or a rebuild table), caught up, then swapped in. - Catch-up: a new or restarted projector processes the backlog from its last position before serving live traffic.
The picture shows the running example: three owners publish through their outboxes, the broker delivers at least once, the projector writes received_events (dedup and replay log) and order_summary in one transaction, a second projector feeds the search index, and a rebuild replays the log into a fresh table. Analytics take a separate path into a warehouse.
Delivery (at-least-once, any order) order_summary row for o-1 after the step
1 fulfilment.parcel.dispatched.v1 evt-ship-1 + {dispatched_at, carrier=DHL} status=pending
2 fulfilment.parcel.dispatched.v1 evt-ship-1 (dup) unchanged: event id already in received_events
3 sales.order.placed.v1 evt-placed-1 v1 + {customer, total=2500, sales_version=1} status=dispatched
4 billing.invoice.paid.v1 evt-paid-1 + {paid_at, paid_minor=2500} status=completed
5 sales.order.placed.v1 evt-placed-0 v0 ignored: sales_version 0 < 1 (stale)
-> same row as if the events had arrived in the "right" order, exactly onceReal scenario: "My orders" (this page); a support "customer 360" read model fed by five contexts; a warehouse pick list sorted by promised date; a product search index fed by Catalog and Pricing events; a per-customer "lifetime spend" counter (careful: a counter is not naturally idempotent, which is why the dedup table matters).
| Projection technique | Handles duplicates | Handles reordering across sources | Handles reordering within a source | Note |
|---|---|---|---|---|
Plain UPDATE … WHERE id | No | No (row may not exist yet) | No | Silently updates 0 rows |
Upsert of own columns (ON CONFLICT DO UPDATE) | Yes for "set" updates | Yes | No | Counters still double count |
Upsert + version guard (WHERE s.sales_version < EXCLUDED.sales_version) | Yes | Yes | Yes | Needs a version in the event |
Dedup table (received_events UNIQUE event_id) in the same transaction | Yes, always | Combine with upsert | Combine with guard | Also the replay log |
| Derive status from facts present | n/a | Yes | n/a | No "status" column to overwrite |
Fix / how to use it: the core of the Go projector; the full code is in Go, the Laravel listener in Laravel.
func (p *Projector) Handle(ctx context.Context, env contracts.Envelope) error {
patch, err := Decode(env) // unknown types -> nil: forward compatible
if err != nil || patch == nil {
return err
}
applied, err := p.Store.ApplyOnce(ctx, env, patch) // log + upsert, one transaction
if err == nil && applied {
p.Lag.Observe(env.Source, p.Now().Sub(env.Time))
}
return err
}INSERT INTO order_summary AS s (order_id, dispatched_at, carrier, tracking_ref, updated_at)
VALUES ($1, $2, $3, $4, now())
ON CONFLICT (order_id) DO UPDATE SET dispatched_at = EXCLUDED.dispatched_at,
carrier = EXCLUDED.carrier, tracking_ref = EXCLUDED.tracking_ref, updated_at = now();Read-side replication options Important
In plain words: there are five ways to get data from the side that writes it to the side that reads it; they differ in how much they respect ownership, how stale the copy can be, and how much you have to run.
Common misunderstanding: "A read replica is CQRS." A physical replica has the same schema as the primary: it scales reads but gives you neither a different model nor data from other owners. It is a scaling tool, with its own lag (Replication & Failover).
Definition:
- Database read replica: a byte-for-byte (physical) copy of the owner's database, read-only, lagging by milliseconds to seconds. Same schema, same owner.
- Logical replication of selected tables: PostgreSQL's "method of replicating data objects and their changes, based upon their replication identity (usually a primary key)". A publication picks tables, columns ("Each publication can optionally specify which columns of each table are replicated to subscribers") and rows (row filters). "The database schema and DDL commands are not replicated."
- CDC into a read store: Debezium reads the write-ahead log through logical decoding (
plugin.name=pgoutput,wal_level=logical) and emits row-change events (opc,u,d,rfor snapshot reads) to Kafka; a consumer reshapes them into the read store. The Debezium PostgreSQL connector docs: normally exactly once, but "while it is recovering from the fault, it’s possible that the connector might emit some duplicate change events", i.e. at least once. - Event-driven projection: the owner publishes integration events (via an outbox) and the reader projects them. The events are designed contracts, not table rows.
- Materialized view: a stored query result inside one database, refreshed with
REFRESH MATERIALIZED VIEW;CONCURRENTLYrefreshes "without locking out concurrent selects" but requires a unique index.
Owner commits at t=0 When the reader sees it
1 physical replica t + replay lag (ms..s), same schema
2 logical replication (selected tables) t + apply lag (ms..s), selected columns/rows
3 CDC (Debezium -> Kafka -> consumer) t + poll + Kafka + consumer (100 ms..s)
4 outbox -> broker -> projector t + relay interval + broker + projector (ms..s)
5 materialized view at the next REFRESH (minutes, hours)Real scenario: read replicas for Sales' own order history pages; logical replication of Billing's insert-only invoice_payments into the read database; CDC from Catalog's products table into a search index when Catalog cannot publish events yet; event-driven projections for OrderSummary; a materialized view for a nightly "orders per region" table in a modular monolith.
| Option | Respects ownership | Lag | Complexity to run | Copy can be reshaped | Cross-owner joins | Main risk |
|---|---|---|---|---|---|---|
| Read replica | Yes (owner's own replica) | ms to s | Low | No | No | Stale reads after writes |
| Logical replication | Yes, if the owner publishes a contract table | ms to s | Medium | Columns and rows only | Yes, on the subscriber | DDL not replicated; slots retain WAL |
| CDC (Debezium) | Only via an outbox or published table | 100 ms to s | High (Kafka Connect) | Yes, in the consumer | Yes | Couples readers to table shape |
| Event-driven projection | Yes, events are the contract | ms to s | Medium | Yes | Yes | Lag, idempotency, replay source |
| Materialized view | Only within one database | Until refresh | Low | Yes (SQL) | Yes, in one DB | Staleness; full recompute cost |
Fix / how to use it: prefer events for read models across owners; use logical replication or CDC only on tables the owner publishes as a contract; keep materialized views inside one owner's (or one modular monolith's) database. The SQL for alternatives A and B:
-- Alternative A (same database, modular monolith): a materialized view over
-- tables owned by three modules. Cheap, but it couples the view to every
-- owner's schema and it is only as fresh as the last refresh.
CREATE MATERIALIZED VIEW reporting.order_summary_mv AS
SELECT o.id AS order_id, o.customer_id, o.total_minor, o.placed_at,
s.dispatched_at, s.carrier, i.paid_at
FROM sales.orders o
LEFT JOIN fulfilment.shipments s ON s.order_id = o.id
LEFT JOIN billing.invoices i ON i.order_id = o.id;
CREATE UNIQUE INDEX ON reporting.order_summary_mv (order_id); -- required for CONCURRENTLY
REFRESH MATERIALIZED VIEW CONCURRENTLY reporting.order_summary_mv;
-- Alternative B (separate databases): PostgreSQL logical replication of
-- SELECTED tables, columns and rows into the read database. The owner publishes
-- a deliberately small, documented, insert-only table of facts rather than its
-- internal invoices table. DDL is not replicated: schema changes are a
-- contract change, coordinated like an event version.
-- On the Billing database (publisher, wal_level = logical):
CREATE PUBLICATION billing_payments_pub
FOR TABLE billing.invoice_payments (payment_id, order_id, invoice_id, paid_minor, paid_at)
WHERE (paid_minor > 0) -- row filter: refunds stay private
WITH (publish = 'insert'); -- insert-only, so the filter may use any column
-- On the read database (subscriber); the target table must already exist there:
CREATE SUBSCRIPTION read_billing_payments
CONNECTION 'host=billing-db dbname=billing user=replicator'
PUBLICATION billing_payments_pub;
-- The read side builds order_summary from its own replicated copy; it never
-- connects to Billing's database. The apply worker runs with
-- session_replication_role = replica, so a projection trigger on the
-- subscriber must be enabled with ENABLE ALWAYS (or ENABLE REPLICA):
ALTER TABLE billing.invoice_payments ENABLE ALWAYS TRIGGER project_payment_into_summary;The Debezium connector for the same table (Kafka Connect JSON; publication.autocreate.mode=filtered is what the Debezium docs recommend with pgoutput so the connector does not try CREATE PUBLICATION … FOR ALL TABLES):
{
"name": "billing-payments-cdc",
"config": {
"connector.class": "io.debezium.connector.postgresql.PostgresConnector",
"database.hostname": "billing-db",
"database.port": "5432",
"database.user": "debezium",
"database.password": "${file:/secrets/billing.properties:password}",
"database.dbname": "billing",
"topic.prefix": "billing",
"plugin.name": "pgoutput",
"publication.name": "dbz_billing_payments",
"publication.autocreate.mode": "filtered",
"table.include.list": "billing.invoice_payments",
"column.include.list": "billing.invoice_payments.payment_id,billing.invoice_payments.order_id,billing.invoice_payments.invoice_id,billing.invoice_payments.paid_minor,billing.invoice_payments.paid_at",
"snapshot.mode": "initial",
"heartbeat.interval.ms": "10000"
}
}API composition vs a CQRS read model Important
In plain words: for a query across owners you either ask each owner at request time and stitch the answers together, or you keep your own copy fed by their events and ask only it.
Common misunderstanding: "API composition is the naive option, read models are the grown-up one." Composition is fresher, simpler and correct for small keyed lookups; it is the right first choice and the Data Ownership chapter compares the two in depth.
Definition: API composition: "Implement a query by defining an API Composer, which invoking the services that own the data and performs an in-memory join of the results"; drawback: "Some queries would result in inefficient, in-memory joins of large datasets." CQRS read model: "Define a view database, which is a read-only ‘replica’ that is designed specifically to support that query", kept current "by subscribing to Domain events published by the service that own the data"; drawback: "Replication lag/eventually consistent views".
"My orders, newest first, 20 per page, with shipping and payment state"
API composition OrderSummary read model
1 Sales: GET /orders?customer=c-9&limit=20 40 ms SELECT ... FROM order_summary
2 Fulfilment: GET /shipments?orders=... 35 ms WHERE customer_id = 'c-9'
3 Billing: GET /invoices?orders=... 30 ms ORDER BY placed_at DESC LIMIT 20 (4 ms)
4 join in memory, ~80 ms; Billing down -> partial Billing down -> page still works, payment maybe stale
5 filter "unpaid only": Sales cannot page by Billing's state -> read model neededReal scenario: order detail page (composition, keyed by one id); "My orders" with filters across owners (read model); support search by tracking number (read model or search index); checkout summary that must be exact (composition from the owners, no stale data).
| Question | API composition | Read model |
|---|---|---|
| Freshness | Live | Lags (ms to s) |
| Filter/sort/page by another owner's field | No | Yes |
| Works when an owner is down | Partial | Yes (stale) |
| Moving parts | Composer, timeouts, batching | Events, projector, store, replay, lag metric |
| Best for | Keyed lookups, small joins, exact answers | Lists, search, dashboards, high read ratio |
Fix / how to use it: start with composition; batch calls (one per owner, not one per row); move a query to a read model when it needs cross-owner filters or paging, or when composition breaks its latency or availability target (SLOs).
// Composition in Go: one batched call per owner, a budget for the whole page.
ctx, cancel := context.WithTimeout(ctx, 150*time.Millisecond)
defer cancel()
orders, err := sales.ListByCustomer(ctx, customerID, 20)
ships, _ := fulfilment.ByOrders(ctx, ids(orders)) // degrade: missing -> "unknown"// Composition in Laravel with Http::pool (parallel requests).
[$orders, $ships] = Http::pool(fn ($pool) => [
$pool->timeout(1)->get('http://sales/orders', ['customer' => $id]),
$pool->timeout(1)->get('http://fulfilment/shipments', ['customer' => $id]),
]);Read-your-writes after a command Must-know
In plain words: after I place an order I must see it, even if everybody else may see it a moment later. With an asynchronous read model this does not happen by itself; you have to design for it.
Common misunderstanding: "Make the projector faster and the problem goes away." Lag can be 20 ms on a quiet day and 20 s during a broker incident or a rebuild; the user's very next request often comes within 100 ms of the write. You need a mechanism, not a hope.
Definition: read-your-writes is a session guarantee: a client's reads reflect that client's own earlier writes (the model is defined in Eventual Consistency in Databases). For a CQRS read model, four strategies:
- Version token, wait-for-projection: the command returns the aggregate's new version (
202 {version: 1}); the query takesmin_version=1and waits a short budget for the row to reach it, else answers202withRetry-After. - Sticky reads: for a short window after a write, the same user is served from the write model (or the primary). Laravel's
stickyoption does this for one request on a read/write-split connection: "If the sticky option is enabled and a "write" operation has been performed against the database during the current request cycle, any further "read" operations will use the "write" connection." - UI optimism: the client renders its own copy immediately, marked "processing", and reconciles when the read model reaches the version.
- Synchronous projection for this one read model: step 3 of the spectrum (same transaction), if the read model lives in the owner's database.
The timeline shows why the naive read fails: the user's next request arrives before the projector has applied the event. The token strategy waits for exactly that event; the sticky strategy avoids the read model; the optimistic UI never asks.
Client Sales (write) Read side
1 POST /orders {order_id: o-1} BEGIN; insert; outbox; COMMIT
2 <- 202 {version: 1}, Location: /order-summaries/o-1?min_version=1
3 GET .../o-1?min_version=1 row missing -> wait (poll 50 ms)
4 projector applies OrderPlaced v1 (t=180 ms)
5 <- 200 {status: "placed", sales_version: 1} (budget 300 ms not exceeded)
6 (if not reached in 300 ms) <- 202 Retry-After: 1 UI keeps its optimistic copyReal scenario: "My orders" right after checkout; a profile edit shown back on the next page; an admin who deactivates a product and reloads the list; a support agent who refunds and refreshes the customer view.
| Strategy | Works across devices | Load on write side | UX | Use when |
|---|---|---|---|---|
| Version token + wait | Yes, if the token travels (URL, response) | None | Short spinner at worst | Default for async read models |
Sticky reads (Laravel sticky, "read primary for 5 s") | No (per request or per session) | Some | Invisible | Read/write-split replicas; same-request reads |
| UI optimism | No (only the acting client) | None | Instant | Lists the user just added to |
| Synchronous projection | Yes | Every write pays | Invisible | Read model in the owner's DB, must be exact |
Fix / how to use it: return a token from the command, wait briefly on the query.
row, err := query.WaitFor(ctx, store, orderID, minVersion, 300*time.Millisecond, 50*time.Millisecond)
if errors.Is(err, query.ErrNotYetProjected) {
w.Header().Set("Retry-After", "1")
w.WriteHeader(http.StatusAccepted)
return
}// config/database.php for a read/write split on the WRITE side's own connection:
'sales' => ['read' => ['host' => ['10.0.0.11']], 'write' => ['host' => ['10.0.0.10']], 'sticky' => true, /* ... */],Eventual-consistency failures and designing around them Important
In plain words: an asynchronous read model is sometimes wrong for a while. The failures are predictable, so you can design each screen to survive them.
Common misunderstanding: "Eventual consistency means the data is eventually correct, so there is nothing to design." It means if nothing else changes the copies converge; in between, users see stale lists, deleted items that are still there, rows with half their facts, and a projector bug can keep a row wrong until you rebuild.
Definition: the classic failure modes of read models:
- Stale list: the row exists but shows an old state ("placed" after it dispatched).
- Phantom delete / resurrection: an item deleted on the write side still appears in the read model or search index; or a late, older "updated" event recreates a deleted row.
- Missing parent / orphan facts:
ParcelDispatchedarrives beforeOrderPlaced; a naive projector drops it or crashes. - Lost update in the projector: two events for the same row processed concurrently by two workers, each writing the whole row.
- Projector bug or poison event: one event fails forever and blocks the partition or queue behind it.
Write side Search index (projected)
1 DeleteProduct p-7 (Catalog) -> ProductDeleted
2 UpdateProduct p-7 earlier -> ProductUpdated (delayed by a retry)
3 ProductDeleted applied: p-7 removed
4 ProductUpdated applied: p-7 recreated <- resurrection
-> fix: tombstone row with version; apply an update only if version > tombstone versionReal scenario: a product removed for legal reasons still searchable for an hour; an order shown as "placed" while the parcel is already at the door; a customer's address change missing from the support tool; a list count that does not match the number of rows after a duplicate.
| Failure | Design that prevents or hides it |
|---|---|
| Stale list | Show "as of" time or a "processing" badge; read-your-writes for the actor |
| Phantom delete | Deletes are events too; keep a tombstone (deleted_at, version) and filter on it |
| Resurrection by an old event | Version guard: apply only if event version > stored version |
| Missing parent | Upsert own columns; derive status; alert on rows stuck "pending" |
| Concurrent writers to one row | Each event updates only its columns; partition by order id; or row lock |
| Poison event | Retry with backoff, then dead-letter (DLQ); never block the stream forever |
| Projector bug | Fix the code, rebuild from the log, swap |
Fix / how to use it: a tombstone plus version guard.
-- ProductDeleted: keep the row as a tombstone; searches filter deleted_at IS NULL.
UPDATE product_search SET deleted_at = $2, version = $3 WHERE product_id = $1 AND version < $3;
-- ProductUpdated: never resurrect a newer tombstone.
UPDATE product_search SET name = $2, version = $3 WHERE product_id = $1 AND version < $3;Reporting and analytics Important
In plain words: analysts need everything joined with everything, over years. Give them a separate copy built for that; never point a BI tool at the services' production databases.
Common misunderstanding: "A read replica of each service is enough for reporting." It is still each owner's internal schema (so every rename breaks a report), the joins still cross databases, and long analytical queries on a hot standby cause replication conflicts or delay replay.
Definition: Fowler's reporting database: "a completely different database to the operational database", "designed around the reporting needs", kept current by "an overnight run" or "a messaging system so that any changes to the operational database are forwarded to the reporting database". At scale this is a data warehouse or lakehouse fed by CDC or by published events (OLTP vs OLAP, Big Data Architectures).
1 Sales, Fulfilment, Billing commit in their own DBs
2 CDC (Debezium) or outbox events -> Kafka topics (contract tables / events only)
3 loader -> warehouse staging -> modelled tables (orders_fact, shipments_fact)
4 finance dashboard queries the warehouse (seconds), the services never noticeReal scenario: month-end revenue by region; delivery-time percentiles by carrier; refund rates per product; a data-science team training models on order history.
| Source for reports | Freshness | Load on services | Schema stability | Verdict |
|---|---|---|---|---|
| Services' primaries | Live | High, unpredictable | Breaks on every rename | Never |
| Services' replicas | Seconds | Replay conflicts, lag | Breaks on every rename | Avoid |
| Read models (OrderSummary) | Seconds | None | Stable, per screen | Operational dashboards only |
| Warehouse from CDC/events | Minutes | None | Modelled, versioned | Default |
Fix / how to use it: publish analytics-friendly events or CDC from contract tables; load them into a warehouse; give the report owners their own model.
Task-based UIs Important
In plain words: instead of a form that edits the whole record and sends it back with PUT, the screen offers the actions a user actually performs ("Cancel order", "Change delivery address", "Mark paid"), and each sends a small command that names the intent.
Common misunderstanding: "Task-based means more endpoints for the same thing." It means different things: "correct a typo in the address" and "the customer moved" are different business events with different rules (Young's example: "Is there a difference between “Correcting an Address” and “Relocating the Customer”?").
Definition: Young's documents contrast the DTO up/down architecture, in which "the intention of the user is being lost", with commands that are "always in the imperative tense" and carry "only … data points that are required to process the given behavior". The server may reject a command; if it could not, it would be an event. Fowler notes that moving away from CRUD lets you "easily move to a task-based UI".
CRUD screen Task-based screen
1 GET /orders/o-1 -> full DTO GET /order-summaries/o-1 (read model)
2 user edits status, carrier, total user clicks "Cancel order", gives a reason
3 PUT /orders/o-1 {whole DTO} POST /orders/o-1/cancel {reason}
4 server: which field changed, and why? server: CancelOrder -> rule check -> OrderCancelledReal scenario: order cancellation with a reason and refund rule; address correction vs relocation; "pause subscription" vs "change plan"; a support tool where every action is audited by name.
| Aspect | CRUD PUT | Task-based command |
|---|---|---|
| Intent | Lost | Named (CancelOrder) |
| Payload | Whole record | Only what the behaviour needs |
| Where rules live | Spread in validators | On the aggregate method |
| Events | "OrderUpdated" | OrderCancelled with a reason |
| Fits | Reference data, admin lists | Core domain behaviour |
Fix / how to use it: one endpoint per intent, client-generated ids, a 202 with a version token.
Route::post('/orders', [OrderCommandController::class, 'place']); // PlaceOrder
Route::post('/orders/{order}/cancel', [OrderCommandController::class, 'cancel']); // CancelOrder (handler not shown)
Route::get('/order-summaries/{orderId}', [OrderSummaryController::class, 'show'])->name('order-summaries.show');Event sourcing as an option for the write side Good to know
In plain words: instead of storing the order's current row, store every event that ever happened to it and rebuild the current state by replaying them. Then every read is a projection by definition.
Common misunderstanding: "CQRS and event sourcing are the same thing" or "you need event sourcing to do CQRS". Our OrderSummary uses CQRS with a plain state-stored Order aggregate and an outbox.
Definition: "Event sourcing persists the state of a business entity such an Order or a Customer as a sequence of state-changing events." Its cost: "The event store is difficult to query since it requires typical queries to reconstruct the state of the business entities … As a result, the application must use Command Query Responsibility Segregation (CQRS) to implement queries." Event stores, snapshots, upcasting and replay are taught in Event Sourcing & CQRS.
1 state-stored: orders row {status: dispatched, version: 3} + outbox events (this page)
2 event-sourced: OrderPlaced(v1), OrderPaid(v2), OrderDispatched(v3) are the only truth
3 read models in both cases: projections of the events
4 difference: with event sourcing the write side can be replayed too (audit, temporal queries)Real scenario: ledgers and payments where auditors want every change; domains where "what did we know at 10:42?" is a real question; collaborative editing. Not: catalogue admin, user profiles, most CRUD.
| Write side | Audit/history | Query the write side | Learning curve | When |
|---|---|---|---|---|
| State-stored + outbox | Only what you publish | Yes (SQL) | Low | Default |
| Event-sourced | Complete, by construction | No; projections only | High | Audit-heavy core domains |
Fix / how to use it: decide per bounded context, after CQRS has proved useful there; do not adopt it for the read-model problem alone.
Testing projections Good to know
In plain words: a projector is a pure function from events to rows, so test it by feeding it recorded event sequences (fixtures) and comparing the resulting rows with expected ones, including duplicates, reordering and a rebuild.
Common misunderstanding: "End-to-end tests through the broker cover the projector." They are slow and rarely deliver events twice or out of order, which is exactly where projectors break.
Definition: replay fixtures are ordered lists of envelopes (often captured from production, anonymised); snapshot tests (golden files) store the expected read-model row as JSON and fail on any difference; property-style tests shuffle and duplicate the fixture and assert the same final row; rebuild tests replay the log into a fresh store and compare with the live one.
1 fixture: [dispatched, placed, paid] -> row R
2 fixture + fixture (duplicates) -> row R, log has 3 events
3 shuffle(fixture) -> row R
4 rebuild(log) into empty store -> row R
5 golden file testdata/order_summary.golden.json == JSON(R)Real scenario: a new field added to OrderPlaced v1; a refactor of the projector's SQL; a change of event order in Kafka after repartitioning; a bug report "dispatched orders show as placed".
| Test | Catches | Speed |
|---|---|---|
| Unit test per event type | Mapping bugs | ms |
| Replay fixture + snapshot | Any change in the final row | ms |
| Duplicate/shuffle test | Idempotency and ordering bugs | ms |
| Rebuild equals live | Projector depends on hidden state | ms (memory) to s (DB) |
| Contract test on event schemas | Producer changed a field | s |
Fix / how to use it: the Go snapshot test (run go test ./readmodel -update after an intended change and review the golden diff):
package readmodel
import (
"context"
"encoding/json"
"flag"
"os"
"testing"
"time"
"academy/microservices-data-patterns/contracts"
)
var update = flag.Bool("update", false, "rewrite golden files")
type lagSpy struct{ n int }
func (l *lagSpy) Observe(string, time.Duration) { l.n++ }
func project(t *testing.T, events []contracts.Envelope) (*Memory, *lagSpy) {
t.Helper()
store, lag := NewMemory(), &lagSpy{}
p := &Projector{Store: store, Lag: lag, Now: func() time.Time { return t0.Add(5 * time.Minute) }}
for _, e := range events {
if err := p.Handle(context.Background(), e); err != nil {
t.Fatal(err)
}
}
return store, lag
}
func TestOutOfOrderEventsConverge(t *testing.T) {
store, _ := project(t, fixture())
got, _, _ := store.Get(context.Background(), "o-1")
if got.Status() != "completed" || got.TotalMinor != 2500 || got.Carrier != "DHL" {
t.Fatalf("got %+v status %s", got, got.Status())
}
}
func TestDispatchedBeforePlacedIsPending(t *testing.T) {
store, _ := project(t, fixture()[:1])
got, _, _ := store.Get(context.Background(), "o-1")
if got.Status() != "pending" {
t.Fatalf("want pending, got %s", got.Status())
}
}
func TestDuplicateDeliveryIsANoOp(t *testing.T) {
ev := fixture()
store, lag := project(t, append(ev, ev...))
if lag.n != 3 {
t.Fatalf("want 3 applied, got %d", lag.n)
}
n, _ := store.ReplayAfter(context.Background(), 0, 0, func(int64, contracts.Envelope) error { return nil })
if n != 3 {
t.Fatalf("log should hold 3 unique events, got %d", n)
}
}
func TestStaleSalesVersionIsIgnored(t *testing.T) {
ev := fixture()
older := mustEnv("evt-placed-0", "/sales", contracts.TypeOrderPlacedV1, "o-1", t0.Add(-time.Hour), 0,
contracts.OrderPlacedV1{OrderID: "o-1", TotalMinor: 1})
store, _ := project(t, append(ev, older))
got, _, _ := store.Get(context.Background(), "o-1")
if got.TotalMinor != 2500 {
t.Fatalf("stale event overwrote the row: %+v", got)
}
}
func TestUnknownTypeIsIgnored(t *testing.T) {
unknown := mustEnv("evt-x", "/sales", "sales.order.gift_wrapped.v1", "o-1", t0, 2, map[string]string{})
store, _ := project(t, []contracts.Envelope{unknown})
if _, ok, _ := store.Get(context.Background(), "o-1"); ok {
t.Fatal("unknown event created a row")
}
}
func TestRebuildEqualsLive(t *testing.T) {
live, _ := project(t, fixture())
fresh := NewMemory()
last, err := Rebuild(context.Background(), live, 0, 0, fresh)
if err != nil || last != 3 {
t.Fatalf("last=%d err=%v", last, err)
}
a, _, _ := live.Get(context.Background(), "o-1")
b, _, _ := fresh.Get(context.Background(), "o-1")
ja, _ := json.Marshal(a)
jb, _ := json.Marshal(b)
if string(ja) != string(jb) {
t.Fatalf("rebuild differs\nlive: %s\nrebuilt: %s", ja, jb)
}
}
// TestSnapshot is a snapshot (golden-file) test: replay the fixture and compare
// the row with the committed JSON. Run `go test ./readmodel -update` after an
// intended change and review the diff in code review.
func TestSnapshot(t *testing.T) {
store, _ := project(t, fixture())
got, _, _ := store.Get(context.Background(), "o-1")
b, _ := json.MarshalIndent(struct {
OrderSummary
Status string `json:"status"`
}{got, got.Status()}, "", " ")
path := "testdata/order_summary.golden.json"
if *update {
if err := os.WriteFile(path, b, 0o644); err != nil {
t.Fatal(err)
}
}
want, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if string(want) != string(b) {
t.Fatalf("snapshot mismatch\nwant: %s\ngot: %s", want, b)
}
}Observability of projections Important
In plain words: you must be able to answer "how far behind is the read model, and is it moving?" at any moment, and you must be able to rebuild it with one command.
Common misunderstanding: "Queue length tells us the lag." A queue can be empty because the relay stopped publishing; the user-facing number is the age of the newest fact the read model has applied, per source.
Definition: projection lag = now minus the event time of the last applied event (per source), or the event-time delay measured at apply time (histogram). Also watch: consumer lag (Kafka offsets, RabbitMQ queue depth), dead-letter count, rows stuck in "pending", rebuild duration, and replication slot retained WAL for CDC/logical replication.
1 metric projection_lag_seconds{projection="order_summary",source="/billing"} p99 0.4 s
2 alert: lag > 30 s for 5 min, or no applied events for 10 min while the outbox has rows
3 dashboard: lag per source, applied/s, duplicates/s, DLQ size, pending rows
4 runbook: pause projector -> fix -> order-summary:rebuild -> swap -> resumeReal scenario: Billing's relay stopped after a deploy and "paid" never appeared; a Kafka consumer group rebalanced in a loop; a replication slot filled the disk of the Billing primary; a rebuild that took 3 h because the log table had no index on position.
| Signal | Where | Meaning |
|---|---|---|
projection_lag_seconds per source | Projector (Prometheus histogram) | User-visible staleness |
| Consumer lag | Kafka offsets / RabbitMQ queue depth | Backlog not yet delivered |
received_events rate vs outbox rate | Both sides | Relay or consumer stopped |
Rows placed_at IS NULL older than 10 min | Read store | Missing parent / lost event |
| DLQ size | Broker | Poison events |
pg_replication_slots retained WAL | Owner's PostgreSQL | Stuck CDC or subscriber |
Fix / how to use it: the lag query from the read-side schema (also in Mechanics), and the projector's LagRecorder in Go or the projection.applied log line in Laravel.
SELECT source, now() - max(occurred_at) AS lag_by_event_time, now() - max(received_at) AS since_last_delivery
FROM received_events GROUP BY source;Mechanics
The read-side schema
Two tables. received_events is the dedup key (UNIQUE event_id) and the replay log (position identity). order_summary groups its columns by owning context, so each event type writes only its group. The last two queries are the lag metric and the "stuck pending" alarm.
-- Read side of the "My orders" screen, owned by the read-model service
-- (or by the Sales module's read side in a modular monolith).
-- 1. Every integration event this read side has received: dedup key + replay log.
CREATE TABLE received_events (
position bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
event_id text NOT NULL UNIQUE, -- idempotency: one row per event id
source text NOT NULL, -- /sales, /fulfilment, /billing
type text NOT NULL, -- sales.order.placed.v1 ...
subject text NOT NULL, -- order id
source_version bigint NOT NULL,
occurred_at timestamptz NOT NULL,
received_at timestamptz NOT NULL DEFAULT now(),
payload jsonb NOT NULL
);
-- 2. The read model: one denormalised row per order, columns grouped by owner.
CREATE TABLE order_summary (
order_id text PRIMARY KEY,
-- Sales columns (from sales.order.placed.v1), guarded by sales_version
customer_id text,
currency char(3),
total_minor bigint NOT NULL DEFAULT 0,
line_count int NOT NULL DEFAULT 0,
sales_version bigint NOT NULL DEFAULT 0,
placed_at timestamptz,
-- Fulfilment columns (from fulfilment.parcel.dispatched.v1)
dispatched_at timestamptz,
carrier text,
tracking_ref text,
-- Billing columns (from billing.invoice.paid.v1)
paid_at timestamptz,
paid_minor bigint NOT NULL DEFAULT 0,
updated_at timestamptz NOT NULL DEFAULT now()
);
-- Indexes follow the screens, not the domain: "my orders, newest first".
CREATE INDEX order_summary_customer_placed ON order_summary (customer_id, placed_at DESC);
-- 3. Projection lag per source: how old is the newest fact we have applied?
SELECT source,
now() - max(occurred_at) AS lag_by_event_time,
now() - max(received_at) AS since_last_delivery
FROM received_events
GROUP BY source;
-- 4. Orders stuck in "pending" (a Fulfilment/Billing fact arrived, OrderPlaced did not).
SELECT order_id, updated_at
FROM order_summary
WHERE placed_at IS NULL AND updated_at < now() - interval '10 minutes';The projection algorithm, step by step
Projector worker (one delivery)
1 receive envelope {id, source, type, subject, time, sourceversion, data}
2 Decode(type): unknown type -> ack and skip (forward compatible); bad payload -> error -> retry -> DLQ
3 BEGIN
4 INSERT INTO received_events (...) ON CONFLICT (event_id) DO NOTHING
5 rows affected = 0 -> COMMIT; ack; stop (duplicate)
6 INSERT INTO order_summary (own columns) ON CONFLICT (order_id) DO UPDATE SET own columns
[Sales only: WHERE s.sales_version < EXCLUDED.sales_version]
7 COMMIT
8 ack the message (after commit: a crash before ack only causes a redelivery, which step 5 absorbs)
9 observe lag = now - envelope.timeTwo properties make this safe without distributed transactions: the dedup insert and the row update share one local transaction, and the broker ack comes after the commit (at-least-once). Concurrency: two workers handling two events of the same order touch different columns; the row-level lock taken by ON CONFLICT DO UPDATE serialises them. Partitioning by subject (Kafka key, RabbitMQ consistent-hash exchange) removes even that contention (Ordering & Partitioning).
Rebuild and swap
Rebuild job Live projector (several workers)
1 CREATE TABLE order_summary_rebuild (LIKE order_summary INCLUDING ALL)
2 fence F1: BEGIN; LOCK received_events EXCLUSIVE; in-flight inserts finish first,
SELECT max(position); COMMIT new ones wait a moment
3 replay positions 1..F1 into _rebuild keeps applying F1+1, F1+2 ... to order_summary
4 catch-up: fence F2, replay F1+1..F2 (repeat a few times)
5 BEGIN; LOCK TABLE received_events IN EXCLUSIVE MODE new ApplyOnce calls wait (plain SELECTs do not)
6 replay F2+1..end into _rebuild (complete: no inserter is open)
7 RENAME order_summary -> _old, _rebuild -> order_summary; DROP _old
readers of order_summary wait (ACCESS EXCLUSIVE)
8 COMMIT waiting calls continue on the new tableWhy a fence. position is an identity value assigned when the row is inserted, not when it commits. With several projector workers, position 11 can commit while 10 is still open; a pass that reads "everything after 9" sees 11, records 11 as done, and 10 is never replayed, including in the final tail, after which the swap drops the only table that had it. Taking LOCK TABLE received_events IN EXCLUSIVE MODE waits for every open inserter, so max(position) read under that lock is a position below which everything has committed. PostgreSQL's lock table: INSERT takes ROW EXCLUSIVE, which conflicts with EXCLUSIVE; and EXCLUSIVE "allows only concurrent ACCESS SHARE locks", i.e. plain reads of the log continue. The swap is not invisible to readers: ALTER TABLE … RENAME takes ACCESS EXCLUSIVE ("An ACCESS EXCLUSIVE lock is acquired unless explicitly noted"), and "Only an ACCESS EXCLUSIVE lock blocks a SELECT", so queries on order_summary wait for the milliseconds of steps 7 and 8. Both transactions lock the log before the summary table, so the swap cannot deadlock with ApplyOnce. If you would rather not reason about this, pause the projector (queue:pause, stop the consumer) for the rebuild; the broker buffers. A new read-model version (new columns, new shape) uses the same procedure with a new projector, or a side-by-side order_summary_v2 that readers switch to by configuration.
Knobs and settings per product
| Product | Knob | What it does here |
|---|---|---|
| Laravel 13 | 'sticky' => true on a read/write connection | Reads after a write in the same request go to the write host |
| Laravel 13 | DB::withoutAffectingStickiness(fn) | Writes (audit, progress) that should not make reads sticky |
| Laravel 13 | ShouldQueueAfterCommit on a listener | Queue the listener only after the open transaction commits |
| Laravel 13 | after_commit in config/queue.php | Same, for every job on that connection |
| Laravel 13 | ShouldDispatchAfterCommit on an event | Dispatch the event only after commit; discarded on rollback |
| Laravel 13 | $tries, backoff() on a queued listener | Retry policy before failed_jobs |
| Laravel 13 | ShouldBeUnique | Only one instance of a job/listener queued at a time (not dedup of events) |
| Laravel Scout | queue option, Searchable trait | Index sync through model observers, queued |
| PostgreSQL | wal_level = logical | Required for logical replication and Debezium |
| PostgreSQL | max_replication_slots, max_wal_senders | Capacity for subscribers and CDC connectors |
| PostgreSQL | CREATE PUBLICATION … (cols) WHERE (…), WITH (publish = 'insert') | Column lists, row filters, operations |
| PostgreSQL | REPLICA IDENTITY | Needed to replicate UPDATE/DELETE; limits row filters and column lists |
| PostgreSQL | REFRESH MATERIALIZED VIEW CONCURRENTLY | Refresh without blocking readers; needs a unique index |
| PostgreSQL | ALTER TABLE … ENABLE ALWAYS TRIGGER | Fire a projection trigger in the logical-replication apply worker |
| Debezium | plugin.name=pgoutput, publication.autocreate.mode=filtered | Use the built-in plugin, create a publication only for included tables |
| Debezium | table.include.list, column.include.list | Capture only the contract table and columns |
| Debezium | snapshot.mode=initial | Snapshot existing rows (op: r) before streaming |
| Debezium | heartbeat.interval.ms | Keep the slot advancing when captured tables are quiet |
| Kafka | key = order id; topic retention or compaction | Per-order ordering; how far back a replay can go |
Errors you will see
| Error | Where | Meaning and fix |
|---|---|---|
duplicate key value violates unique constraint "received_events_event_id_key" (SQLSTATE 23505) | PostgreSQL | A plain INSERT met a redelivery; use ON CONFLICT DO NOTHING (or catch it) |
Illuminate\Database\UniqueConstraintViolationException | Laravel | Same, from Eloquent/query builder; insertOrIgnore avoids it |
MySQL 1062 Duplicate entry | MySQL | Same on MySQL; INSERT IGNORE / insertOrIgnore |
permission denied for schema sales (42501) | PostgreSQL | A service touched another service's schema: the ownership rule worked |
cannot refresh materialized view "…" concurrently | PostgreSQL | No suitable unique index on the materialized view |
cannot update table "…" because it does not have a replica identity and publishes updates | PostgreSQL publisher | Set REPLICA IDENTITY or publish inserts only |
replication slot "…" is active for PID … | PostgreSQL | Two connectors on one slot; one CDC connector per slot |
deadlock detected (40P01) | PostgreSQL | Projector updating several rows in different orders; partition by key or sort (Deadlocks) |
ErrNotYetProjected / HTTP 202 + Retry-After | Our query API | The read model has not reached the client's version within the budget |
What each product really does
| Product | Feature used as a read side | Behaviour to know |
|---|---|---|
| PostgreSQL | Tables, upsert, materialized views, logical replication | ON CONFLICT takes a row lock; DDL not replicated; matview refresh is full recompute |
| MySQL / InnoDB | Read replicas (binlog), INSERT … ON DUPLICATE KEY UPDATE, INSERT IGNORE | No materialized views; replicas lag; dedup with a unique key plus INSERT IGNORE |
| MongoDB | Document per screen; change streams as a CDC source | Natural fit for per-screen documents; change streams need a replica set |
| Elasticsearch / OpenSearch | Search read model | Near-real-time: a document is searchable after the next refresh; use external versioning to avoid resurrection |
| Redis | Key-value read model, counters | Fast; not a log, so rebuild from your own log, not from Redis |
| Kafka | Transport; compacted topic as a "latest state per key" source | Retention decides how far a replay can go; compaction keeps last value per key |
| Debezium | CDC from PostgreSQL/MySQL/MongoDB into Kafka | At least once on failures; snapshot then stream; one slot per connector |
| Laravel Scout | Search index sync from Eloquent models | Observer-based, same-model shape; fine within one owner, not a cross-owner read model |
Go
The Go module (academy/microservices-data-patterns, pgx v5) has the write side, the read side and an in-memory store with the same contract as the PostgreSQL one, so go test ./... exercises duplicates, reordering, stale versions, rebuilds and read-your-writes without a database.
The contracts: three owners, one envelope
// Package contracts holds the integration events the OrderSummary read model
// consumes. Each type is owned by the context that publishes it: Sales owns
// sales.*, Fulfilment owns fulfilment.*, Billing owns billing.*. The read side
// only depends on these published shapes, never on another context's tables.
package contracts
import (
"encoding/json"
"time"
)
// Envelope uses CloudEvents attribute names in its JSON form.
// SourceVersion is the publishing aggregate's version after the change; a
// consumer uses it to ignore stale or reordered events from the same source.
type Envelope struct {
ID string `json:"id"`
Source string `json:"source"`
Type string `json:"type"`
Subject string `json:"subject"` // the order id for all three types
Time time.Time `json:"time"`
SourceVersion int64 `json:"sourceversion"`
Data json.RawMessage `json:"data"`
}
// Contract names: <context>.<entity>.<fact>.v<major>.
const (
TypeOrderPlacedV1 = "sales.order.placed.v1"
TypeParcelDispatchedV1 = "fulfilment.parcel.dispatched.v1"
TypeInvoicePaidV1 = "billing.invoice.paid.v1"
)
// OrderPlacedV1 is published by Sales when an Order aggregate is placed.
type OrderPlacedV1 struct {
OrderID string `json:"orderId"`
CustomerID string `json:"customerId"`
TotalMinor int64 `json:"totalMinor"`
Currency string `json:"currency"`
LineCount int `json:"lineCount"`
}
// ParcelDispatchedV1 is published by Fulfilment when the parcel leaves the warehouse.
type ParcelDispatchedV1 struct {
OrderID string `json:"orderId"`
ShipmentID string `json:"shipmentId"`
Carrier string `json:"carrier"`
TrackingRef string `json:"trackingRef"`
}
// InvoicePaidV1 is published by Billing when the invoice for an order is paid.
type InvoicePaidV1 struct {
OrderID string `json:"orderId"`
InvoiceID string `json:"invoiceId"`
PaidMinor int64 `json:"paidMinor"`
}
// New builds an envelope; tests and the demo use it.
func New(id, source, typ, subject string, at time.Time, version int64, payload any) (Envelope, error) {
raw, err := json.Marshal(payload)
if err != nil {
return Envelope{}, err
}
return Envelope{ID: id, Source: source, Type: typ, Subject: subject, Time: at, SourceVersion: version, Data: raw}, nil
}CQS at the method level
// Package cqs shows Command-Query Separation at the method level: a command
// changes state and returns only an error; a query returns data and changes
// nothing observable.
package cqs
import "errors"
// ErrNotPaid is returned when a rule rejects a command.
var ErrNotPaid = errors.New("order is not paid")
// Status is a small value type.
type Status string
const (
Placed Status = "placed"
Paid Status = "paid"
Dispatched Status = "dispatched"
)
// Order is a tiny aggregate used only to show the method shapes.
type Order struct {
id string
status Status
version int64
}
// NewOrder places an order (a constructor is allowed to return the object).
func NewOrder(id string) *Order { return &Order{id: id, status: Placed, version: 1} }
// MarkPaid is a COMMAND: it mutates and returns only an error.
func (o *Order) MarkPaid() error {
if o.status != Placed {
return errors.New("only a placed order can be paid")
}
o.status = Paid
o.version++
return nil
}
// Dispatch is a COMMAND guarded by a rule.
func (o *Order) Dispatch() error {
if o.status != Paid {
return ErrNotPaid
}
o.status = Dispatched
o.version++
return nil
}
// Status is a QUERY: no side effects, safe to call any number of times in any order.
func (o *Order) Status() Status { return o.status }
// Version is a QUERY; the application layer reads it after a command to hand
// the caller a consistency token (see the query package).
func (o *Order) Version() int64 { return o.version }
// CanDispatch is a QUERY that answers a question without changing the answer.
func (o *Order) CanDispatch() bool { return o.status == Paid }Write side: the Order aggregate and a task-based command handler
The handler returns an Ack with the new version, not read data: that is the consistency token.
// Package sales is the WRITE side: the Order aggregate, a task-based command
// and its handler. Nothing here is shaped for screens.
package sales
import (
"errors"
"time"
)
// Line is one order line (value object).
type Line struct {
SKU string
Quantity int
PriceMinor int64
}
// Order is the aggregate root. Its fields are private: screens read the
// OrderSummary read model, not this object.
type Order struct {
id string
customerID string
lines []Line
currency string
placedAt time.Time
version int64
pending []Placed
}
// Placed is the domain event recorded by Place.
type Placed struct {
OrderID string
CustomerID string
TotalMinor int64
Currency string
LineCount int
Version int64
At time.Time
}
// ErrEmptyOrder is a rule violation.
var ErrEmptyOrder = errors.New("an order needs at least one line")
// Place is the factory for a new order. The client supplies the id (a UUID),
// so the command needs no return value to tell the caller what was created.
func Place(id, customerID, currency string, lines []Line, now time.Time) (*Order, error) {
if len(lines) == 0 {
return nil, ErrEmptyOrder
}
o := &Order{id: id, customerID: customerID, lines: lines, currency: currency, placedAt: now, version: 1}
o.pending = append(o.pending, Placed{
OrderID: id, CustomerID: customerID, TotalMinor: o.total(), Currency: currency,
LineCount: len(lines), Version: o.version, At: now,
})
return o, nil
}
func (o *Order) total() int64 {
var t int64
for _, l := range o.lines {
t += l.PriceMinor * int64(l.Quantity)
}
return t
}
// ID and Version are queries.
func (o *Order) ID() string { return o.id }
// Version is the optimistic-concurrency version, also used as a consistency token.
func (o *Order) Version() int64 { return o.version }
// PullEvents hands recorded events to the repository and clears them.
func (o *Order) PullEvents() []Placed {
ev := o.pending
o.pending = nil
return ev
}package sales
import (
"context"
"time"
)
// PlaceOrder is a COMMAND: an intent in the imperative, carrying only what the
// behaviour needs. It is not an OrderDTO.
type PlaceOrder struct {
OrderID string // client-generated UUID
CustomerID string
Currency string
Lines []Line
}
// Repository saves the aggregate and its events (outbox) in ONE local
// transaction. The PostgreSQL version lives in the aggregates chapter.
type Repository interface {
Add(ctx context.Context, o *Order, events []Placed) error
}
// Ack is what the handler returns: no read data, only a consistency token the
// client may pass to the read side ("show me order X at version >= 1").
type Ack struct {
OrderID string
Version int64
}
// PlaceOrderHandler is the application service for the command.
type PlaceOrderHandler struct {
Repo Repository
Now func() time.Time
}
// Handle runs the command. It returns an Ack, not an OrderSummary: reading
// the result is the query side's job.
func (h PlaceOrderHandler) Handle(ctx context.Context, cmd PlaceOrder) (Ack, error) {
o, err := Place(cmd.OrderID, cmd.CustomerID, cmd.Currency, cmd.Lines, h.Now())
if err != nil {
return Ack{}, err
}
if err := h.Repo.Add(ctx, o, o.PullEvents()); err != nil {
return Ack{}, err
}
return Ack{OrderID: o.ID(), Version: o.Version()}, nil
}Read side: the OrderSummary model, patches and ports
// Package readmodel is the QUERY side: the OrderSummary read model, the
// patches events turn into, and the projector that applies them.
package readmodel
import (
"context"
"time"
"academy/microservices-data-patterns/contracts"
)
// OrderSummary is one row per order, shaped for the "My orders" screen and the
// support tool. It joins facts owned by three contexts; it owns none of them.
type OrderSummary struct {
OrderID string `json:"orderId"`
CustomerID string `json:"customerId,omitempty"`
TotalMinor int64 `json:"totalMinor"`
Currency string `json:"currency,omitempty"`
LineCount int `json:"lineCount"`
SalesVersion int64 `json:"salesVersion"` // 0 until OrderPlaced arrives
PlacedAt *time.Time `json:"placedAt,omitempty"`
DispatchedAt *time.Time `json:"dispatchedAt,omitempty"`
Carrier string `json:"carrier,omitempty"`
TrackingRef string `json:"trackingRef,omitempty"`
PaidAt *time.Time `json:"paidAt,omitempty"`
PaidMinor int64 `json:"paidMinor"`
}
// Status is DERIVED from which facts have arrived, so the order in which the
// three contexts' events arrive does not matter.
func (s OrderSummary) Status() string {
switch {
case s.PlacedAt == nil:
return "pending" // a Fulfilment or Billing fact arrived before OrderPlaced
case s.DispatchedAt != nil && s.PaidAt != nil:
return "completed"
case s.DispatchedAt != nil:
return "dispatched"
case s.PaidAt != nil:
return "paid"
default:
return "placed"
}
}
// Patch is the part of the row one event type owns. Each context's event
// touches only its own columns, so concurrent or reordered events never undo
// each other.
type Patch interface{ orderID() string }
// PlacedPatch owns the Sales columns; it is applied only if SalesVersion grows.
type PlacedPatch struct {
OrderID, CustomerID, Currency string
TotalMinor int64
LineCount int
SalesVersion int64
PlacedAt time.Time
}
// DispatchedPatch owns the Fulfilment columns.
type DispatchedPatch struct {
OrderID, Carrier, TrackingRef string
DispatchedAt time.Time
}
// PaidPatch owns the Billing columns.
type PaidPatch struct {
OrderID string
PaidMinor int64
PaidAt time.Time
}
func (p PlacedPatch) orderID() string { return p.OrderID }
func (p DispatchedPatch) orderID() string { return p.OrderID }
func (p PaidPatch) orderID() string { return p.OrderID }
// Store is the read store plus its received-events log. ApplyOnce must append
// the envelope to the log (unique on event id) and apply the patch in ONE
// transaction; it reports false for a duplicate.
type Store interface {
ApplyOnce(ctx context.Context, env contracts.Envelope, p Patch) (bool, error)
Get(ctx context.Context, orderID string) (OrderSummary, bool, error)
}
// Log is the append-only copy of every integration event this read side has
// received. It is the replay source for rebuilds: Fulfilment's and Billing's
// own databases are not ours to read. ReplayAfter visits positions in
// (after, upTo]; upTo = 0 means no upper bound.
type Log interface {
ReplayAfter(ctx context.Context, after, upTo int64, fn func(pos int64, env contracts.Envelope) error) (last int64, err error)
}
// Target receives patches during a rebuild (no dedup: the log is already unique).
type Target interface {
Apply(ctx context.Context, p Patch) error
}The projector: decode, apply once, measure lag, rebuild
package readmodel
import (
"context"
"encoding/json"
"fmt"
"time"
"academy/microservices-data-patterns/contracts"
)
// LagRecorder receives the projection lag: now minus the event's time.
// In production this is a Prometheus histogram labelled by source.
type LagRecorder interface {
Observe(source string, lag time.Duration)
}
// Projector turns integration events into read-model patches.
type Projector struct {
Store Store
Lag LagRecorder
Now func() time.Time
}
// Decode maps an envelope to a patch. Unknown types return (nil, nil): a new
// event type published tomorrow must not crash today's projector.
func Decode(env contracts.Envelope) (Patch, error) {
switch env.Type {
case contracts.TypeOrderPlacedV1:
var d contracts.OrderPlacedV1
if err := json.Unmarshal(env.Data, &d); err != nil {
return nil, fmt.Errorf("decode %s %s: %w", env.Type, env.ID, err)
}
return PlacedPatch{OrderID: d.OrderID, CustomerID: d.CustomerID, Currency: d.Currency,
TotalMinor: d.TotalMinor, LineCount: d.LineCount, SalesVersion: env.SourceVersion, PlacedAt: env.Time}, nil
case contracts.TypeParcelDispatchedV1:
var d contracts.ParcelDispatchedV1
if err := json.Unmarshal(env.Data, &d); err != nil {
return nil, fmt.Errorf("decode %s %s: %w", env.Type, env.ID, err)
}
return DispatchedPatch{OrderID: d.OrderID, Carrier: d.Carrier, TrackingRef: d.TrackingRef, DispatchedAt: env.Time}, nil
case contracts.TypeInvoicePaidV1:
var d contracts.InvoicePaidV1
if err := json.Unmarshal(env.Data, &d); err != nil {
return nil, fmt.Errorf("decode %s %s: %w", env.Type, env.ID, err)
}
return PaidPatch{OrderID: d.OrderID, PaidMinor: d.PaidMinor, PaidAt: env.Time}, nil
}
return nil, nil
}
// Handle is the projection handler the consumer calls for every delivery.
// Delivery is at-least-once, so the same envelope may arrive twice; ApplyOnce
// makes the second delivery a no-op.
func (p *Projector) Handle(ctx context.Context, env contracts.Envelope) error {
patch, err := Decode(env)
if err != nil || patch == nil {
return err // a decode error goes to the DLQ via the consumer's retry policy
}
applied, err := p.Store.ApplyOnce(ctx, env, patch)
if err != nil {
return err
}
if applied && p.Lag != nil {
p.Lag.Observe(env.Source, p.Now().Sub(env.Time))
}
return nil
}
// Rebuild replays the received-events log in (after, upTo] into a fresh target
// (a new table or a new index). Run it for a new read-model version or after a
// projector bug; then switch readers to the new target. upTo must be a fence:
// a position below which every log insert has committed (see pgstore).
func Rebuild(ctx context.Context, log Log, after, upTo int64, target Target) (int64, error) {
return log.ReplayAfter(ctx, after, upTo, func(_ int64, env contracts.Envelope) error {
patch, err := Decode(env)
if err != nil || patch == nil {
return err
}
return target.Apply(ctx, patch)
})
}PostgreSQL store with pgx: dedup and upsert in one transaction
// Package pgstore is the PostgreSQL read store for OrderSummary, using pgx.
// Schema: docs/snippets/ddd/microservices-data-patterns/sql/read_model.sql.
package pgstore
import (
"context"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"academy/microservices-data-patterns/contracts"
"academy/microservices-data-patterns/readmodel"
)
// Store implements readmodel.Store and readmodel.Log.
type Store struct {
DB *pgxpool.Pool
Table string // "order_summary"; a rebuild writes "order_summary_rebuild"
}
// ApplyOnce: append to received_events (dedup by event id) and upsert the
// read row in the same transaction. A crash between the two is impossible;
// a redelivery finds the id and does nothing.
func (s Store) ApplyOnce(ctx context.Context, env contracts.Envelope, p readmodel.Patch) (bool, error) {
applied := false
err := pgx.BeginFunc(ctx, s.DB, func(tx pgx.Tx) error {
tag, err := tx.Exec(ctx, `
INSERT INTO received_events (event_id, source, type, subject, source_version, occurred_at, payload)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (event_id) DO NOTHING`,
env.ID, env.Source, env.Type, env.Subject, env.SourceVersion, env.Time, env.Data)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return nil // duplicate delivery
}
applied = true
return apply(ctx, tx, s.table(), p)
})
return applied, err
}
// Apply is the rebuild path (no dedup).
func (s Store) Apply(ctx context.Context, p readmodel.Patch) error {
return apply(ctx, s.DB, s.table(), p)
}
func (s Store) table() string {
if s.Table == "" {
return pgx.Identifier{"order_summary"}.Sanitize()
}
return pgx.Identifier{s.Table}.Sanitize()
}
// execer is satisfied by both pgx.Tx and *pgxpool.Pool.
type execer interface {
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
}
// apply upserts ONLY the columns the event's context owns. The row may not
// exist yet (ParcelDispatched can arrive before OrderPlaced), so every patch is an
// INSERT ... ON CONFLICT DO UPDATE, never an UPDATE that silently hits 0 rows.
func apply(ctx context.Context, db execer, table string, p readmodel.Patch) error {
var err error
switch v := p.(type) {
case readmodel.PlacedPatch:
_, err = db.Exec(ctx, fmt.Sprintf(`
INSERT INTO %s AS s (order_id, customer_id, currency, total_minor, line_count, sales_version, placed_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, now())
ON CONFLICT (order_id) DO UPDATE SET
customer_id = EXCLUDED.customer_id, currency = EXCLUDED.currency,
total_minor = EXCLUDED.total_minor, line_count = EXCLUDED.line_count,
sales_version = EXCLUDED.sales_version, placed_at = EXCLUDED.placed_at, updated_at = now()
WHERE s.sales_version < EXCLUDED.sales_version`, table),
v.OrderID, v.CustomerID, v.Currency, v.TotalMinor, v.LineCount, v.SalesVersion, v.PlacedAt)
case readmodel.DispatchedPatch:
_, err = db.Exec(ctx, fmt.Sprintf(`
INSERT INTO %s (order_id, dispatched_at, carrier, tracking_ref, updated_at)
VALUES ($1, $2, $3, $4, now())
ON CONFLICT (order_id) DO UPDATE SET
dispatched_at = EXCLUDED.dispatched_at, carrier = EXCLUDED.carrier,
tracking_ref = EXCLUDED.tracking_ref, updated_at = now()`, table),
v.OrderID, v.DispatchedAt, v.Carrier, v.TrackingRef)
case readmodel.PaidPatch:
_, err = db.Exec(ctx, fmt.Sprintf(`
INSERT INTO %s (order_id, paid_at, paid_minor, updated_at)
VALUES ($1, $2, $3, now())
ON CONFLICT (order_id) DO UPDATE SET
paid_at = EXCLUDED.paid_at, paid_minor = EXCLUDED.paid_minor, updated_at = now()`, table),
v.OrderID, v.PaidAt, v.PaidMinor)
default:
err = fmt.Errorf("unknown patch %T", p)
}
return err
}package pgstore
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"academy/microservices-data-patterns/contracts"
"academy/microservices-data-patterns/readmodel"
)
// Get is the thin read layer: one indexed lookup, no domain objects.
func (s Store) Get(ctx context.Context, orderID string) (readmodel.OrderSummary, bool, error) {
var r readmodel.OrderSummary
err := s.DB.QueryRow(ctx, fmt.Sprintf(`
SELECT order_id, coalesce(customer_id, ''), total_minor, coalesce(currency, ''), line_count,
sales_version, placed_at, dispatched_at, coalesce(carrier, ''), coalesce(tracking_ref, ''),
paid_at, paid_minor
FROM %s WHERE order_id = $1`, s.table()), orderID).Scan(
&r.OrderID, &r.CustomerID, &r.TotalMinor, &r.Currency, &r.LineCount,
&r.SalesVersion, &r.PlacedAt, &r.DispatchedAt, &r.Carrier, &r.TrackingRef,
&r.PaidAt, &r.PaidMinor)
if errors.Is(err, pgx.ErrNoRows) {
return r, false, nil
}
return r, err == nil, err
}
// ReplayAfter streams received_events in position order (a bigint identity
// column). Positions are assigned at INSERT, not at COMMIT, so a scan may see
// 11 before 10 has committed: callers pass a fence as upTo (see rebuild.go).
func (s Store) ReplayAfter(ctx context.Context, after, upTo int64, fn func(int64, contracts.Envelope) error) (int64, error) {
rows, err := s.DB.Query(ctx, `
SELECT position, event_id, source, type, subject, source_version, occurred_at, payload
FROM received_events
WHERE position > $1 AND ($2 = 0 OR position <= $2)
ORDER BY position`, after, upTo)
if err != nil {
return after, err
}
defer rows.Close()
last := after
for rows.Next() {
var pos int64
var e contracts.Envelope
if err := rows.Scan(&pos, &e.ID, &e.Source, &e.Type, &e.Subject, &e.SourceVersion, &e.Time, &e.Data); err != nil {
return last, err
}
if err := fn(pos, e); err != nil {
return last, err
}
last = pos
}
return last, rows.Err()
}Rebuild and swap under a short lock
package pgstore
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"academy/microservices-data-patterns/contracts"
"academy/microservices-data-patterns/readmodel"
)
// fence returns a position below which every received_events insert has
// committed. Identity values are assigned at INSERT time, so with several
// projector workers position 11 can commit before 10; a plain "position > last"
// scan would skip 10 forever. LOCK ... EXCLUSIVE waits for every open inserter
// (ROW EXCLUSIVE) to finish, so max(position) read under it is a safe fence.
func fence(ctx context.Context, db *pgxpool.Pool) (int64, error) {
var f int64
err := pgx.BeginFunc(ctx, db, func(tx pgx.Tx) error {
if _, err := tx.Exec(ctx, `LOCK TABLE received_events IN EXCLUSIVE MODE`); err != nil {
return err
}
return tx.QueryRow(ctx, `SELECT coalesce(max(position), 0) FROM received_events`).Scan(&f)
})
return f, err
}
// RebuildAndSwap rebuilds the read model while the live projector keeps running:
// 1. create order_summary_rebuild (LIKE order_summary) and replay the log up to
// a fence into it;
// 2. catch-up passes, each up to a new fence;
// 3. in one transaction: LOCK received_events (blocks ApplyOnce, not readers of
// the log), replay the final tail, swap the table names, commit. The RENAME
// takes ACCESS EXCLUSIVE on order_summary, so readers wait for those last
// milliseconds. Lock order matches ApplyOnce (log, then summary): no deadlock.
func RebuildAndSwap(ctx context.Context, db *pgxpool.Pool) error {
if _, err := db.Exec(ctx, `DROP TABLE IF EXISTS order_summary_rebuild;
CREATE TABLE order_summary_rebuild (LIKE order_summary INCLUDING ALL)`); err != nil {
return err
}
live := Store{DB: db}
target := Store{DB: db, Table: "order_summary_rebuild"}
var last int64
for i := 0; i < 4; i++ { // first pass + catch-up passes
f, err := fence(ctx, db)
if err != nil {
return err
}
if _, err := readmodel.Rebuild(ctx, live, last, f, target); err != nil {
return err
}
last = f // not the last row seen: rolled-back inserts leave gaps
}
return pgx.BeginFunc(ctx, db, func(tx pgx.Tx) error {
// EXCLUSIVE allows only ACCESS SHARE (plain SELECT) alongside it.
if _, err := tx.Exec(ctx, `LOCK TABLE received_events IN EXCLUSIVE MODE`); err != nil {
return err
}
tail, err := collectTail(ctx, tx, last) // complete: no inserter is open now
if err != nil {
return err
}
table := pgx.Identifier{"order_summary_rebuild"}.Sanitize()
for _, env := range tail {
patch, err := readmodel.Decode(env)
if err != nil {
return err
}
if patch != nil {
if err := apply(ctx, tx, table, patch); err != nil {
return err
}
}
}
_, err = tx.Exec(ctx, `
ALTER TABLE order_summary RENAME TO order_summary_old;
ALTER TABLE order_summary_rebuild RENAME TO order_summary;
DROP TABLE order_summary_old`)
return err
})
}
// collectTail reads the rest of the log inside the locking transaction. Rows
// are collected first because one connection cannot Exec while rows are open.
func collectTail(ctx context.Context, tx pgx.Tx, after int64) ([]contracts.Envelope, error) {
rows, err := tx.Query(ctx, `
SELECT event_id, source, type, subject, source_version, occurred_at, payload
FROM received_events WHERE position > $1 ORDER BY position`, after)
if err != nil {
return nil, err
}
defer rows.Close()
var out []contracts.Envelope
for rows.Next() {
var e contracts.Envelope
if err := rows.Scan(&e.ID, &e.Source, &e.Type, &e.Subject, &e.SourceVersion, &e.Time, &e.Data); err != nil {
return nil, err
}
out = append(out, e)
}
return out, rows.Err()
}In-memory store with the same contract
package readmodel
import (
"context"
"sync"
"academy/microservices-data-patterns/contracts"
)
// Memory is an in-memory Store, Log and Target with the same contract as the
// PostgreSQL store; tests and the demo use it.
type Memory struct {
mu sync.Mutex
rows map[string]OrderSummary
seen map[string]bool
log []contracts.Envelope
}
// NewMemory returns an empty store.
func NewMemory() *Memory {
return &Memory{rows: map[string]OrderSummary{}, seen: map[string]bool{}}
}
// ApplyOnce appends to the log and applies the patch atomically.
func (m *Memory) ApplyOnce(_ context.Context, env contracts.Envelope, p Patch) (bool, error) {
m.mu.Lock()
defer m.mu.Unlock()
if m.seen[env.ID] {
return false, nil
}
m.seen[env.ID] = true
m.log = append(m.log, env)
m.apply(p)
return true, nil
}
// Apply applies a patch without dedup (rebuild target).
func (m *Memory) Apply(_ context.Context, p Patch) error {
m.mu.Lock()
defer m.mu.Unlock()
m.apply(p)
return nil
}
// apply mirrors the SQL upserts: create the row if missing, set only the
// columns the patch owns, guard the Sales columns by version.
func (m *Memory) apply(p Patch) {
r := m.rows[p.orderID()]
r.OrderID = p.orderID()
switch v := p.(type) {
case PlacedPatch:
if v.SalesVersion <= r.SalesVersion {
return // stale or replayed older Sales fact
}
at := v.PlacedAt
r.CustomerID, r.Currency, r.TotalMinor, r.LineCount = v.CustomerID, v.Currency, v.TotalMinor, v.LineCount
r.SalesVersion, r.PlacedAt = v.SalesVersion, &at
case DispatchedPatch:
at := v.DispatchedAt
r.DispatchedAt, r.Carrier, r.TrackingRef = &at, v.Carrier, v.TrackingRef
case PaidPatch:
at := v.PaidAt
r.PaidAt, r.PaidMinor = &at, v.PaidMinor
}
m.rows[r.OrderID] = r
}
// Get reads one row.
func (m *Memory) Get(_ context.Context, id string) (OrderSummary, bool, error) {
m.mu.Lock()
defer m.mu.Unlock()
r, ok := m.rows[id]
return r, ok, nil
}
// ReplayAfter walks positions after+1 .. upTo (positions start at 1; upTo 0 = all).
func (m *Memory) ReplayAfter(_ context.Context, after, upTo int64, fn func(int64, contracts.Envelope) error) (int64, error) {
m.mu.Lock()
log := append([]contracts.Envelope(nil), m.log...)
m.mu.Unlock()
end := len(log)
if upTo > 0 && int(upTo) < end {
end = int(upTo)
}
last := after
for i := int(after); i < end; i++ {
if err := fn(int64(i+1), log[i]); err != nil {
return last, err
}
last = int64(i + 1)
}
return last, nil
}Read-your-writes: wait for the version token
// Package query is the read API. WaitFor implements read-your-writes on an
// asynchronously updated read model: the client sends the version token it got
// from the command, and the query waits briefly for the projection to reach it.
package query
import (
"context"
"errors"
"time"
"academy/microservices-data-patterns/readmodel"
)
// ErrNotYetProjected tells the HTTP layer to answer 202 with Retry-After, or
// the UI to keep its optimistic copy.
var ErrNotYetProjected = errors.New("read model has not reached the requested version")
// Reader is the read store's query port.
type Reader interface {
Get(ctx context.Context, orderID string) (readmodel.OrderSummary, bool, error)
}
// WaitFor polls until SalesVersion >= minVersion or the budget runs out.
// The budget stays small (a few hundred ms): this is a UX aid, not a lock.
func WaitFor(ctx context.Context, r Reader, orderID string, minVersion int64, budget, every time.Duration) (readmodel.OrderSummary, error) {
deadline := time.Now().Add(budget)
for {
row, ok, err := r.Get(ctx, orderID)
if err != nil {
return readmodel.OrderSummary{}, err
}
if ok && row.SalesVersion >= minVersion {
return row, nil
}
if time.Now().After(deadline) {
return row, ErrNotYetProjected
}
select {
case <-ctx.Done():
return row, ctx.Err()
case <-time.After(every):
}
}
}A runnable demo
// Command demo runs the write side and the projector in one process with the
// in-memory store: place an order, deliver three contexts' events out of order
// and twice, read with a version token, then rebuild and compare.
package main
import (
"context"
"encoding/json"
"fmt"
"time"
"academy/microservices-data-patterns/contracts"
"academy/microservices-data-patterns/query"
"academy/microservices-data-patterns/readmodel"
"academy/microservices-data-patterns/sales"
)
type outbox struct{ events []contracts.Envelope }
// Add stands in for "INSERT order + INSERT outbox row" in one transaction.
func (o *outbox) Add(_ context.Context, _ *sales.Order, evs []sales.Placed) error {
for _, e := range evs {
env, err := contracts.New("evt-placed-"+e.OrderID, "/sales", contracts.TypeOrderPlacedV1, e.OrderID, e.At, e.Version,
contracts.OrderPlacedV1{OrderID: e.OrderID, CustomerID: e.CustomerID, TotalMinor: e.TotalMinor, Currency: e.Currency, LineCount: e.LineCount})
if err != nil {
return err
}
o.events = append(o.events, env)
}
return nil
}
type printLag struct{}
func (printLag) Observe(src string, d time.Duration) { fmt.Printf(" lag %-11s %v\n", src, d) }
func main() {
ctx := context.Background()
t0 := time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)
ob := &outbox{}
h := sales.PlaceOrderHandler{Repo: ob, Now: func() time.Time { return t0 }}
ack, err := h.Handle(ctx, sales.PlaceOrder{OrderID: "o-1", CustomerID: "c-9", Currency: "EUR",
Lines: []sales.Line{{SKU: "MUG", Quantity: 2, PriceMinor: 1250}}})
if err != nil {
panic(err)
}
fmt.Printf("1 command acknowledged: order=%s version=%d\n", ack.OrderID, ack.Version)
store := readmodel.NewMemory()
p := &readmodel.Projector{Store: store, Lag: printLag{}, Now: func() time.Time { return t0.Add(4 * time.Minute) }}
_, err = query.WaitFor(ctx, store, ack.OrderID, ack.Version, 20*time.Millisecond, 5*time.Millisecond)
fmt.Printf("2 read before projection: %v\n", err)
dispatched, _ := contracts.New("evt-ship-1", "/fulfilment", contracts.TypeParcelDispatchedV1, "o-1", t0.Add(3*time.Minute), 4,
contracts.ParcelDispatchedV1{OrderID: "o-1", ShipmentID: "s-7", Carrier: "DHL", TrackingRef: "JD0042"})
paid, _ := contracts.New("evt-paid-1", "/billing", contracts.TypeInvoicePaidV1, "o-1", t0.Add(time.Minute), 2,
contracts.InvoicePaidV1{OrderID: "o-1", InvoiceID: "inv-3", PaidMinor: 2500})
fmt.Println("3 deliveries: dispatched, dispatched (duplicate), placed, paid")
for _, e := range []contracts.Envelope{dispatched, dispatched, ob.events[0], paid} {
if err := p.Handle(ctx, e); err != nil {
panic(err)
}
}
row, err := query.WaitFor(ctx, store, ack.OrderID, ack.Version, 20*time.Millisecond, 5*time.Millisecond)
if err != nil {
panic(err)
}
b, _ := json.Marshal(row)
fmt.Printf("4 read with token v%d: status=%s %s\n", ack.Version, row.Status(), b)
fresh := readmodel.NewMemory()
last, err := readmodel.Rebuild(ctx, store, 0, 0, fresh)
if err != nil {
panic(err)
}
rebuilt, _, _ := fresh.Get(ctx, "o-1")
rb, _ := json.Marshal(rebuilt)
fmt.Printf("5 rebuilt from %d logged events, identical=%v\n", last, string(rb) == string(b))
}Wrong: CRUD PUT, a CQS-violating query, a cross-schema join
// Package wrong shows the two shapes this chapter argues against.
package wrong
import "database/sql"
// OrderDTO is the whole record, sent back and forth by a CRUD screen.
type OrderDTO struct {
ID string
Status string // the client may send "dispatched" directly
TotalMinor int64
Carrier string
}
// SaveOrder is a CRUD "PUT": the intent (pay? dispatch? correct the address?) is
// lost, any field can be overwritten, and the rule "dispatch only when paid" has no
// place to live.
func SaveOrder(db *sql.DB, in OrderDTO) error {
_, err := db.Exec(`UPDATE orders SET status=$2, total_minor=$3, carrier=$4 WHERE id=$1`,
in.ID, in.Status, in.TotalMinor, in.Carrier)
return err
}
// NextShipmentAndMark both answers a question and changes state (a CQS
// violation): calling it twice from a dashboard "just to look" marks two orders.
func NextShipmentAndMark(db *sql.DB) (string, error) {
var id string
err := db.QueryRow(`UPDATE orders SET status='picking'
WHERE id = (SELECT id FROM orders WHERE status='paid' ORDER BY placed_at LIMIT 1)
RETURNING id`).Scan(&id)
return id, err
}
// SummaryByJoiningOtherServices joins tables that belong to Fulfilment and
// Billing: a shared database in disguise.
func SummaryByJoiningOtherServices(db *sql.DB, orderID string) (*sql.Row, error) {
return db.QueryRow(`SELECT o.id, s.tracking_ref, i.paid_at
FROM sales.orders o
LEFT JOIN fulfilment.shipments s ON s.order_id = o.id
LEFT JOIN billing.invoices i ON i.order_id = o.id
WHERE o.id = $1`, orderID), nil
}The Go angle
- pgx ("a pure Go driver and toolkit for PostgreSQL") gives
pgx.BeginFuncfor the one-transaction dedup-and-upsert,CommandTag.RowsAffected()to detect duplicates, andpgx.Identifier{…}.Sanitize()for the table name a rebuild writes to. - sqlc ("sqlc generates fully type-safe idiomatic Go code from SQL") fits the thin read layer well: the read side is plain SQL, and generated methods keep it typed. The code above is hand-written; with sqlc you would put the upserts in a
queries.sqlfile and call the generated methods inside the same transaction. - Watermill has a
cqrspackage ("We segregate the responsibility between commands (write requests) and queries (read requests)") with a command bus, event bus andEventProcessor/NewEventHandlerover Kafka, RabbitMQ, SQL and others. It handles routing and marshalling; idempotency and the read store remain your code, exactly as above. - Go interfaces make the store swappable: the same
Projectorruns againstreadmodel.Memoryin tests andpgstore.Storein production. - Keep projector concurrency per key: one goroutine per partition (or per order-id hash) preserves per-order sequencing and avoids row-lock contention.
Laravel
Laravel 13, PHP 8.4. In a modular monolith the outbox relay dispatches IntegrationEventReceived in process; in the microservice form the read-side service's broker consumer decodes each message with IntegrationEvent::fromArray and dispatches the same event. The projector does not know the difference.
Contracts
<?php
declare(strict_types=1);
namespace App\Modules\Contracts;
use DateTimeImmutable;
/**
* The envelope every context publishes (CloudEvents attribute names).
* sourceVersion is the publishing aggregate's version after the change.
*/
final readonly class IntegrationEvent
{
public const ORDER_PLACED_V1 = 'sales.order.placed.v1';
public const PARCEL_DISPATCHED_V1 = 'fulfilment.parcel.dispatched.v1';
public const INVOICE_PAID_V1 = 'billing.invoice.paid.v1';
/** @param array<string, mixed> $data */
public function __construct(
public string $id,
public string $source,
public string $type,
public string $subject,
public DateTimeImmutable $time,
public int $sourceVersion,
public array $data,
) {
}
/** @param array<string, mixed> $row a received_events row or a decoded message body */
public static function fromArray(array $row): self
{
return new self(
id: (string) $row['id'],
source: (string) $row['source'],
type: (string) $row['type'],
subject: (string) $row['subject'],
time: new DateTimeImmutable((string) $row['time']),
sourceVersion: (int) $row['sourceversion'],
data: is_array($row['data']) ? $row['data'] : json_decode((string) $row['data'], true, flags: JSON_THROW_ON_ERROR),
);
}
}<?php
declare(strict_types=1);
namespace App\Modules\Contracts;
use Illuminate\Foundation\Events\Dispatchable;
/**
* Dispatched by whoever delivers integration events into this process:
* - modular monolith: the outbox relay command, in-process;
* - microservices: the broker consumer of the read-side service
* (RabbitMQ/Kafka message body decoded with IntegrationEvent::fromArray).
*/
final class IntegrationEventReceived
{
use Dispatchable;
public function __construct(public readonly IntegrationEvent $event)
{
}
}Write side: CQS on the aggregate, a command, an action, a task-based endpoint
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
use DateTimeImmutable;
use DomainException;
/**
* Write model. Commands (place, markPaid, dispatch) change state and return
* nothing; queries (status, version, total, canDispatch) return data and change
* nothing. Screens never read this class: they read OrderSummary.
*/
final class Order
{
/** @var list<array<string, mixed>> */
private array $recorded = [];
/** @param list<array{sku: string, quantity: int, price_minor: int}> $lines */
private function __construct(
public readonly string $id,
private readonly string $customerId,
private readonly array $lines,
private readonly string $currency,
private string $status,
private int $version,
) {
}
/** @param list<array{sku: string, quantity: int, price_minor: int}> $lines */
public static function place(string $id, string $customerId, string $currency, array $lines, DateTimeImmutable $now): self
{
if ($lines === []) {
throw new DomainException('An order needs at least one line.');
}
$order = new self($id, $customerId, $lines, $currency, 'placed', 1);
$order->recorded[] = [
'type' => 'OrderPlaced',
'order_id' => $id,
'customer_id' => $customerId,
'total_minor' => $order->total(),
'currency' => $currency,
'line_count' => count($lines),
'version' => $order->version,
'at' => $now->format(DATE_ATOM),
];
return $order;
}
public function markPaid(): void
{
if ($this->status !== 'placed') {
throw new DomainException('Only a placed order can be paid.');
}
$this->status = 'paid';
$this->version++;
}
public function dispatch(): void
{
if (! $this->canDispatch()) {
throw new DomainException('An unpaid order cannot be dispatched.');
}
$this->status = 'dispatched';
$this->version++;
}
public function status(): string
{
return $this->status;
}
public function version(): int
{
return $this->version;
}
public function canDispatch(): bool
{
return $this->status === 'paid';
}
public function total(): int
{
return array_sum(array_map(fn (array $l): int => $l['quantity'] * $l['price_minor'], $this->lines));
}
public function customerId(): string
{
return $this->customerId;
}
public function currency(): string
{
return $this->currency;
}
/** @return list<array<string, mixed>> */
public function pullEvents(): array
{
[$events, $this->recorded] = [$this->recorded, []];
return $events;
}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Application;
/** A command: an intent in the imperative, carrying only what the behaviour needs. */
final readonly class PlaceOrder
{
/** @param list<array{sku: string, quantity: int, price_minor: int}> $lines */
public function __construct(
public string $orderId, // client-generated UUID
public string $customerId,
public string $currency,
public array $lines,
) {
}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Application;
use App\Modules\Contracts\IntegrationEvent;
use App\Modules\Sales\Domain\Order;
use DateTimeImmutable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/**
* The command handler ("action"). It writes the aggregate and the outbox row
* in ONE transaction and returns only the new version: a consistency token,
* not read data. The outbox relay (see the Outbox chapter) delivers the event.
*/
final class PlaceOrderAction
{
public function __invoke(PlaceOrder $cmd): int
{
$order = Order::place($cmd->orderId, $cmd->customerId, $cmd->currency, $cmd->lines, new DateTimeImmutable());
DB::transaction(function () use ($order): void {
DB::table('sales_orders')->insert([
'id' => $order->id,
'customer_id' => $order->customerId(),
'currency' => $order->currency(),
'total_minor' => $order->total(),
'status' => $order->status(),
'version' => $order->version(),
]);
foreach ($order->pullEvents() as $e) {
DB::table('sales_outbox')->insert([
'id' => (string) Str::uuid7(),
'type' => IntegrationEvent::ORDER_PLACED_V1,
'subject' => $e['order_id'],
'source_version' => $e['version'],
'occurred_at' => $e['at'],
'payload' => json_encode([
'orderId' => $e['order_id'],
'customerId' => $e['customer_id'],
'totalMinor' => $e['total_minor'],
'currency' => $e['currency'],
'lineCount' => $e['line_count'],
], JSON_THROW_ON_ERROR),
]);
}
});
return $order->version();
}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Http;
use App\Modules\Sales\Application\PlaceOrder;
use App\Modules\Sales\Application\PlaceOrderAction;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
/**
* Task-based endpoint: POST /orders (place), not PUT /orders/{id} with the
* whole record. The response carries a version token and where to read.
*/
final class OrderCommandController
{
public function place(Request $request, PlaceOrderAction $placeOrder): JsonResponse
{
$valid = $request->validate([
'order_id' => ['required', 'uuid'],
'currency' => ['required', 'string', 'size:3'],
'lines' => ['required', 'array', 'min:1'],
'lines.*.sku' => ['required', 'string'],
'lines.*.quantity' => ['required', 'integer', 'min:1'],
'lines.*.price_minor' => ['required', 'integer', 'min:0'],
]);
$version = $placeOrder(new PlaceOrder(
orderId: $valid['order_id'],
customerId: (string) $request->user()->getAuthIdentifier(),
currency: $valid['currency'],
lines: $valid['lines'],
));
$readUrl = route('order-summaries.show', ['orderId' => $valid['order_id'], 'min_version' => $version]);
return response()->json(['order_id' => $valid['order_id'], 'version' => $version], 202)
->header('Location', $readUrl);
}
}Read model table and log
<?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
{
protected $connection = 'read_model';
public function up(): void
{
Schema::create('received_events', function (Blueprint $table): void {
$table->id('position'); // replay order
$table->string('event_id')->unique(); // idempotency key
$table->string('source');
$table->string('type');
$table->string('subject')->index();
$table->unsignedBigInteger('source_version');
$table->timestampTz('occurred_at');
$table->timestampTz('received_at')->useCurrent();
$table->jsonb('payload');
});
Schema::create('order_summary', function (Blueprint $table): void {
$table->string('order_id')->primary();
// Sales columns
$table->string('customer_id')->nullable();
$table->char('currency', 3)->nullable();
$table->bigInteger('total_minor')->default(0);
$table->integer('line_count')->default(0);
$table->unsignedBigInteger('sales_version')->default(0);
$table->timestampTz('placed_at')->nullable();
// Fulfilment columns
$table->timestampTz('dispatched_at')->nullable();
$table->string('carrier')->nullable();
$table->string('tracking_ref')->nullable();
// Billing columns
$table->timestampTz('paid_at')->nullable();
$table->bigInteger('paid_minor')->default(0);
$table->timestampTz('updated_at')->useCurrent();
$table->index(['customer_id', 'placed_at']);
});
}
public function down(): void
{
Schema::dropIfExists('order_summary');
Schema::dropIfExists('received_events');
}
};<?php
declare(strict_types=1);
namespace App\Modules\OrderSummary;
use Illuminate\Database\Eloquent\Model;
/**
* Read model row. Read-only for everything except the projector.
* It lives on its own connection so a read/write split elsewhere does not
* add a second, invisible lag on top of the projection lag.
*/
final class OrderSummary extends Model
{
protected $connection = 'read_model';
protected $table = 'order_summary';
protected $primaryKey = 'order_id';
protected $keyType = 'string';
public $incrementing = false;
public $timestamps = false; // the projector sets updated_at itself
protected $guarded = [];
protected function casts(): array
{
return [
'placed_at' => 'immutable_datetime',
'dispatched_at' => 'immutable_datetime',
'paid_at' => 'immutable_datetime',
'sales_version' => 'integer',
'total_minor' => 'integer',
'paid_minor' => 'integer',
];
}
/** Status is derived from which facts arrived, so arrival order does not matter. */
public function status(): string
{
return match (true) {
$this->placed_at === null => 'pending',
$this->dispatched_at !== null && $this->paid_at !== null => 'completed',
$this->dispatched_at !== null => 'dispatched',
$this->paid_at !== null => 'paid',
default => 'placed',
};
}
}Projector and queued listener: insertOrIgnore dedup, whereKey patches
<?php
declare(strict_types=1);
namespace App\Modules\OrderSummary;
use App\Modules\Contracts\IntegrationEvent;
use Illuminate\Database\Eloquent\Builder;
/**
* Pure projection logic: one event in, one row patched. No dedup here; the
* listener (live) and the log (rebuild) provide it. Each event type writes
* ONLY the columns its context owns.
*/
final class OrderSummaryProjector
{
public function __construct(private readonly string $table = 'order_summary')
{
}
public function handles(string $type): bool
{
return in_array($type, [
IntegrationEvent::ORDER_PLACED_V1,
IntegrationEvent::PARCEL_DISPATCHED_V1,
IntegrationEvent::INVOICE_PAID_V1,
], true);
}
public function apply(IntegrationEvent $e): void
{
if (! $this->handles($e->type)) {
return; // unknown or newer types are ignored, not fatal
}
// The row may not exist yet: ParcelDispatched can arrive before OrderPlaced.
$this->rows()->insertOrIgnore(['order_id' => $e->subject, 'updated_at' => now()]);
$d = $e->data;
match ($e->type) {
IntegrationEvent::ORDER_PLACED_V1 => $this->rows()
->whereKey($e->subject)
->where('sales_version', '<', $e->sourceVersion) // stale Sales facts lose
->update([
'customer_id' => $d['customerId'],
'currency' => $d['currency'],
'total_minor' => $d['totalMinor'],
'line_count' => $d['lineCount'],
'sales_version' => $e->sourceVersion,
'placed_at' => $e->time,
'updated_at' => now(),
]),
IntegrationEvent::PARCEL_DISPATCHED_V1 => $this->rows()
->whereKey($e->subject)
->update([
'dispatched_at' => $e->time,
'carrier' => $d['carrier'],
'tracking_ref' => $d['trackingRef'],
'updated_at' => now(),
]),
IntegrationEvent::INVOICE_PAID_V1 => $this->rows()
->whereKey($e->subject)
->update([
'paid_at' => $e->time,
'paid_minor' => $d['paidMinor'],
'updated_at' => now(),
]),
};
}
/** @return Builder<OrderSummary> */
private function rows(): Builder
{
return (new OrderSummary())->setTable($this->table)->newQuery();
}
}<?php
declare(strict_types=1);
namespace App\Modules\OrderSummary;
use App\Modules\Contracts\IntegrationEventReceived;
use Illuminate\Contracts\Queue\ShouldQueueAfterCommit;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
/**
* Queued projection handler. Register it in a module service provider:
* Event::listen(IntegrationEventReceived::class, ProjectOrderSummary::class);
*
* Idempotency: the event id goes into received_events (UNIQUE event_id) in
* the same transaction as the row patch. A redelivery inserts 0 rows and stops.
*/
final class ProjectOrderSummary implements ShouldQueueAfterCommit
{
use InteractsWithQueue;
public string $queue = 'projections';
public int $tries = 10;
public function __construct(private readonly OrderSummaryProjector $projector)
{
}
/** @return list<int> */
public function backoff(): array
{
return [1, 5, 30, 120];
}
public function handle(IntegrationEventReceived $received): void
{
$e = $received->event;
if (! $this->projector->handles($e->type)) {
return;
}
$applied = DB::connection('read_model')->transaction(function () use ($e): bool {
$inserted = DB::connection('read_model')->table('received_events')->insertOrIgnore([
'event_id' => $e->id,
'source' => $e->source,
'type' => $e->type,
'subject' => $e->subject,
'source_version' => $e->sourceVersion,
'occurred_at' => $e->time,
'payload' => json_encode($e->data, JSON_THROW_ON_ERROR),
]);
if ($inserted === 0) {
return false; // duplicate delivery
}
$this->projector->apply($e);
return true;
});
if ($applied) {
// Projection lag: now minus the event's own time. Export it as a metric.
Log::info('projection.applied', [
'projection' => 'order_summary',
'source' => $e->source,
'lag_ms' => (int) ((microtime(true) - (float) $e->time->format('U.u')) * 1000),
]);
}
}
}Rebuild command
<?php
declare(strict_types=1);
namespace App\Modules\OrderSummary;
use App\Modules\Contracts\IntegrationEvent;
use Illuminate\Console\Command;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Support\Facades\DB;
/**
* php artisan order-summary:rebuild
*
* Replays received_events into order_summary_rebuild while the live projector
* keeps running, catches up, then swaps tables under a short lock (PostgreSQL).
* Positions are assigned at INSERT, not COMMIT, so every pass replays only up
* to a fence read under LOCK ... EXCLUSIVE (all earlier inserts have committed).
*/
final class RebuildOrderSummaries extends Command
{
protected $signature = 'order-summary:rebuild {--chunk=1000}';
protected $description = 'Rebuild the OrderSummary read model from the received-events log';
public function handle(): int
{
$db = DB::connection('read_model');
$db->statement('DROP TABLE IF EXISTS order_summary_rebuild');
$db->statement('CREATE TABLE order_summary_rebuild (LIKE order_summary INCLUDING ALL)');
$projector = new OrderSummaryProjector('order_summary_rebuild');
$last = 0;
for ($pass = 0; $pass < 4; $pass++) { // first pass + catch-up passes
$fence = $this->fence($db);
$this->replay($db, $projector, $last, $fence);
$last = $fence; // not the last row seen: rolled-back inserts leave gaps
}
$this->info("replayed up to position {$last}");
$db->transaction(function () use ($db, $projector, $last): void {
// Blocks new inserts into the log (live listener) but not plain SELECTs.
$db->statement('LOCK TABLE received_events IN EXCLUSIVE MODE');
$this->replay($db, $projector, $last, null); // complete: no inserter is open
// RENAME takes ACCESS EXCLUSIVE: readers of order_summary wait until COMMIT.
$db->statement('ALTER TABLE order_summary RENAME TO order_summary_old');
$db->statement('ALTER TABLE order_summary_rebuild RENAME TO order_summary');
$db->statement('DROP TABLE order_summary_old');
});
$this->info('swapped');
return self::SUCCESS;
}
/** A position below which every log insert has committed. */
private function fence(ConnectionInterface $db): int
{
return (int) $db->transaction(function () use ($db): int {
$db->statement('LOCK TABLE received_events IN EXCLUSIVE MODE');
return (int) $db->table('received_events')->max('position');
});
}
private function replay(ConnectionInterface $db, OrderSummaryProjector $projector, int $after, ?int $upTo): int
{
$last = $after;
$db->table('received_events')
->where('position', '>', $after)
->when($upTo !== null, fn ($q) => $q->where('position', '<=', $upTo))
->lazyById((int) $this->option('chunk'), 'position')
->each(function (object $row) use ($projector, &$last): void {
$projector->apply(IntegrationEvent::fromArray([
'id' => $row->event_id,
'source' => $row->source,
'type' => $row->type,
'subject' => $row->subject,
'time' => $row->occurred_at,
'sourceversion' => $row->source_version,
'data' => $row->payload,
]));
$last = (int) $row->position;
});
return $last;
}
}Query endpoint with the version token
<?php
declare(strict_types=1);
namespace App\Modules\OrderSummary;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
/**
* GET /order-summaries/{orderId}?min_version=1
* Read-your-writes on an async read model: wait briefly for the projection
* to reach the version the command returned, else answer 202 + Retry-After.
*/
final class OrderSummaryController
{
public function show(Request $request, string $orderId): JsonResponse
{
$minVersion = (int) $request->query('min_version', '0');
$deadline = microtime(true) + 0.3; // a UX budget, not a lock
do {
$row = OrderSummary::query()->whereKey($orderId)->first();
if ($row !== null && $row->sales_version >= $minVersion) {
return response()->json([
'order_id' => $row->order_id,
'status' => $row->status(),
'total_minor' => $row->total_minor,
'currency' => $row->currency,
'carrier' => $row->carrier,
'tracking_ref' => $row->tracking_ref,
'sales_version' => $row->sales_version,
]);
}
usleep(50_000);
} while (microtime(true) < $deadline);
return response()->json(['order_id' => $orderId, 'status' => 'processing'], 202)
->header('Retry-After', '1');
}
}Pest tests: replay fixture, duplicates, pending, rebuild, snapshot
<?php
declare(strict_types=1);
use App\Modules\Contracts\IntegrationEvent;
use App\Modules\Contracts\IntegrationEventReceived;
use App\Modules\OrderSummary\OrderSummary;
use App\Modules\OrderSummary\ProjectOrderSummary;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
// Runs on PostgreSQL (the rebuild uses CREATE TABLE ... LIKE and LOCK TABLE);
// phpunit.xml points the read_model connection at the test database.
uses(RefreshDatabase::class);
/** Replay fixture: three contexts, delivered out of order (dispatched first). */
function fixture(): array
{
$e = fn (string $id, string $src, string $type, string $at, int $v, array $data) => new IntegrationEvent(
$id, $src, $type, 'o-1', new DateTimeImmutable($at), $v, $data,
);
return [
$e('evt-ship-1', '/fulfilment', IntegrationEvent::PARCEL_DISPATCHED_V1, '2026-11-25T10:03:00Z', 4,
['orderId' => 'o-1', 'carrier' => 'DHL', 'trackingRef' => 'JD0042']),
$e('evt-placed-1', '/sales', IntegrationEvent::ORDER_PLACED_V1, '2026-11-25T10:00:00Z', 1,
['orderId' => 'o-1', 'customerId' => 'c-9', 'totalMinor' => 2500, 'currency' => 'EUR', 'lineCount' => 1]),
$e('evt-paid-1', '/billing', IntegrationEvent::INVOICE_PAID_V1, '2026-11-25T10:01:00Z', 2,
['orderId' => 'o-1', 'paidMinor' => 2500]),
];
}
function project(array $events): void
{
$listener = app(ProjectOrderSummary::class);
foreach ($events as $event) {
$listener->handle(new IntegrationEventReceived($event));
}
}
it('converges whatever the arrival order', function () {
project(fixture());
$row = OrderSummary::query()->whereKey('o-1')->firstOrFail();
expect($row->status())->toBe('completed')
->and($row->total_minor)->toBe(2500)
->and($row->carrier)->toBe('DHL');
});
it('ignores a duplicate delivery', function () {
project([...fixture(), ...fixture()]);
expect(DB::connection('read_model')->table('received_events')->count())->toBe(3);
});
it('shows pending when only a downstream fact has arrived', function () {
project([fixture()[0]]);
expect(OrderSummary::query()->whereKey('o-1')->firstOrFail()->status())->toBe('pending');
});
it('rebuilds to the same row', function () {
project(fixture());
$before = OrderSummary::query()->whereKey('o-1')->firstOrFail()->toArray();
$this->artisan('order-summary:rebuild')->assertSuccessful();
$after = OrderSummary::query()->whereKey('o-1')->firstOrFail()->toArray();
expect(collect($after)->except('updated_at')->all())
->toBe(collect($before)->except('updated_at')->all());
});
it('matches the snapshot', function () {
project(fixture());
$row = OrderSummary::query()->whereKey('o-1')->firstOrFail();
expect(collect($row->toArray())->except('updated_at')->put('status', $row->status())->toJson(JSON_PRETTY_PRINT))
->toMatchSnapshot(); // pest-plugin-snapshots style golden file
});Wrong: the CRUD controller and the cross-context join
<?php
declare(strict_types=1);
namespace App\Wrong;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
/**
* Anti-patterns this chapter replaces:
* 1. PUT the whole record: intent is lost, any field can be overwritten.
* 2. The "summary" joins Fulfilment's and Billing's tables directly.
*/
final class OrderCrudController
{
public function update(Request $request, string $id): JsonResponse
{
DB::table('orders')->where('id', $id)->update($request->only('status', 'total_minor', 'carrier'));
return response()->json(DB::table('orders')->find($id)); // a query riding on a command
}
public function summary(string $id): JsonResponse
{
return response()->json(DB::table('sales.orders as o')
->leftJoin('fulfilment.shipments as s', 's.order_id', '=', 'o.id')
->leftJoin('billing.invoices as i', 'i.order_id', '=', 'o.id')
->where('o.id', $id)
->first(['o.id', 's.tracking_ref', 'i.paid_at']));
}
}The Laravel angle
- Queued listeners and transactions. The docs warn that queued listeners dispatched inside a transaction "may be processed by the queue before the database transaction has committed".
ShouldQueueAfterCommiton the listener (orafter_commiton the queue connection) prevents a projector from reading rows that do not exist yet. It does not make delivery exactly-once; thereceived_eventsunique key does. insertOrIgnorereturns the number of inserted rows, which is the duplicate check; the docs note it ignores duplicate-record errors (and on MySQL bypasses strict mode, so validate payloads first).whereKey(Eloquent builder) targets the read row by primary key; combined withwhere('sales_version', '<', …)it is the version guard.- Read/write split.
stickygives read-your-writes within one request on a replica setup, which is a different lag from projection lag; we put the read model on its ownread_modelconnection so the two do not stack invisibly. - Scout: "Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records." Good for indexing one owner's model, not for a read model that joins three owners (feed a custom engine or index from the projector instead).
- Event discovery only scans
app/Listenersby default; register module listeners withEvent::listenin the module's service provider. ShouldBeUniqueprevents two copies of the same job from being queued; it is not event dedup and has a lock TTL.
Solving the classic problems
"This screen needs data from three services"
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| API composition | BFF calls Sales, Fulfilment, Billing in parallel, joins in memory | Live data, no new store | Latency of the slowest, partial answers, no cross-owner filters |
| Read model (OrderSummary) | Project the three contexts' events into one table | One fast query, filters and paging | Lag, projector, replay log, rebuild tooling |
| Shared database join | JOIN across schemas | Easy today | Couples three teams' schemas; forbidden |
| Ask Sales to store Billing's data in its own model | Sales listens to InvoicePaid and updates orders.paid_at | No new service | Sales' write model now carries others' facts; acceptable only as a small local copy |
Preferred: composition for the order detail page; OrderSummary for the list. The code is Go / Laravel.
"The list still shows the old status"
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Version token + wait | Command returns version, query takes min_version | Exact for the actor | Needs the token to travel with the client |
| UI optimism | Client inserts its own row marked "processing" | Instant | Must reconcile and handle rejection |
| "As of" timestamp | Show when the row was last updated | Honest | Users still see stale data |
| Synchronous projection | Update read table in the command's transaction | Never stale | Same DB only; slower writes |
"A deleted item is still in search"
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Deletes as events | ProductDeleted projected like any other event | Same pipeline | Must never be dropped |
| Tombstone + version guard | Keep deleted_at and version; apply only newer events | Prevents resurrection | Tombstones need periodic cleanup |
| External versioning in the index | Elasticsearch/OpenSearch version_type=external | Index rejects older writes | Product-specific |
| Hard filter at query time | Check the owner for sensitive deletions | Correct for legal removals | A call per result page |
"We changed the read model's shape"
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Rebuild and swap | Replay log into _rebuild up to fences, catch up, rename | Readers wait only for the rename | Needs a complete log; fence logic |
| Side-by-side v2 | New projector writes order_summary_v2; readers switch by flag | Rollback by flipping back | Two projectors for a while |
| In-place migration | ALTER TABLE + backfill from the log | Simple for added columns | Risky for semantic changes |
"The projector fell behind, or was wrong for a day"
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Catch-up | Restart from the last committed position; broker retention covers the gap | Automatic | Lag spike, needs retention ≥ outage |
| Scale out by key | More partitions/workers, key = order id | Restores throughput | Rebalancing; ordering only per key |
| Rebuild from the log | order-summary:rebuild after fixing the bug | Repairs every row | Duration grows with the log; snapshot the log for very large histories |
| Dead-letter poison events | Retry with backoff, then DLQ (DLQ) | Stream keeps flowing | Someone must process the DLQ |
"Finance wants to join everything"
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Warehouse fed by CDC/events | Debezium or event topics into a warehouse | No load on services; modelled data | Minutes of lag; a data team |
| Reporting database (Fowler) | Nightly copy reshaped for reports | Simple | Yesterday's data |
| Point BI at replicas | Direct queries | None that last | Breaks on renames; replay conflicts |
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| CRUD-shaped context (Identity users, Catalog admin) | CQS only (step 1) | Task-based endpoints for the few real actions | Fowler: CRUD systems "should be done in that style" |
| One owner, read and write shapes differ | CQRS step 2 or 3 (thin read layer, read tables in same DB) | Synchronous projection | No lag, no new infrastructure |
| Keyed detail page across owners | API composition | Batched calls, timeouts, partial results | Fresh, simple |
| List/filter/page across owners | Event-driven read model (step 4) | Dedup log, upserts, version guard, token | Only a local copy can filter on others' fields |
| Free-text search | Search index fed by events or CDC | Tombstones, external versions | SQL is the wrong engine |
| Owner cannot publish events yet | CDC (Debezium) or logical replication of a contract table | Outbox table as the CDC source | Ownership kept via a published table |
| Reports across everything | Warehouse via CDC/events | Modelled marts | Keeps analytics off production |
| Audit of every change is a requirement | Consider event sourcing for that context | Projections for every read | History by construction |
| Read scale for one owner's own data | Read replicas | sticky, lag guard | Same model, more readers |
| Same-database modular monolith report | Materialized view | REFRESH … CONCURRENTLY on a schedule | Cheapest; staleness acceptable |
In architecture: from a single process to a distributed system
Monolith: one process, one database
Everything is one schema and one transaction, so most of this page reduces to CQS and, at most, CQRS step 2. Simple example: an OrderQueries class with SQL for the "My orders" page next to PlaceOrderAction; both use the same tables and there is no lag. Complex example: a slow dashboard query moves into a read table updated in the same transaction as the order (step 3), or into a materialized view refreshed every five minutes. Keep commands returning only a version so the code is ready for step 4.
Modular monolith and multiple databases
Modules own schemas (sales, fulfilment, billing) and may not join each other's tables; a module reads another module's data through its public API (in process) or through events. Simple example: the Sales module's OrderSummary read side listens to in-process IntegrationEventReceived events dispatched by the outbox relay; the queued listener and the received_events table are the same code that will run in the microservice. Complex example: a reporting schema with materialized views across modules is tolerated as a read-only contract owned by the reporting team, with tests that fail when a module renames a column the view uses; it is removed when the modules become services.
Microservices: no joins, no shared transactions
Each service has its own database; queries across owners use composition or read models; writes use sagas and outboxes. Example flow for "My orders":
1 Client -> Sales: POST /orders {order_id: o-1} -> COMMIT orders + sales_outbox
2 Sales relay -> broker: sales.order.placed.v1 (key o-1) <- 202 {version: 1}
3 Billing consumes OrderPlaced, creates invoice; payment -> billing.invoice.paid.v1
4 Fulfilment consumes InvoicePaid, dispatches -> fulfilment.parcel.dispatched.v1
5 Read-side service consumes all three: received_events + order_summary (one tx each)
6 Client -> Read side: GET /order-summaries/o-1?min_version=1 -> 200 {status: completed}Each arrow is at-least-once; each consumer is idempotent; the read side owns its own store and its own replay log, because it may not read Sales', Fulfilment's or Billing's databases to rebuild.
Distributed data: replicas, caches, CDC and regions
Lag now stacks: the owner's replica lag, the relay interval, broker latency, projector lag, and the read store's own replication. Example: the read database has a replica for heavy list traffic; a token check against the replica can fail even though the primary already has the row, so the query reads the primary (or waits) when a min_version is present. Multi-region: project into a read store in each region from a replicated topic; the version token still works because it compares the aggregate version, not wall-clock time. CDC slots and logical-replication subscriptions must be monitored per region (retained WAL).
Scaling path: 1×, 10×, 100×
| Load | Write side | Read side | What changes |
|---|---|---|---|
| 1× (hundreds of orders/day) | Monolith, one DB | SQL queries, CQS | Nothing to project |
| 10× | Services or modules with outboxes | One OrderSummary table, one projector, token reads | Lag metric and rebuild command appear |
| 100× | Partitioned topics by order id | Projector workers per partition, read replicas of the read store, search index, warehouse | Rebuild time becomes a design constraint: snapshot the log, rebuild in parallel by key range |
Lab: break and protect a read model
Part 1 runs on any machine with Go (we ran it; the output is real). Parts 2 and 3 need PostgreSQL and a Laravel app; they are written with commands and expected output, not run (the lab cost rule: no containers).
1. The projector in memory (run).
cd docs/snippets/ddd/microservices-data-patterns/go
go test ./readmodel ./query -v | grep -E '^--- |^ok'
go run ./cmd/demo--- PASS: TestOutOfOrderEventsConverge (0.00s)
--- PASS: TestDispatchedBeforePlacedIsPending (0.00s)
--- PASS: TestDuplicateDeliveryIsANoOp (0.00s)
--- PASS: TestStaleSalesVersionIsIgnored (0.00s)
--- PASS: TestUnknownTypeIsIgnored (0.00s)
--- PASS: TestRebuildEqualsLive (0.00s)
--- PASS: TestSnapshot (0.00s)
ok academy/microservices-data-patterns/readmodel
--- PASS: TestWaitForCatchesUp (0.00s)
--- PASS: TestWaitForGivesUp (0.01s)
ok academy/microservices-data-patterns/query
1 command acknowledged: order=o-1 version=1
2 read before projection: read model has not reached the requested version
3 deliveries: dispatched, dispatched (duplicate), placed, paid
lag /fulfilment 1m0s
lag /sales 4m0s
lag /billing 3m0s
4 read with token v1: status=completed {"orderId":"o-1",...,"salesVersion":1,...,"paidMinor":2500}
5 rebuilt from 3 logged events, identical=trueLine 2 is the naive read failing; line 3 shows the duplicate absorbed (three lag lines for four deliveries); line 5 is the rebuild property. Now break it: in readmodel/memory.go delete the if m.seen[env.ID] check and rerun go test ./readmodel: TestDuplicateDeliveryIsANoOp fails with want 3 applied, got 4. Delete the v.SalesVersion <= r.SalesVersion guard: TestStaleSalesVersionIsIgnored fails.
2. The same rules in PostgreSQL (expected, not run). Create the schema from Mechanics, then in two psql sessions:
-- Session A: a delivery
BEGIN;
INSERT INTO received_events (event_id, source, type, subject, source_version, occurred_at, payload)
VALUES ('evt-ship-1', '/fulfilment', 'fulfilment.parcel.dispatched.v1', 'o-1', 4, now(), '{}')
ON CONFLICT (event_id) DO NOTHING; -- INSERT 0 1
INSERT INTO order_summary (order_id, dispatched_at, carrier) VALUES ('o-1', now(), 'DHL')
ON CONFLICT (order_id) DO UPDATE SET dispatched_at = EXCLUDED.dispatched_at, carrier = EXCLUDED.carrier;
COMMIT;
-- Session A again: the redelivery
INSERT INTO received_events (event_id, source, type, subject, source_version, occurred_at, payload)
VALUES ('evt-ship-1', '/fulfilment', 'fulfilment.parcel.dispatched.v1', 'o-1', 4, now(), '{}')
ON CONFLICT (event_id) DO NOTHING; -- INSERT 0 0 -> stop, do not touch order_summary
-- Without ON CONFLICT:
-- ERROR: duplicate key value violates unique constraint "received_events_event_id_key"
SELECT order_id, placed_at IS NULL AS pending, carrier FROM order_summary;
-- order_id | pending | carrier
-- o-1 | t | DHL3. Materialized view vs projection (expected, not run). In a single database with sales.orders, fulfilment.shipments, billing.invoices, create the view from alternative A. Insert a shipment, then:
SELECT carrier FROM reporting.order_summary_mv WHERE order_id = 'o-2'; -- (0 rows): not refreshed yet
REFRESH MATERIALIZED VIEW CONCURRENTLY reporting.order_summary_mv;
SELECT carrier FROM reporting.order_summary_mv WHERE order_id = 'o-2'; -- DHL
DROP INDEX reporting.order_summary_mv_order_id_idx;
REFRESH MATERIALIZED VIEW CONCURRENTLY reporting.order_summary_mv;
-- ERROR: cannot refresh materialized view "reporting.order_summary_mv" concurrently
-- HINT: Create a unique index with no WHERE clause on one or more columns of the materialized view.4. Laravel (expected, not run). With the migration applied on the read_model connection and the listener registered:
php artisan test --filter=OrderSummaryProjection
# PASS Tests\Feature\OrderSummaryProjectionTest
# ✓ it converges whatever the arrival order
# ✓ it ignores a duplicate delivery
# ✓ it shows pending when only a downstream fact has arrived
# ✓ it rebuilds to the same row
# ✓ it matches the snapshot
php artisan order-summary:rebuild
# replayed up to position 3
# swapped
curl -i 'http://localhost/order-summaries/o-1?min_version=2'
# HTTP/1.1 202 Accepted
# Retry-After: 1
# {"order_id":"o-1","status":"processing"}5. Measure the lag. Run the lag query from Mechanics while pausing the queue worker (php artisan queue:pause redis:projections) for 30 seconds: lag_by_event_time for the paused sources grows by about 30 seconds and drops back after php artisan queue:continue redis:projections.
Common misconceptions
| Belief | Reality |
|---|---|
| "CQRS means two databases and a broker." | Young: CQRS "is simply the creation of two objects where there was previously only one"; stores and messaging are later, optional steps. |
| "Every service should use CQRS." | Fowler: only "specific portions of a system (a BoundedContext in DDD lingo)"; most contexts fit CRUD. |
| "CQRS requires event sourcing." | Our OrderSummary uses a state-stored aggregate plus an outbox; event sourcing is a separate write-side choice. |
| "Database per service means a server per service." | Private tables or a schema per service on a shared server are listed by Richardson as the lowest-overhead options. |
| "Reading another service's tables is harmless." | Reads couple schemas and load; a rename breaks the reader, a long query hurts the owner. |
| "A read replica gives us CQRS." | Same schema, same owner, plus lag; it scales reads, it does not separate models. |
| "A read model is a cache." | It is a different shape, fed by events, owned by the reader, rebuildable, and never read-through. |
| "Exactly-once delivery makes dedup unnecessary." | Brokers and Debezium deliver at least once on failures; the dedup key in the same transaction is what makes the effect once. |
| "Commands must return void, so we cannot tell the client anything." | Returning a version token keeps reads on the read side and enables read-your-writes. |
| "Make the projector fast and users will see their writes." | Lag varies from ms to minutes; read-your-writes needs a token, stickiness or UI optimism. |
| "Rebuild from the other services' databases." | Not yours to read; keep your own log of received events, or rely on broker retention you control. |
| "A materialized view is a cross-service read model." | It needs all tables in one database, so it only works inside one owner or a modular monolith. |
| "BI can query the replicas." | Replicas carry internal schemas and suffer replay conflicts; reports belong in a warehouse. |
Cheat sheet
| Topic | Remember |
|---|---|
| The data problem | No cross-service joins (compose or project), no cross-service transactions (saga + outbox) |
| Shared database | Forbidden for writes; tolerated only as an owner-published view or insert-only contract table during a migration |
| Database per service | Private data; tables, schema or server; schema + role is the usual default |
| Polyglot persistence | Each service, and each read model, picks the store that fits its queries |
| CQS | Commands change and return no data; queries return data and change nothing |
| CQRS | Two objects first; then read tables; then read stores; stop as early as possible |
| Synchronous vs async projection | Same transaction = no lag, same DB; events = lag, any store |
| Read model | Per screen, denormalised, owned by the reader, rebuildable, versioned |
| Projector | Dedup by event id + upsert own columns + version guard, in one transaction; ack after commit |
| Out-of-order events | Upsert, never update-if-exists; derive status from facts present |
| Rebuild | Replay your own received_events up to a fence into a new table, catch up, lock briefly, swap |
| Replication options | Replica (scale), logical replication (selected tables), CDC (log → events), events (contracts), matview (one DB) |
| Read-your-writes | Version token + wait, sticky reads, UI optimism, or synchronous projection |
| EC failures | Stale lists, phantom deletes, resurrection, missing parents: tombstones + version guards + alarms |
| Reporting | Warehouse via CDC/events; never production services |
| Observability | projection_lag_seconds per source, pending rows, DLQ size, retained WAL |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Name the two capabilities a single database gives you that disappear with database per service, and the pattern that replaces each. Must-know
Answer
Answer: Joins across owners (replaced by API composition or a CQRS read model) and atomic transactions across owners (replaced by a saga of local transactions, with an outbox for reliable publishing).
2 — Billing only reads sales.orders. Why is that still a shared-database problem? Must-know
Answer
Answer: Development-time coupling (Sales cannot rename or reshape the table without breaking Billing) and runtime coupling (Billing's queries take locks, snapshots and I/O on Sales' database). The fix is a contract: an API, events, or an owner-published view or table.
3 — Which three granularities does Richardson list for keeping data private, and which two are cheapest? Good to know
Answer
Answer: Private tables per service, schema per service, database server per service; the first two "have the lowest overhead".
4 — Does func (h Handler) Handle(cmd PlaceOrder) (Ack, error) with Ack{OrderID, Version} violate CQS? Important
Answer
Answer: Strictly, it returns a value; pragmatically it returns no read data, only an identifier the client already knows and a version token. It keeps all reads on the query side and enables read-your-writes, which is why it is a common accepted deviation.
5 — Per Young, what is CQRS itself, and what is it not? Must-know
Answer
Answer: "simply the creation of two objects where there was previously only one", split by command vs query. It is not eventual consistency, eventing, messaging, separate stores or event sourcing; those are decisions made around it.
6 — When does Fowler say CQRS is not worth it, and what does he suggest instead for heavy queries? Important
Answer
Answer: When the domain fits a CRUD model or there is enough overlap between command and query sides; it adds "risky complexity". For a few demanding queries he suggests a ReportingDatabase while the main system keeps serving most queries.
7 — ParcelDispatched arrives before OrderPlaced. What two design choices keep the projector correct? Important
Answer
Answer: Upsert (create the row if missing) and write only the columns the event's context owns; derive the status from which facts are present (a row without placed_at is "pending"). Guard Sales' columns by Sales' version for reordering within Sales.
8 — Why must the dedup insert and the read-row update be in the same transaction, and when do you ack? Must-know
Answer
Answer: So that "seen" and "applied" can never disagree after a crash; and you ack after commit, so a crash before ack only causes a redelivery, which the dedup key turns into a no-op.
9 — Why does the read side keep received_events instead of rebuilding from Fulfilment's and Billing's databases? Important
Answer
Answer: Those databases are private to their owners; reading them would reintroduce a shared database. The read side's own append-only log (or broker retention it controls) is its replay source.
10 — A user places an order and the list does not show it. List four strategies and the one you would use by default. Must-know
Answer
Answer: Version token + wait-for-projection (default for async read models), sticky reads to the write side, UI optimism, synchronous projection in the same transaction.
11 — Which replication option keeps ownership and lets you reshape the copy freely? Good to know
Answer
Answer: Event-driven projections (events are designed contracts and the projector can build any shape). CDC and logical replication respect ownership only when the owner publishes a contract table, and logical replication can only select columns and rows.
12 — A product deleted on the write side reappears in search an hour later. Name the cause and the fix. Important
Answer
Answer: Resurrection: an older update event applied after the delete. Keep a tombstone with a version and apply events only if their version is newer (or use external versioning in the search engine).
Glossary
| Term | Meaning |
|---|---|
| 2PC (two-phase commit) | Atomic commit across resources; avoided across services |
| API composition | Query the owners and join the results in memory |
| At-least-once delivery | A message may be delivered more than once, never lost |
| Bounded context | The boundary within which one model applies; CQRS is decided per context |
| Catch-up | Processing the backlog from the last position before serving live traffic |
| CDC (change data capture) | Turning a database's log into a stream of row-change events |
| Command | A request to change state, named in the imperative; may be rejected |
| Consistency token / version token | The aggregate version a command returns, used by the client to read its own write |
| CQRS | Command Query Responsibility Segregation: separate objects/models/stores for writes and reads |
| CQS | Command-Query Separation: a method either changes state or returns data |
| Database per service | Each service's data is private and reachable only through its API or events |
| Debezium | Open-source CDC platform on Kafka Connect |
| Denormalised | Data duplicated to avoid joins at read time |
| Event sourcing | Storing an aggregate as the sequence of its events |
| Eventual consistency | Copies converge if no new updates arrive; reads may lag meanwhile |
| Idempotent update | Applying the same event twice has the same effect as once |
| Logical replication | PostgreSQL replication of data changes by replica identity, via publications and subscriptions |
| Materialized view | A stored query result, refreshed explicitly |
| Outbox | A table written in the same transaction as the aggregate, relayed to the broker |
| Phantom delete | A deleted item that still appears in a read model |
| Polyglot persistence | Using different storage technologies for different needs |
| Projection | The function from events to read-model rows |
| Projection lag | How far the read model is behind the events that produced it |
| Projector (projection handler) | The code that applies events to a read model |
| Publication / subscription | PostgreSQL objects that define what is replicated and who receives it |
| Read model | A query-shaped copy owned by the reader |
| Read replica | A physical copy of a database for reads, with replication lag |
| Read-your-writes | A session guarantee that a client sees its own earlier writes |
| Rebuild | Recreating a read model by replaying its event log |
| Replay fixture | A recorded event sequence used as test input |
| Replica identity | The columns PostgreSQL uses to identify rows for logical replication of updates and deletes |
| Reporting database | A separate database shaped for reports (Fowler) |
| Resurrection | An old event recreating a deleted row |
| Saga | A sequence of local transactions with compensations |
| Shared database | Several services accessing the same tables |
| Snapshot test (golden file) | Comparing output with a committed expected file |
| Sticky reads | Reading from the write side for a while after a write (Laravel sticky) |
| Task-based UI | A UI that sends intent-named commands instead of whole records |
| Thin read layer | Young's query side: SQL straight to DTOs, bypassing the domain model |
| Tombstone | A marker row recording a deletion and its version |
| UI optimism | Showing the expected result before the server confirms it |
| Version guard | Applying an update only if its version is newer than the stored one |
| Warehouse | An analytical store fed from operational systems |
| Write model | The model that processes commands and protects invariants (aggregates) |
References
- Chris Richardson, microservices.io: Database per Service, Shared Database, CQRS, API Composition, Event Sourcing, Saga
- Greg Young, CQRS Documents (PDF)
- Greg Young, CQRS, Task Based UIs, Event Sourcing agh! (February 2010, archived copy)
- Martin Fowler, bliki: CQRS (2011), CommandQuerySeparation (2005), ReportingDatabase
- Bertrand Meyer, Object-Oriented Software Construction (book; principle taken from Fowler's summary and Wikipedia: Command–query separation, secondary)
- Vaughn Vernon, Implementing Domain-Driven Design (2013), chapter 4; Vlad Khononov, Learning Domain-Driven Design (2021) — books, cited for placement only
- PostgreSQL 19 docs: Logical Replication, Publication, Row Filters, Column Lists, Restrictions, Architecture, REFRESH MATERIALIZED VIEW, PostgreSQL 10 release notes
- Debezium: PostgreSQL connector, FAQ
- Laravel 13: Database (read/write, sticky), Events (queued listeners, after commit), Queues, Query Builder (insertOrIgnore), Eloquent (upserts), Scout
- Go: pgx, sqlc, Watermill CQRS
- Sibling chapters: Data Ownership in Microservices, Outbox, Change Data Capture, Event Sourcing & CQRS, Idempotent Consumer & Inbox, Eventual Consistency in Databases, Replication & Failover, Domain Events vs Integration Events, Designing for Failure & Reliable Messaging