Data Ownership in Microservices: Database per Service, Shared Database, Brownfield Options
"Keep each microservice’s persistent data private to that service and accessible only via its API." — Chris Richardson, Pattern: Database per service, microservices.io
Summary: Who may write a piece of data, and who may only ask for it, decides more about a microservice system than any framework does; the ideal is one owner per piece of data with everyone else going through its API or events, and the realistic path from a shared database to that ideal is a sequence of small, reversible database moves. Focus: Why data is the hardest coupling, database per service and what "database" means (tables, schema, database, server, engine), the shared database anti-pattern and when it is tolerable, single/common/joint ownership and the four joint-ownership fixes, reference data, cross-service queries (API composition, CQRS read model, reporting database, CDC-fed store), cross-service writes without 2PC, read-your-writes across services, data sovereignty and tenant isolation, Newman's brownfield patterns (view, wrapping service, split table, FK to code, synchronize in application, tracer write), schema change across services, data mesh, testing and lag observability. Learning goal: Given a shared schema, assign an owner to every table, choose an isolation level for each owner, pick a query strategy and a write strategy for every cross-service use case, and plan the brownfield decomposition as numbered steps with a rollback for each, then prove it with database grants, a view, an outbox and a lag metric in Go and Laravel.
This chapter closes group AR 03 (Microservices in Practice). It assumes you have drawn service lines (Service Boundaries) and know how services talk (Service Communication). It owns the architecture decision: who owns which data, how isolated, and how to get there from a shared database. The mechanics live elsewhere and are linked, not re-taught: consistency models inside engines (Eventual Consistency in Database Systems), tenant layouts (Multi-Tenancy Strategies), replication (Replication & Failover), 2PC (Distributed SQL, Consensus & 2PC), expand/contract (Zero-Downtime Schema Migrations), the outbox (Transactional Outbox), sagas (Saga Pattern), CDC (Change Data Capture), projections (Event Sourcing & CQRS) and deduplication (Idempotent Consumers & Inbox). The DDD view of the same patterns (shared database, database per service, CQS to CQRS) is in Data Patterns in Microservices.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why data is the hardest coupling | Why data ownership is the hard part |
| Fowler 2004 to Hard Parts and data mesh | Where it comes from |
| Single writer, system of record | Data ownership |
| Tables vs schema vs database vs server | Database per service |
| Integration database, when sharing is tolerable | Shared database |
| Single, common, joint ownership; split, data domain, delegate, consolidate | Ownership scenarios |
| Countries, currencies, product names everybody needs | Reference data and duplication |
| API composition, CQRS read model, reporting DB, CDC | Cross-service queries |
| Sagas, outbox, no 2PC | Cross-service writes |
| "I saved it and it is not there" | Consistency promised to clients |
| PII location, residency, tenant silos | Data sovereignty and compliance |
| View, wrapping service, split table, FK to code, sync in app | Brownfield decomposition patterns |
| Two sources of truth during migration | Tracer write and dual-run |
| Changing a schema other services depend on | Schema change across services |
| Analytical data owned by domains | Data mesh, briefly |
| Data contracts, fixtures per service | Testing ownership |
| Lag metrics and alerts | Observability of owned data |
| Grants, views, errors, lag queries | Mechanics |
| Two services, composition, read model, tracer write | Go, Laravel |
| Joins, transactions, shared status column, reports, deletes | Solving the classic problems |
| Which option for which situation | Choosing |
| Monolith to distributed data | In architecture |
| Hands-on decomposition with lag measurement | 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 |
|---|---|---|---|
| Data ownership | One service is the only writer and the system of record for a piece of data | Catalog alone writes products | Two teams change the same rows by different rules |
| Database per service | Each service's data is private; others use its API or events | Orders cannot SELECT from catalog.products | A column rename breaks three services |
| Shared database (integration database) | Many services read and write the same tables | Orders, Billing, Shipping all join customers | Every schema change is a cross-team meeting |
| Reference data | Small, slowly changing data many services need | Countries, currencies, product names | Either chatty calls or uncontrolled copies |
| API composition | Join at query time by calling the owners | BFF calls Orders then Catalog | Latency adds up, availability multiplies down |
| CQRS read model | Join ahead of time in a store fed by events | order_summaries built from two event streams | Data is stale by the consistency lag |
| Saga | A multi-service write as local steps plus compensations | Reserve stock, charge card, or undo | Half-done business transactions |
| Transactional outbox | Write state and the event in one local transaction | orders row + outbox row, relay publishes | Lost or phantom events (dual write) |
| Tracer write | Move the source of truth gradually, writing to both for a while | Monolith writes invoices and calls Invoicing | Big-bang cutover with no way back |
| Data sovereignty | Data stays where law or contract says, under its owner's control | EU customers' PII only in the EU region | Fines, breach scope across every service |
What "database" can mean (the isolation ladder, drawn in Database per service):
| Level | Shape | Isolates | Enforced by | Cost |
|---|---|---|---|---|
| 0 | Shared tables | Nothing | Nothing | Lowest now, highest later |
| 1 | Private tables per service, one schema | Names, by convention | Table-level GRANT, code review | Very low |
| 2 | Schema per service | Names and privileges | PostgreSQL schema + role, REVOKE ... FROM PUBLIC | Low |
| 3 | Database per service, shared server | Names, privileges, migrations | MySQL CREATE DATABASE, per-service user | Low to medium |
| 4 | Database server per service | Plus CPU, memory, connections, backups, failures | Separate instance or cluster | Medium to high |
| 5 | Different engine, account or region | Plus technology and jurisdiction | Separate platform | Highest |
Cross-service reads and writes, the menu.
| Need | First choice | Second choice | Avoid |
|---|---|---|---|
| Show one order with product names | API composition with one batched call | Local copy of names via events | Joining another service's table |
| Search orders by product category, paged | CQRS read model | Reporting database | In-memory join of two large lists |
| Monthly revenue by region | Reporting database / warehouse via CDC | Data products (data mesh) | Analytical queries on owners' OLTP databases |
| Place an order that reserves stock and charges | Saga + outbox per step | Merge the services if the invariant is strict | 2PC across services |
| Rename a column others depend on | Expand/contract on the published contract | Version the API or event | Changing the table in one deploy |
Brownfield patterns at a glance (from Newman's Monolith to Microservices, chapter 4; details in Brownfield decomposition patterns):
| Pattern | One line | Reversible? |
|---|---|---|
| Database view | Expose a limited, read-only projection instead of the raw tables | Yes, drop the view |
| Database wrapping service | Put a thin service in front of a schema too messy to split now | Yes |
| Database-as-a-service interface | Publish a dedicated read database built for outside consumers | Yes |
| Split table | Break one table that two contexts write into two tables | With effort |
| Move foreign key to code | Drop the constraint, check existence through the owner's API | Yes, re-add FK while in one DB |
| Synchronize data in application | Copy, dual write, switch reads, retire the old store | Yes until the old store is retired |
| Tracer write | Same idea, one slice of data at a time | Yes until the old store is retired |
| Change data ownership | The monolith calls the new service instead of its own tables | Yes behind a flag |
Why data ownership is the hard part
Splitting code is a refactoring problem. Splitting data is a coupling problem, because data is where two pieces of code that never call each other still meet. If Orders and Billing both read the customers table, they are coupled even if neither imports the other: a column rename, a new NOT NULL, a long transaction holding a lock, or a new status value breaks the other side. Richardson lists exactly these costs of a shared database: "Development time coupling", where a developer "will need to coordinate schema changes with the developers of other services that access the same tables", and "Runtime coupling", because "if long running CustomerService transaction holds a lock on the ORDER table then the OrderService will be blocked."
The blast radius of a schema change is the set of services that break when it ships. In a shared database it is "everyone who touches the table, and you do not know who that is". Hard Parts makes the same point with a concrete case: if Service B, which owns table 3, "decides to make a change to its business rules that requires a column to be removed from table 3. Doing so would break Service C and any other services using table 3." Ownership shrinks the blast radius to one service and a published contract.
| One owner per piece of data | Many writers / readers on the same tables |
|---|---|
| Schema changes are local; the contract changes only on purpose | Every schema change needs every reader's sign-off |
| Rules that protect the data live next to it | Rules are copied, and drift |
| Failures and load stay inside one service | A slow report blocks checkout |
| Cross-service joins and transactions get harder | Joins and ACID transactions are free |
| Data is duplicated on purpose and kept in sync | One copy, but nobody can change it |
| Good for: independently evolving teams | Good for: one team, one deploy, or a short transition |
The analogy we reuse on this page: the office spreadsheet. A small company keeps everything in one shared spreadsheet: sales adds rows, finance adds a column for invoice status, warehouse colours cells red when stock is low. It works until finance renames a column and the warehouse macro breaks, or someone sorts the sheet while another is typing. The fix is not "no spreadsheets" but "one sheet per department, each kept by its owner; others read a published summary tab, or ask". The published tab is a view; asking is an API; the nightly copy to the boss's dashboard is a reporting database.
The ladder shows that "database per service" is a family of options. Levels 2 and 3 already give logical ownership, which is what removes coupling; levels 4 and 5 buy resource isolation and jurisdiction at a real operational price.
Three common misunderstandings, up front
- "Database per service means one database server per service." Richardson says the opposite: "You do not need to provision a database server for each service", and lists private tables, schema per service and server per service as options. Ownership is about who may write and read, not how many instances you run.
- "If we split the database we lose transactions, so we cannot split." You lose cross-service ACID transactions. You keep local ones, and you replace the cross-service ones with sagas and an outbox, or you conclude the two things belong in one service. Both are legitimate outcomes.
- "A shared database is always wrong." It is the right transition state and is tolerable for read-only reference data or a deliberately published read interface. The harm comes from leaving it open-ended and ungoverned.
Where it comes from
Fowler, 2004. Martin Fowler's bliki entries named the two poles. An IntegrationDatabase (25 May 2004) "acts as the data store for multiple applications", needs a schema that "has to unify what should be separate BoundedContexts", and "most software architects that I respect take the view that integration databases should be avoided." An ApplicationDatabase (3 August 2004) is "controlled and accessed by a single application"; to share data "the controlling application may provide services. It also may provide a ReportingDatabase for a wider range of read-only use." Microservices did not invent data ownership; they made it mandatory.
Fowler, Reporting Database (2014). The separate read-only copy "designed around the reporting needs", refreshed overnight or via messaging, with the remark that "many reporting needs work perfectly well with yesterday's data."
Lewis and Fowler, 2014. The Microservices article lists "Decentralized Data Management" as a characteristic (see Microservices Architecture).
Richardson, microservices.io (from 2014). The pattern language: Database per service with its three variants (private tables, schema, server), Shared database as the alternative, and the follow-on patterns for queries (API Composition, CQRS) and writes (Saga, Transactional outbox, Transaction log tailing, Event sourcing).
Newman, 2019. Monolith to Microservices, chapter 4 "Decomposing the Database", catalogued the brownfield moves: shared database, database view, database wrapping service, database-as-a-service interface, aggregate exposing monolith, change data ownership, synchronize data in application, tracer write, repository and database per bounded context, split table, move foreign-key relationship to code, and sagas. We could not fetch the book chapter (O'Reilly returns 403); the pattern descriptions on this page come from two sets of reader notes (Dan Lebrero's summary and Ignacio Herrera's handbook), labelled as secondary.
Ford, Richards, Sadalage, Dehghani, 2021. Software Architecture: The Hard Parts treats data as a first-class decomposition driver: data disintegrators and integrators (chapter 6), granularity integrators including "Database transactions" and "Data relationships" (chapter 7, free excerpt, which we read), and data ownership scenarios with their resolution techniques (chapter 9, which we could not fetch; the terms single/common/joint ownership, table split, data domain, delegate and service consolidation are the book's, the explanations ours).
Dehghani, 2019 to 2020. Data Mesh moved the ownership idea from operational to analytical data: "domain-oriented decentralized data ownership and architecture, data as a product, self-serve data infrastructure as a platform, and federated computational governance."
Debezium and log-based CDC (2016 onwards). Made "publish every committed change" cheap: Debezium's documentation says log-based CDC "Ensures that all data changes are captured" with delays "in the millisecond range" for MySQL or PostgreSQL. That turned CQRS read models and reporting copies from heroic projects into configuration.
The concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, a comparison table, and the fix.
Data ownership and the single writer Must-know
In plain words: for each piece of data there is exactly one service that may change it and that everyone else trusts as the truth; other services may keep copies, but they never write the original.
Common misunderstanding: "Ownership means nobody else may see the data." Others may read it, cache it, copy it into their own stores, even build their business on it. They may not write it, and they may not depend on how it is stored.
Definition: a service owns data when it is the single writer and the system of record (the source of truth) for it, and it exposes the data only through contracts it controls: an API, events, or a deliberately published read model. Hard Parts' function-to-table mapping draws the same line: "owner implies writes (and corresponding reads) and access implies read-only access to a table not owned by that function."
Customer changes delivery address; Customer service owns addresses
1 Client -> Customer API: PUT /customers/42/address only Customer writes customer.addresses
2 Customer: UPDATE customer.addresses ...; INSERT outbox one local transaction
3 Relay publishes CustomerAddressChanged.v1 (event_id e-77)
4 Orders consumes e-77 -> updates its copy orders.ship_to a copy, not the original
5 Shipping consumes e-77 -> re-plans open shipments its own rule, its own data
Leaky version: Orders runs UPDATE customer.addresses itself -> Customer's validation and audit are bypassedReal scenario: a bank where only the ledger service changes balances and everything else asks or listens; a marketplace where Catalog owns product names but Search keeps a denormalised copy for ranking; a SaaS where Identity owns e-mail addresses and Billing keeps a copy for invoices, refreshed by events; a retailer where two services both "fix" order status and nobody can explain a refund.
What a healthy owner provides:
| Owner provides | So that others can | Tooling |
|---|---|---|
| A query API (by id, batched) | Read current state on demand | REST/gRPC, Service Communication |
| Integration events with versions | Keep their own copies fresh | Outbox or CDC, Outbox |
| A published read model or view | Report without calling the API per row | Reporting DB, database view |
| Commands for changes | Ask for a change, never make it | API or command message |
| An ownership record | Know whom to ask | Data catalogue, CODEOWNERS, ADR |
Fix / how to use it: write an ownership table (table → owning service → team → contract), enforce it with database roles (see Mechanics), and route every "can I write that table?" question to the owner's API.
Database per service Must-know
In plain words: each service keeps its data to itself; the database is part of the service's implementation, like its private classes.
Common misunderstanding: "It requires a separate server and a different engine per service." Richardson: "There are a few different ways to keep a service’s persistent data private. You do not need to provision a database server for each service." The options are "Private-tables-per-service", "Schema-per-service" and "Database-server-per-service", and "Private-tables-per-service and schema-per-service have the lowest overhead."
Definition: Database per service means "A service’s transactions only involve its database" and its data "cannot be accessed directly by other services." The barrier must be real: Richardson recommends "a different database user id to each service and use a database access control mechanism such as grants", because "Without some kind of barrier to enforce encapsulation, developers will always be tempted to bypass a service’s API and access it’s data directly."
Schema per service on one PostgreSQL cluster
1 orders_svc connects with search_path=orders sees orders.*
2 orders_svc: SELECT * FROM catalog.products ERROR: permission denied for schema catalog (42501)
3 orders_svc -> GET catalog-api/products?ids=p1,p2 the only door
4 Catalog renames products.title -> products.name catalog's migration only; API contract unchanged
5 Orders keeps working; no meeting, no lockstep deployReal scenario: Richardson's FTGO example, where "Each service has database credentials that only grant it access its own (logical) database on a shared MySQL server"; Datadog's migration (described in June 2025), whose first phase created around 30 private schemas with explicit ACLs inside the shared PostgreSQL database, while moving schemas to separate instances was a later, overlapping phase; a startup with five services on one managed PostgreSQL, five schemas, five roles.
Variants compared, per product:
| Variant | PostgreSQL | MySQL / InnoDB | SQL Server | Oracle | MongoDB |
|---|---|---|---|---|---|
| Private tables | Table-level GRANT in one schema | Table-level GRANT in one database | Table-level GRANT in dbo | Grants on tables of one schema | Collection-level roles |
| Schema per service | CREATE SCHEMA ... AUTHORIZATION role | (schema = database in MySQL) | CREATE SCHEMA, GRANT ... ON SCHEMA::x | One schema user per service | Database per service in one cluster |
| Database per service | Separate database; no cross-database query without postgres_fdw | CREATE DATABASE orders + per-service user | Separate database | Pluggable database (PDB) | Separate database |
| Server per service | Separate instance/cluster | Separate instance | Separate instance | Separate CDB/instance | Separate cluster |
Fix / how to use it: start at schema per service with one role each (cheapest real barrier), move a service to its own server only for a named reason (load, failure isolation, compliance, a different engine). Polyglot persistence (Elasticsearch for search, Neo4j for a graph, as Richardson's page mentions) is a benefit of ownership, not the reason for it.
Shared database (integration database) Must-know
In plain words: several services read and write the same tables, so the database, not an API, is their contract.
Common misunderstanding: "It is fine because each service uses different columns." Readers still depend on table names, types, row semantics and locks. And "different columns" is usually untrue a year later.
Definition: Richardson's Shared database: "Use a (single) database that is shared by multiple services. Each service freely accesses data owned by other services using local ACID transactions." Benefits: familiar ACID and "A single database is simpler to operate". Drawbacks: development-time coupling, runtime coupling, and "Single database might not satisfy the data storage and access requirements of all services." Per the notes on Newman's chapter 4, the deeper problem is that sharing denies the owner the chance to decide what is shared and what is hidden, and it becomes unclear who controls the data and where the logic that changes it lives.
Shared database: Billing adds a NOT NULL column to customers
1 Billing migration: ALTER TABLE customers ADD COLUMN tax_id text NOT NULL DEFAULT ''
2 Orders still INSERTs customers without tax_id fine today: default applies
3 Billing: ALTER TABLE customers ALTER tax_id DROP DEFAULT "clean-up"
4 Orders sign-up: ERROR: null value in column "tax_id" ... violates not-null constraint (23502)
5 Incident; root cause is a migration in a service Orders never callsWhen it is tolerable (per the notes on Newman, plus our reading of Fowler):
| Situation | Why it is acceptable | Guard rails |
|---|---|---|
| Read-only static reference data | Stable, clear owner, admin-managed changes | One writer role; readers get SELECT only |
| A deliberately published read endpoint (database-as-a-service interface, reporting DB) | Designed and versioned for many consumers | Separate schema or database; owner maintains it |
| A short transition during extraction | Steps of the brownfield plan | End date, owner, metrics; see timeline |
| One team, one deployable (modular monolith) | Coupling is inside one team | Schema per module, see Modular Monolith |
| Reporting that can be a day stale | Fowler's reporting database | Copy, not the live OLTP tables |
Fix / how to use it: if you must share, make it explicit: one writer role per table, read-only roles for the rest, a view or a wrapping service as the published face, and an exit date. Datadog's post is candid that splitting "is far from an obvious win—it’s expensive, time-consuming, and not always the right answer"; the decision to split must come from felt pain, not principle.
Ownership scenarios: single, common, joint Important
In plain words: after you map which service writes which table, every table falls into one of three cases: one writer (easy), almost everyone writes it (give it its own owner), or a few services write it (pick one of four fixes).
Common misunderstanding: "Joint ownership can be solved by being careful." Two writers mean two sets of rules for one state machine; care does not scale across teams.
Definition (terms from Software Architecture: The Hard Parts, chapter 9; explanations ours since we could not fetch that chapter):
- Single ownership: one service writes the table. Assign it; others read via API or events.
- Common ownership: most services write the table (an audit log, a notifications table). Make a dedicated service the owner; others send it writes, usually asynchronously.
- Joint ownership: a few services write the same table. Resolve with, from most to least decoupled: table split (split by columns so each writes its own table), data domain (accept a shared schema owned jointly by tightly related services: a bounded exception), delegate (one service owns the table; the other writes through its API), or service consolidation (merge the services; the transaction stays local).
Joint ownership of customer.status (example from the notes on Newman's "split table")
1 Sign-up code: status NOT_VERIFIED -> VERIFIED (Customer context)
2 Finance code: status VERIFIED -> SUSPENDED (unpaid) (Finance context)
3 Split: Customer owns the state machine; Finance calls POST /customers/42/suspensions
4 Finance keeps its own finance.accounts (credit, dunning level)
5 The status column now has one writer and one set of rulesReal scenario: an audit_log written by every service (common: give it to an Audit service fed by events); product written by Catalog (name, description) and Inventory (stock) (joint: table split); wishlist written by Cart and Wishlist teams who always change together (joint: consolidate); customer.status written by sign-up and finance (joint: delegate).
| Technique | When | You keep | You lose |
|---|---|---|---|
| Table split | Writers touch different columns | Independence | One-row atomicity across the columns |
| Data domain | Services are tightly related, same team | Local ACID across them | Independent schema change between them |
| Delegate | One service naturally owns the state machine | One writer, one rule set | Latency and availability of the delegate on the other's write path |
| Service consolidation | Writers must change atomically and always change together | ACID, simplicity | A smaller service; possibly team autonomy |
Fix / how to use it: build the table-by-service write matrix from code search and from database statistics (pg_stat_statements by role, MySQL Performance Schema), mark each table single, common or joint, and write one decision per joint table in an ADR (Architecture Decisions).
Reference data and duplication Important
In plain words: countries, currencies, tax rates and product names are needed by everyone; you decide per dataset whether to ask the owner each time, keep a cached copy, replicate it, or ship it as a library.
Common misunderstanding: "Duplication violates single source of truth." A copy with a known owner, a known refresh path and a known staleness is not a second source of truth; it is a cache. The violation is a copy that is written locally.
Definition: reference data is small, slowly changing data with a clear owner and many readers. Duplicating it deliberately (data duplication) trades storage and staleness for availability and latency. The notes on Newman's chapter list the options: duplicate it, a dedicated reference schema, a static library for small datasets, or a data service that "Maybe can emit change events".
Currency list: owner = Finance, readers = Orders, Billing, Catalog
1 Finance adds "XCG" (new currency) and publishes CurrencyAdded.v1
2 Orders' consumer upserts orders.currencies_copy (replicate)
3 Catalog has an in-process cache, TTL 10 min, refreshes on miss (cache)
4 Billing uses the currencies package v3.2 pinned at build time (library: needs a redeploy)
5 Ten minutes later all three accept XCG; Billing only after its next releaseReal scenario: product names in order history (copy at order time: the name as sold is a fact of the order, not a reference); country lists (library or replicated table); exchange rates (call or short-TTL cache: staleness costs money); feature flags (owned by a platform service, cached).
| Option | Freshness | Availability if owner is down | Coupling | Best for |
|---|---|---|---|---|
| Call the owner each time | Live | None | Temporal | Rapidly changing, cheap to fetch |
| Cache with TTL | TTL-stale | Until TTL | Low | Read-heavy, tolerant of minutes |
| Replicate via events / CDC | Lag-stale | Full | Low (contract only) | Joins and filters in the reader |
| Static library / config | Release-stale | Full | Deployment | Tiny, almost-never-changing lists |
| Dedicated shared reference schema | Live | Shares the DB's availability | Schema (read-only) | Transition, or a true reference service |
| Snapshot into own record | Frozen by design | Full | None | "As it was at the time" facts |
Fix / how to use it: for each reference dataset, record the owner, the chosen option, and the acceptable staleness in seconds; that number becomes an alert threshold (see Observability).
Cross-service queries Must-know
In plain words: when one screen needs data from two owners, you either ask both at query time (API composition) or keep a joined copy fed by their events (CQRS read model, reporting database).
Common misunderstanding: "CQRS is the advanced version, so always use it." It adds a projector, a store, replays and a lag to watch. API composition is simpler and fresher and is the right first choice when the join is small and keyed.
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." Often done by an API gateway or BFF (API Gateway & BFF).
- CQRS read model: "Define a view database, which is a read-only ‘replica’ that is designed specifically to support that query", kept up to date "by subscribing to Domain events published by the service that own the data". Drawbacks include "Replication lag/eventually consistent views". Mechanics in Event Sourcing & CQRS.
- Reporting database / data warehouse: Fowler's separate read-only copy "designed around the reporting needs", refreshed by batch or messaging. At scale it is a warehouse or lakehouse fed by CDC (OLTP vs OLAP).
- CDC-fed read store: a read model built from the owner's database log rather than hand-written events (Change Data Capture). Cheapest to start; couples readers to the owner's table shape unless you route through an outbox table.
Query: "my orders with product names", two owners
API composition CQRS read model
1 GET /orders?customer=42 -> Orders (40 ms) OrderPlaced, ProductRenamed already projected
2 GET /products?ids=... -> Catalog (30 ms, batched) SELECT ... FROM reporting.order_summaries
3 join in memory, return (~75 ms) JOIN reporting.product_names (5 ms)
4 Catalog down -> partial answer, names missing Catalog down -> full answer, names maybe stale
5 Product renamed 1 s ago -> new name shown -> old name until the projector catches upReal scenario: an order page (composition), a "filter my orders by brand and sort by date" screen (read model: composition would need to fetch all orders), a finance month-end report (reporting database), a search index (CDC-fed store), a customer 360 view in support tools (read model across five owners).
| Option | Freshness | Read latency | Works when an owner is down | Large joins, filters, paging | Moving parts |
|---|---|---|---|---|---|
| API composition | Live | Sum/max of calls | No (or partial) | Poor | Composer only |
| CQRS read model | Lagging (ms to s) | One local query | Yes | Good | Events, projector, store, replay |
| Reporting DB / warehouse | Minutes to a day | Fast for analytics | Yes | Excellent for aggregates | ETL/ELT or CDC pipeline |
| CDC-fed read store | Lagging (ms to s) | One local query | Yes | Good | CDC connector, schema coupling |
Fix / how to use it: start with composition and batch the calls (one request per owner, never one per row). Move a query to a read model when it needs filtering or paging across owners, or when composition latency or availability breaks its SLO (SLOs). Send analytics to a reporting store, never to the owners' OLTP databases.
Cross-service writes: sagas, outbox, no 2PC Must-know
In plain words: a business action that changes two services' data is done as local transactions, one per service, linked by messages, with undo steps if a later one fails.
Common misunderstanding: "We will use distributed transactions (XA / 2PC) to keep ACID across services." Richardson's database-per-service page: "Distributed transactions are best avoided because of the CAP theorem. Moreover, many modern (NoSQL) databases don’t support them." 2PC also couples availability: every participant must be up and the coordinator's failure blocks everyone (Distributed SQL, Consensus & 2PC).
Definition: a saga is a sequence of local transactions; if one "fails because it violates a business rule, the changes made by the completed steps are undone by compensating transactions." It is coordinated by choreography (events) or orchestration (a coordinator). Each step publishes its event reliably with a transactional outbox: store "the message in the database as part of the transaction that updates the business entities. A separate process then sends the messages". The result is eventual consistency. Full mechanics: Saga Pattern, Transactional Outbox.
Place order (Orders, Inventory, Payments each own their data), orchestrated
1 Orders: INSERT order PENDING + outbox(ReserveStock) local tx 1
2 Inventory: reserve 2 x p-1 + outbox(StockReserved) local tx 2
3 Payments: charge fails (card declined) + outbox(PaymentFailed) local tx 3
4 Orders -> Inventory: ReleaseStock (compensation) local tx 4
5 Orders: UPDATE order REJECTED local tx 5
Between 1 and 5 another reader may see PENDING and reserved stock: no isolation across servicesReal scenario: order placement with stock and payment; hotel + flight booking; account opening with KYC; refund flows that touch ledger, inventory and notifications. When the invariant cannot tolerate the gap (two services must never disagree on a balance), Hard Parts' integrator "Database transactions" says keep them in one service.
| Approach | Atomic? | Isolation across services | Availability coupling | Use |
|---|---|---|---|---|
| Local ACID in one service | Yes | Yes | None | Default inside a service |
| 2PC / XA across services | Yes (blocking) | Yes | All participants + coordinator | Avoid between microservices |
| Saga + outbox | Eventually | No (countermeasures: semantic locks, pending states) | Per step | Business processes across owners |
| Merge the services | Yes | Yes | One service | Invariant that must hold at every instant |
Fix / how to use it: design the states clients see while a saga is running (PENDING, RESERVED), make every step idempotent, publish through an outbox, consume through an inbox (Idempotent Consumers). The Go and Laravel code below writes the order and its outbox row in one local transaction.
Consistency promised to clients Important
In plain words: after users click "save", they expect to see their change on the next screen even if that screen reads from a different service's copy; you must decide what you promise and engineer it.
Common misunderstanding: "Read-your-writes is a database setting." Inside one database with replicas it can be (Laravel's sticky, session-pinned reads; see Eventual Consistency in Database Systems). Across services no setting exists; it is a design.
Definition: read-your-writes across services means a client that performed a write sees it in every later read it makes, even when those reads hit a read model that lags. Techniques: return the new state in the write response; route the next read to the owner; carry a version or position token and wait for the read model to reach it; or show a "pending" UI state honestly (Consistency Models).
User renames a product; the product list is a read model with ~800 ms lag
1 PUT catalog/products/p-1 {name:"Kettle XL"} -> 200 {version: 7}
2 Client navigates to /products (read model at version 6)
3a Naive: list shows "Kettle" -> user renames again -> duplicate events, support ticket
3b Token: GET /products?min_version[p-1]=7 -> projector at 6 -> wait up to 1 s or fall back to Catalog API
3c UI: optimistic update from the PUT response, marked "saving..."Real scenario: a seller renames a product and the storefront list lags; a user changes the delivery address and the checkout page (read model) shows the old one; an admin grants a permission and the user's next request is checked by a service with a cached copy.
| Promise | Technique | Cost |
|---|---|---|
| Read-your-writes, same request | Laravel sticky, same transaction | None across services |
| Read-your-writes, next requests in the session | PreventStaleDatabaseReads (replicas of one DB), or route to owner for N seconds | Owner load |
| Read-your-writes via read model | Version/position token, wait or fall back | Projector must expose its position |
| Monotonic reads | Pin a session to one replica / one read model instance | Uneven load |
| None (honest eventual consistency) | UI shows pending state | Product design work |
Fix / how to use it: state the promise per screen in the requirements, return the authoritative new state from every write, and expose version or last_event_id from read models so callers can wait for their own write.
Data sovereignty and compliance Important
In plain words: some data must live in a specific place, be visible to few services, and be deletable on request; ownership is how you make those promises checkable.
Common misunderstanding: "Encrypting the database is enough for compliance." Location, access, retention and erasure are separate obligations. A copy of an e-mail address in eight read models is eight places to erase.
Definition: data sovereignty in this chapter means each service has authority over its data and its copies' rules, and regulated data stays under the control and jurisdiction required for it (data residency). Consequences for ownership: keep PII in as few owners as possible, replicate references (ids, tokens) instead of PII, give tenant isolation a physical level when contracts demand it (Multi-Tenancy Strategies), and make erasure an event every copy handles.
Right-to-erasure request for customer 42 (EU)
1 Privacy service -> Customer: DELETE /customers/42/pii owner erases or crypto-shreds
2 Customer publishes CustomerErased.v1 {customer_id: 42}
3 Orders replaces name/address on old orders with "erased" copy handled
4 Reporting drops 42 from customer_dim; Search removes documents copies handled
5 Audit: each consumer acks erasure; missing ack after 72 h -> alertReal scenario: PII only in the Identity service, all others store customer_id; health data in a dedicated service and database with its own key in a KMS; per-region deployments where EU tenants' data never leaves eu-*; card data isolated so that only one service is in PCI DSS scope (the compliance decomposition driver in Service Boundaries).
| Requirement | Ownership decision | Isolation level from the ladder |
|---|---|---|
| Minimise PII spread | One PII owner; others hold ids/tokens | 2 or more |
| Data residency per region | Owner deployed per region; no cross-region replication of PII | 5 |
| Tenant contract demands isolation | Silo tenant data per database or server | 3 to 5 |
| PCI DSS scope reduction | Card data in one service and network segment | 4 |
| Erasure | Owner + erasure event handled by every copy | Any |
Fix / how to use it: tag columns by sensitivity in the ownership table, forbid PII in integration events unless the consumer is entitled (use ids and let entitled services ask), and test erasure end to end (Messaging Security, Database Security).
Brownfield decomposition patterns Must-know
In plain words: you rarely start with clean ownership; you start with one big database and move one table, one constraint, one reader at a time, keeping every step small enough to undo.
Common misunderstanding: "First we split the database, then the code, in one project." Per the notes on Newman, most teams split the code first and then the data, and the risky move is doing both at once ("DB and code at the same time: Avoid").
Definition: the patterns below are from Newman's chapter 4 as summarised by readers' notes (secondary; wording here is ours unless quoted from the notes).
| Pattern | When | How | Risks |
|---|---|---|---|
| Shared database (accepted) | Read-only static reference data with a clear owner | Readers get SELECT only | Becomes permanent |
| Database view | Readers you cannot change yet; read-only needs | A view in a separate schema exposing only needed columns; one role per consumer | Read-only; same engine; whoever owns the view must keep it working |
| Database wrapping service | Schema too tangled to split now; stop it growing | Thin service in front; revoke direct access; log usage | Consumers must change to API calls; performance of the wrapper |
| Database-as-a-service interface | Outside consumers need SQL-style reads | Dedicated read database, filled by CDC, batch or event log | Mapping engine to maintain; lag |
| Aggregate exposing monolith | New service needs data still owned by the monolith | Monolith exposes a proper aggregate API | Monolith team must build and run it |
| Change data ownership | Monolith still uses data the new service now owns | Monolith calls the new service, or reads a projected view | Breaks FKs and transactions in the monolith |
| Synchronize data in application | Moving data to a new store with fallback | Bulk copy (+ CDC for catch-up), dual write read old, dual write read new, retire | Two writers; needs one writer at a time |
| Tracer write | Same, but one slice at a time | Write to old and new via the new service's API, switch consumers gradually | Inconsistency window; reconciliation |
| Repository / database per bounded context | Inside the monolith, before extraction | Group data access by context; even separate schemas | Little short-term benefit |
| Split table | One table written by two contexts | New tables per context; pick an owner for shared columns | Loses one-row atomicity |
| Move foreign-key relationship to code | Rows reference data now in another service | Drop FK, store the id, check via API; handle deletes | Latency; orphans |
| Saga | Business transactions spanning the split | Local steps + compensation | No isolation |
Extracting Catalog, one deploy per line, each reversible
1 v1: create role per consumer; reporting reads legacy_compat.products_v (view)
2 v2: split products into catalog.products + inventory.stock; compat view keeps old readers alive
3 v3: DROP CONSTRAINT orders_product_id_fkey; Orders checks products via Catalog API
4 v4: Catalog service live; monolith tracer-writes products to it; reads still from old tables
5 v5: flag flips reads to Catalog; writes still go to both; reconciler reports 0 mismatches for 7 days
6 v6: catalog schema moves to its own database; old grants revoked
7 v7: drop old tables and compat viewsReal scenario: Datadog (June 2025) ran almost exactly this ladder on its shared PostgreSQL: phase 1 created private schemas and explicit ACLs ("denizens of the shared database could still access everyone else’s data ... but the ACLs will be explicit"), phase 2 removed direct dependencies ("we favored the build a service for teams that depend on your data approach") and narrowed ACLs, phase 3 moved schemas to their own instances, with "continuous replication of the data to the old instance to support rollbacks". The phases overlapped in time (phase 1 from Q1 2024 to Q1 2025, phase 3 from Q3 2024), and their chart of schemas and tables shows 326 tables going to 257 between December 2023 and early April 2025.
Fix / how to use it: write the plan as numbered deploys like the timeline above, each with a metric that proves it worked and a rollback. The SQL for the view, split and FK steps is in Mechanics and is exercised in the Lab.
Tracer write and dual-run Important
In plain words: while moving data to a new owner, write every change to both places for a while, read from the old one until you trust the new one, then flip, and keep comparing.
Common misunderstanding: "Dual writes are always wrong." An unguarded dual write (database + broker, no outbox) loses events. A tracer write is a deliberate, temporary dual write with one declared source of truth per phase, a reconciler, and an end date.
Definition: per the notes on Newman, with a tracer write "we move the source of truth for data in an incremental fashion, tolerating there being two sources of truth during the migration", and the write strategy is one of "Write to one source" (then sync), "Send writes to both sources", or "Send writes to either source", where the last "should be avoidable when possible as two-way synchronization can be very difficult to achieve." Dual-run is running old and new side by side and comparing results. The same notes describe the related synchronize data in application sequence: bulk copy (with "a change data capture process" for changes made during the copy), "Synchronize on Write, Read from Old Schema", "Synchronize on Write, Read from New Schema", then decommission.
Invoices move from the monolith to Invoicing (phases via feature flag)
1 old_only : monolith writes invoices table
2 backfill : job copies existing invoices through Invoicing's API
3 dual_read_old : write old, then PUT to Invoicing (failure logged, not fatal); reads old
4 reconcile : nightly compare by id; repair follower; mismatch rate -> 0
5 dual_read_new : write Invoicing first, then old (fallback); reads Invoicing
6 new_only : stop writing old; keep table read-only for 30 days; dropReal scenario: per the same notes, Square split a single Order concept by creating a Fulfillment service; the background worker "made use of an API exposed by the Fulfillments service rather than doing a direct insertion into the database", upstream clients made two sets of API calls, and the switch of consumers "ended up being pretty much a non-event". Trifork moved Danish medical records from MySQL to Riak with the application synchronising both. Datadog's phase 3 read from the new instance while writing the old one before cutting writes over.
| Phase | Source of truth | Write order | Read from | Rollback |
|---|---|---|---|---|
| Old only | Old | Old | Old | n/a |
| Dual write, read old | Old | Old, then new (best effort) | Old | Turn off new writes |
| Dual write, read new | New | New, then old (fallback) | New | Flip reads back |
| New only | New | New | New | Needs reverse sync (plan it) |
Fix / how to use it: one flag controls the phase, the secondary write never fails the user request, a reconciler compares and repairs by id, and the mismatch rate is a dashboard number. See tracer in Go and TracerWriteInvoices in Laravel.
Schema change across services Important
In plain words: inside its own database an owner changes whatever it wants; what others depend on (API fields, event fields, views) changes in two steps: add the new thing, move everyone, then remove the old thing.
Common misunderstanding: "With database per service, schema changes are free." The private schema is. The published contract (event payloads, API responses, compat views, CDC topics that mirror tables) still needs expand/contract (ParallelChange, Danilo Sato on Fowler's bliki).
Definition: expand/contract applies the same three phases to tables and to contracts: expand (add new column/field, write both), migrate (move readers), contract (remove the old). Mechanics for tables are in Zero-Downtime Schema Migrations; for events in Message Design & Schema Evolution.
Catalog renames title -> name; Search consumes ProductChanged via CDC on the products table
1 Expand: ADD COLUMN name; trigger/app writes both; event carries title and name
2 Search deploys reading name with fallback to title
3 Contract check: consumer-driven contract tests show nobody reads title
4 Contract: drop title from event (v2) and from the table
Without the outbox: CDC on the raw table publishes the rename instantly -> Search breaks at step 1Real scenario: a CDC topic mirroring a table, so a column rename becomes a breaking event change (use an outbox table as the published shape, e.g. Debezium's outbox event router); a compat view that must be updated with the table under it; a BFF composing a field that the owner removed.
| What changes | Inside owner only | Needs expand/contract | Tool |
|---|---|---|---|
| Private table, column, index | Yes | No | Owner's migrations |
| API response field | No | Yes | Versioned API, contract tests |
| Event payload | No | Yes | Schema registry, versioned event type |
| Published view / DBaaS interface | No | Yes | View migration owned by data owner |
| CDC topic of a raw table | No | Yes, and it is easy to forget | Prefer outbox table as the contract |
Fix / how to use it: treat everything another team reads as a contract with a version and a test; keep raw tables out of CDC topics others consume.
Data mesh, briefly Good to know
In plain words: the same "domains own their data" rule applied to analytics: each domain publishes curated, documented datasets as products instead of a central team pulling everything into one warehouse.
Common misunderstanding: "Data mesh means microservices query each other's databases for analytics." It means domain teams own analytical data products with contracts and SLOs, served on a shared self-serve platform under federated governance; operational databases stay private.
Definition: Dehghani's four principles: "domain-oriented decentralized data ownership and architecture, data as a product, self-serve data infrastructure as a platform, and federated computational governance." A data product is a dataset with an owner, schema, documentation, quality and freshness SLOs, and access policy.
1 Orders domain publishes data product "orders_daily" (schema v3, freshness SLO 1 h)
2 Platform provides storage, catalogue, access policies (self-serve)
3 Finance analytics consumes orders_daily + payments_daily; never reads orders OLTP
4 Governance policy (PII masking) runs automatically on every productReal scenario: replacing a central warehouse team's ETL that breaks whenever a service changes a table; giving domain teams the duty to publish analytics-ready data with the same care as their APIs.
| Central warehouse | Data mesh |
|---|---|
| Central team pulls from every OLTP DB | Domain teams publish data products |
| Breaks on upstream schema changes | Contract and versioning per product |
| Ownership of meaning is unclear | Domain owns meaning and quality |
Fix / how to use it: most systems do not need a mesh; they need a reporting database fed by CDC or outbox events. Adopt mesh ideas (owner, contract, freshness SLO per dataset) before adopting mesh tooling.
Testing ownership Good to know
In plain words: test that the boundary holds (nobody can reach in) and that the contracts others rely on (APIs, events, views) do not break.
Common misunderstanding: "End-to-end tests with all services and one shared test database are the safest." They re-create the shared database in test, hide ownership violations, and are slow and flaky.
Definition: data contracts are versioned schemas plus semantics (and for analytics, freshness and quality) for data that crosses a boundary; consumer-driven contract tests let each consumer state what it needs and the producer verify it (Pact, or a JSON fixture as in Service Boundaries). Fixtures per service means each service's tests create only its own schema and fake the others' APIs.
| Test | Catches | Example on this page |
|---|---|---|
| Grant test on a real DB | Cross-schema access | OwnershipBoundaryTest (42501) |
| View shape test | Hidden columns leaking into a view | test_legacy_view_hides_columns... |
| Composer test with stubs | Owner down, batching | composer_test.go |
| Projector idempotency test | Duplicate and out-of-order events | projector_test.go |
| Tracer reconciliation test | Lost secondary writes | tracer_test.go |
| Consumer-driven contract | Breaking an API/event field | Service Boundaries |
Fix / how to use it: run grant tests in CI against a real PostgreSQL (Testcontainers), keep per-service fixtures, and put contract tests in the producer's pipeline (Testing Messaging Systems).
Observability of owned data Good to know
In plain words: once data is copied between owners, "how stale is this copy?" is a production metric with an alert, just like latency.
Common misunderstanding: "If the broker has no backlog, read models are fresh." The outbox may be stuck before the broker, the CDC slot may lag, or the projector may be failing and dead-lettering.
Definition: consistency lag is the time from the owner's commit to the change being visible in a copy. Measure it at each hop: outbox (oldest unpublished row), CDC (Debezium MilliSecondsBehindSource: "The number of milliseconds between the last change event’s timestamp and the connector processing it"), broker (consumer lag), projector (event time to applied time).
| Hop | Metric | Where |
|---|---|---|
| Outbox | Age of oldest unpublished row; publish lag histogram | relay.OldestUnpublishedAge, lab query |
| CDC connector | MilliSecondsBehindSource | Debezium JMX streaming metrics |
| PostgreSQL slot | Retained WAL behind confirmed_flush_lsn | pg_replication_slots |
| Broker | Consumer lag (messages or time) | Messaging Observability |
| Projector | now - occurred_at at apply; failures; DLQ size | readmodel.Projector.Lag, read_model_lag log |
| Tracer write | Reconciliation mismatches per day | tracer.Reconcile |
Fix / how to use it: set an SLO per copy ("product names in the storefront are at most 5 s stale for 99% of changes") and alert on the oldest-unpublished age, which grows even when nothing is flowing.
Mechanics
Enforcing ownership with roles and grants
The basic one-schema-one-role setup is shown in Service Boundaries. Here is the target schema of this chapter's examples: two owners, a reporting read model, and a transitional view.
-- PostgreSQL 15+: PUBLIC no longer has CREATE on schema public by default.
CREATE ROLE catalog_svc LOGIN PASSWORD 'catalog';
CREATE ROLE orders_svc LOGIN PASSWORD 'orders';
CREATE ROLE reporting_svc LOGIN PASSWORD 'reporting';
CREATE SCHEMA catalog AUTHORIZATION catalog_svc;
CREATE SCHEMA orders AUTHORIZATION orders_svc;
CREATE SCHEMA reporting AUTHORIZATION reporting_svc;
SET ROLE catalog_svc; -- each owner creates (and so owns) its tables
CREATE TABLE catalog.products (
id text PRIMARY KEY,
sku text NOT NULL UNIQUE,
name text NOT NULL,
price_cents bigint NOT NULL CHECK (price_cents >= 0),
active boolean NOT NULL DEFAULT true,
deleted_at timestamptz,
version bigint NOT NULL DEFAULT 1
);
RESET ROLE;
SET ROLE orders_svc;
CREATE TABLE orders.orders (
id text PRIMARY KEY, customer_id text NOT NULL, total_cents bigint NOT NULL,
status text NOT NULL, version bigint NOT NULL, created_at timestamptz NOT NULL
);
CREATE TABLE orders.order_lines (
order_id text NOT NULL REFERENCES orders.orders(id), -- FK inside one owner: keep it
product_id text NOT NULL, -- FK to another owner: moved to code
qty int NOT NULL CHECK (qty > 0), unit_price_cents bigint NOT NULL,
PRIMARY KEY (order_id, product_id)
);
CREATE TABLE orders.outbox (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
event_id text NOT NULL UNIQUE, aggregate_type text NOT NULL, aggregate_id text NOT NULL,
event_type text NOT NULL, payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(), published_at timestamptz
);
CREATE INDEX outbox_unpublished ON orders.outbox (id) WHERE published_at IS NULL;
RESET ROLE;
SET ROLE reporting_svc;
CREATE TABLE reporting.inbox (event_id text PRIMARY KEY, processed_at timestamptz NOT NULL DEFAULT now());
CREATE TABLE reporting.order_summaries (
order_id text PRIMARY KEY, customer_id text NOT NULL, total_cents bigint NOT NULL,
product_ids jsonb NOT NULL, version bigint NOT NULL
);
CREATE TABLE reporting.product_names (product_id text PRIMARY KEY, name text NOT NULL, version bigint NOT NULL);
RESET ROLE;
-- Who can write what? One writer per schema is the healthy answer.
SELECT table_schema, grantee, string_agg(DISTINCT privilege_type, ',') AS privileges
FROM information_schema.role_table_grants
WHERE table_schema IN ('catalog', 'orders', 'reporting')
AND privilege_type IN ('INSERT', 'UPDATE', 'DELETE')
GROUP BY table_schema, grantee ORDER BY 1, 2;On MySQL the unit is a database: CREATE DATABASE catalog; CREATE USER 'catalog_svc'@'%' IDENTIFIED BY '...'; GRANT ALL ON catalog.* TO 'catalog_svc'@'%'; and no grant for orders_svc. On SQL Server use CREATE SCHEMA catalog AUTHORIZATION catalog_svc and GRANT SELECT ON SCHEMA::catalog TO .... In MongoDB, a database per service with a user whose role is readWrite on that database only.
The brownfield moves in SQL
-- 1. Database view: a limited, read-only face for readers you cannot change yet.
CREATE SCHEMA legacy_compat;
CREATE VIEW legacy_compat.products_v WITH (security_barrier = true) AS
SELECT id, sku, name, active FROM catalog.products WHERE deleted_at IS NULL;
CREATE ROLE reporting_ro LOGIN PASSWORD 'ro';
GRANT USAGE ON SCHEMA legacy_compat TO reporting_ro;
GRANT SELECT ON legacy_compat.products_v TO reporting_ro; -- no grant on catalog.* at all
-- 2. Split table: stock columns leave products and get their own owner.
CREATE SCHEMA inventory;
CREATE TABLE inventory.stock AS
SELECT id AS product_id, stock_qty AS qty, warehouse_bin AS bin FROM public.products;
ALTER TABLE inventory.stock ADD PRIMARY KEY (product_id);
ALTER TABLE public.products DROP COLUMN stock_qty, DROP COLUMN warehouse_bin;
-- 3. Move the foreign key to code: the constraint goes, the id stays.
ALTER TABLE public.orders DROP CONSTRAINT orders_product_id_fkey;
-- Integrity is now a job: find orphans the API check or a delete let through.
SELECT o.id, o.product_id FROM public.orders o
LEFT JOIN catalog.products p ON p.id = o.product_id
WHERE p.id IS NULL; -- only possible while both still live in one database
-- 4. Soft delete instead of DELETE, so references stay resolvable (tombstone).
UPDATE catalog.products SET deleted_at = now(), active = false WHERE id = 'p-3';PostgreSQL makes "simple views" automatically updatable ("Simple views are automatically updatable: the system will allow INSERT, UPDATE, DELETE, and MERGE statements to be used on the view"); a view joining two tables is not, which is exactly why a join view is a safe read-only compat layer. Add WITH CHECK OPTION if you do allow writes through a single-table view, so rows cannot be written that the view would not show. security_barrier makes the view's own WHERE run before user-supplied conditions, so a crafted function cannot see filtered rows. For reads across databases during a transition, postgres_fdw ("can be used to access data stored in external PostgreSQL servers") with IMPORT FOREIGN SCHEMA gives a temporary bridge; logical replication ("replicating data objects and their changes, based upon their replication identity") gives a temporary copy.
Error messages you will see
| Where | Message | Meaning |
|---|---|---|
| PostgreSQL | ERROR: permission denied for schema catalog (SQLSTATE 42501) | A service reached into another's schema; the boundary held |
| PostgreSQL | ERROR: permission denied for table products (42501) | Schema usage granted but not the table |
| PostgreSQL | ERROR: cannot insert into view "products" / DETAIL: Views that do not select from a single table or view are not automatically updatable. | An old writer hit the read-only compat view |
| PostgreSQL | ERROR: column "price_cents" does not exist (42703) | Reader asked for a column the view hides |
| PostgreSQL | ERROR: update or delete on table "products" violates foreign key constraint "orders_product_id_fkey" on table "orders" (23503) | Before moving the FK to code |
| PostgreSQL | ERROR: null value in column "tax_id" ... violates not-null constraint (23502) | Shared-table schema change broke another writer |
| MySQL | ERROR 1142 (42000): SELECT command denied to user 'orders_svc'@'%' for table 'products' | Cross-database read blocked |
| MySQL | ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails | FK still in place |
| Go (this page) | orders: product does not exist or is inactive: p-9 | The FK-in-code check (ErrUnknownProduct) |
| Laravel | Illuminate\Database\QueryException with code 42501 | Boundary test passed or production code leaked |
Measuring consistency lag
-- Outbox: how far behind is the relay right now? (alert if > SLO)
SELECT count(*) AS unpublished,
EXTRACT(EPOCH FROM now() - min(created_at)) AS oldest_unpublished_s
FROM orders.outbox WHERE published_at IS NULL;
-- Outbox: publish lag distribution over the last hour.
SELECT percentile_cont(ARRAY[0.5, 0.95, 0.99]) WITHIN GROUP
(ORDER BY EXTRACT(EPOCH FROM published_at - created_at)) AS p50_p95_p99_s
FROM orders.outbox WHERE published_at > now() - interval '1 hour';
-- CDC on PostgreSQL: WAL a logical slot still holds back (Debezium, logical replication).
SELECT slot_name, active,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn)) AS behind
FROM pg_replication_slots WHERE slot_type = 'logical';Go
Six small packages: two owners with their own pools, a composer, a relay, a read model and a tracer write. Stdlib plus the pgx driver; go vet and go test clean.
Two owners, two pools
// Command pools shows two services' data access side by side in one process
// (a modular monolith on its way out): two DSNs, two credentials, two pools.
// Each pool can reach only its own schema, so a cross-schema query fails with
// SQLSTATE 42501 instead of quietly creating coupling.
package main
import (
"context"
"database/sql"
"fmt"
"log"
"os"
"time"
_ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" driver
)
func open(dsn string, maxOpen int) (*sql.DB, error) {
db, err := sql.Open("pgx", dsn)
if err != nil {
return nil, err
}
db.SetMaxOpenConns(maxOpen) // budget per service, not per process
db.SetMaxIdleConns(maxOpen / 2)
db.SetConnMaxLifetime(30 * time.Minute)
return db, nil
}
func main() {
ordersDSN, catalogDSN := os.Getenv("ORDERS_DSN"), os.Getenv("CATALOG_DSN")
if ordersDSN == "" || catalogDSN == "" {
fmt.Println("set ORDERS_DSN (role orders_svc) and CATALOG_DSN (role catalog_svc)")
return
}
orders, err := open(ordersDSN, 20)
if err != nil {
log.Fatal(err)
}
defer orders.Close()
catalog, err := open(catalogDSN, 10)
if err != nil {
log.Fatal(err)
}
defer catalog.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var n int
if err := orders.QueryRowContext(ctx, `SELECT count(*) FROM orders.orders`).Scan(&n); err != nil {
log.Fatal(err)
}
fmt.Println("orders visible to orders_svc:", n)
// The boundary in action: Orders' credentials cannot read Catalog's table.
err = orders.QueryRowContext(ctx, `SELECT count(*) FROM catalog.products`).Scan(&n)
fmt.Println("orders_svc reading catalog.products:", err)
// Expected: ERROR: permission denied for schema catalog (SQLSTATE 42501)
}Catalog: the only door to products
// Package catalog is the Catalog service. It is the only writer and the
// only reader of the catalog schema; everybody else uses ListByIDs over HTTP.
package catalog
import (
"context"
"database/sql"
"encoding/json"
"net/http"
"strings"
)
// Product is the published shape of a product. It is a contract, not the table.
type Product struct {
ID string `json:"id"`
Name string `json:"name"`
PriceCents int64 `json:"price_cents"`
Active bool `json:"active"`
}
// Store reads products from the catalog schema.
type Store interface {
ListByIDs(ctx context.Context, ids []string) ([]Product, error)
}
// SQLStore uses a pool whose credentials can only reach the catalog schema.
type SQLStore struct{ DB *sql.DB }
// ListByIDs loads many products in one round trip (no N+1 across the network).
func (s SQLStore) ListByIDs(ctx context.Context, ids []string) ([]Product, error) {
const q = `SELECT id, name, price_cents, active
FROM catalog.products
WHERE id = ANY($1::text[])`
rows, err := s.DB.QueryContext(ctx, q, "{"+strings.Join(ids, ",")+"}")
if err != nil {
return nil, err
}
defer rows.Close()
var out []Product
for rows.Next() {
var p Product
if err := rows.Scan(&p.ID, &p.Name, &p.PriceCents, &p.Active); err != nil {
return nil, err
}
out = append(out, p)
}
return out, rows.Err()
}
// Handler serves GET /products?ids=p1,p2 for the composer and for Orders.
func Handler(store Store) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /products", func(w http.ResponseWriter, r *http.Request) {
raw := r.URL.Query().Get("ids")
if raw == "" {
http.Error(w, "ids is required", http.StatusBadRequest)
return
}
ids := strings.Split(raw, ",")
if len(ids) > 100 {
http.Error(w, "at most 100 ids per call", http.StatusBadRequest)
return
}
products, err := store.ListByIDs(r.Context(), ids)
if err != nil {
http.Error(w, "catalog unavailable", http.StatusServiceUnavailable)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(products)
})
return mux
}Orders: FK in code, state and outbox in one transaction
// Package orders is the Orders service. It owns the orders schema, including
// its outbox. product_id is stored as a plain value: the foreign key to the
// catalog moved from the database into code (ProductChecker).
package orders
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"time"
)
// ErrUnknownProduct replaces the old FK violation (SQLSTATE 23503).
var ErrUnknownProduct = errors.New("orders: product does not exist or is inactive")
// ProductChecker is the "foreign key in code". Catalog answers it over HTTP,
// or a local replica of catalog reference data answers it without a network hop.
type ProductChecker interface {
ActiveProducts(ctx context.Context, ids []string) (map[string]int64, error) // id -> price
}
// Line is one order line as the client sends it.
type Line struct {
ProductID string `json:"product_id"`
Qty int `json:"qty"`
}
// OrderPlaced is the integration event other services may rely on.
type OrderPlaced struct {
EventID string `json:"event_id"`
OrderID string `json:"order_id"`
CustomerID string `json:"customer_id"`
TotalCents int64 `json:"total_cents"`
Lines []Line `json:"lines"`
Version int64 `json:"version"`
OccurredAt time.Time `json:"occurred_at"`
}
// Service writes only to the orders schema.
type Service struct {
DB *sql.DB
Products ProductChecker
NewID func() string
Now func() time.Time
}
// PlaceOrder validates references in code, then writes the order and its
// outbox row in ONE local transaction. No 2PC, no call to a broker here.
func (s Service) PlaceOrder(ctx context.Context, customerID string, lines []Line) (string, error) {
ids := make([]string, 0, len(lines))
for _, l := range lines {
ids = append(ids, l.ProductID)
}
prices, err := s.Products.ActiveProducts(ctx, ids)
if err != nil {
return "", fmt.Errorf("check products: %w", err)
}
var total int64
for _, l := range lines {
price, ok := prices[l.ProductID]
if !ok {
return "", fmt.Errorf("%w: %s", ErrUnknownProduct, l.ProductID)
}
total += price * int64(l.Qty)
}
orderID, now := s.NewID(), s.Now().UTC()
evt := OrderPlaced{EventID: s.NewID(), OrderID: orderID, CustomerID: customerID,
TotalCents: total, Lines: lines, Version: 1, OccurredAt: now}
payload, err := json.Marshal(evt)
if err != nil {
return "", err
}
tx, err := s.DB.BeginTx(ctx, nil)
if err != nil {
return "", err
}
defer tx.Rollback() //nolint:errcheck // no-op after Commit
if _, err := tx.ExecContext(ctx,
`INSERT INTO orders.orders (id, customer_id, total_cents, status, version, created_at)
VALUES ($1, $2, $3, 'PLACED', 1, $4)`, orderID, customerID, total, now); err != nil {
return "", err
}
for _, l := range lines {
// product_id has no REFERENCES clause: catalog.products lives in another service.
if _, err := tx.ExecContext(ctx,
`INSERT INTO orders.order_lines (order_id, product_id, qty, unit_price_cents)
VALUES ($1, $2, $3, $4)`, orderID, l.ProductID, l.Qty, prices[l.ProductID]); err != nil {
return "", err
}
}
if _, err := tx.ExecContext(ctx,
`INSERT INTO orders.outbox (event_id, aggregate_type, aggregate_id, event_type, payload, created_at)
VALUES ($1, 'order', $2, 'OrderPlaced.v1', $3, $4)`, evt.EventID, orderID, payload, now); err != nil {
return "", err
}
return orderID, tx.Commit()
}API composition with a latency budget
// Package composer implements API composition: one query, answered by
// calling the services that own the data and joining the results in memory.
package composer
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"time"
)
// OrderView is what Orders returns for one order.
type OrderView struct {
ID string `json:"id"`
CustomerID string `json:"customer_id"`
Status string `json:"status"`
Lines []struct {
ProductID string `json:"product_id"`
Qty int `json:"qty"`
} `json:"lines"`
}
// ProductView is what Catalog returns per product.
type ProductView struct {
ID string `json:"id"`
Name string `json:"name"`
}
// LineDetails is one joined row.
type LineDetails struct {
ProductID string `json:"product_id"`
Name string `json:"name"` // empty when Catalog did not answer
Qty int `json:"qty"`
}
// OrderDetails is the composed answer. Partial tells the client that a
// non-essential owner (Catalog) did not answer in time.
type OrderDetails struct {
OrderID string `json:"order_id"`
Status string `json:"status"`
Lines []LineDetails `json:"lines"`
Partial bool `json:"partial"`
}
// Composer knows where each owner lives. It owns no data itself.
type Composer struct {
Client *http.Client
OrdersURL string
CatalogURL string
Budget time.Duration // total latency budget for the whole composition
}
// OrderDetails calls Orders (essential) and then Catalog (enrichment) with one
// batched request, never one request per line.
func (c Composer) OrderDetails(ctx context.Context, orderID string) (OrderDetails, error) {
ctx, cancel := context.WithTimeout(ctx, c.Budget)
defer cancel()
var order OrderView
if err := c.getJSON(ctx, c.OrdersURL+"/orders/"+url.PathEscape(orderID), &order); err != nil {
return OrderDetails{}, fmt.Errorf("orders: %w", err) // owner of the main record: fail
}
ids := make([]string, 0, len(order.Lines))
for _, l := range order.Lines {
ids = append(ids, l.ProductID)
}
names := map[string]string{}
partial := false
var products []ProductView
if err := c.getJSON(ctx, c.CatalogURL+"/products?ids="+url.QueryEscape(strings.Join(ids, ",")), &products); err != nil {
partial = true // degrade: show the order without product names
}
for _, p := range products {
names[p.ID] = p.Name
}
out := OrderDetails{OrderID: order.ID, Status: order.Status, Partial: partial}
for _, l := range order.Lines {
out.Lines = append(out.Lines, LineDetails{ProductID: l.ProductID, Name: names[l.ProductID], Qty: l.Qty})
}
return out, nil
}
func (c Composer) getJSON(ctx context.Context, u string, dst any) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return err
}
resp, err := c.Client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("%s: status %d", u, resp.StatusCode)
}
return json.NewDecoder(resp.Body).Decode(dst)
}package composer
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func ordersStub() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(`{"id":"o-1","customer_id":"c-9","status":"PLACED",
"lines":[{"product_id":"p-1","qty":2},{"product_id":"p-2","qty":1}]}`))
}))
}
func TestComposesBothOwners(t *testing.T) {
orders := ordersStub()
defer orders.Close()
catalog := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.URL.Query().Get("ids"); got != "p-1,p-2" {
t.Errorf("expected one batched call, got ids=%q", got)
}
_, _ = w.Write([]byte(`[{"id":"p-1","name":"Kettle"},{"id":"p-2","name":"Mug"}]`))
}))
defer catalog.Close()
c := Composer{Client: http.DefaultClient, OrdersURL: orders.URL, CatalogURL: catalog.URL, Budget: time.Second}
got, err := c.OrderDetails(context.Background(), "o-1")
if err != nil {
t.Fatal(err)
}
if got.Partial || got.Lines[0].Name != "Kettle" || got.Lines[1].Name != "Mug" {
t.Fatalf("unexpected result: %+v", got)
}
}
func TestDegradesWhenCatalogIsDown(t *testing.T) {
orders := ordersStub()
defer orders.Close()
catalog := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "down", http.StatusServiceUnavailable)
}))
defer catalog.Close()
c := Composer{Client: http.DefaultClient, OrdersURL: orders.URL, CatalogURL: catalog.URL, Budget: time.Second}
got, err := c.OrderDetails(context.Background(), "o-1")
if err != nil {
t.Fatal(err)
}
if !got.Partial || len(got.Lines) != 2 || got.Lines[0].Name != "" {
t.Fatalf("expected a partial answer with lines but no names, got %+v", got)
}
}Outbox relay with a lag measurement
// Package relay moves rows from orders.outbox to a broker and measures the
// consistency lag that every downstream read model inherits.
// The full pattern (polling vs CDC, ordering, broker specifics) is in
// /messaging/outbox-pattern; this is the minimum needed for the lab.
package relay
import (
"context"
"database/sql"
"time"
)
// Publisher hides the broker (RabbitMQ, Kafka, Redis Streams, ...).
type Publisher interface {
Publish(ctx context.Context, key, eventType string, payload []byte) error
}
// LagObserver receives "commit -> published" delay for each event.
// Wire it to a Prometheus histogram such as outbox_publish_lag_seconds.
type LagObserver func(eventType string, lag time.Duration)
// Relay publishes in batches. Several replicas may run: SKIP LOCKED makes
// them take different rows instead of waiting on each other.
type Relay struct {
DB *sql.DB
Pub Publisher
Observe LagObserver
BatchSize int
Now func() time.Time
}
// Once publishes one batch and returns how many rows it handled.
func (r Relay) Once(ctx context.Context) (int, error) {
tx, err := r.DB.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
defer tx.Rollback() //nolint:errcheck // no-op after Commit
rows, err := tx.QueryContext(ctx, `
SELECT id, aggregate_id, event_type, payload, created_at
FROM orders.outbox
WHERE published_at IS NULL
ORDER BY id
LIMIT $1
FOR UPDATE SKIP LOCKED`, r.BatchSize)
if err != nil {
return 0, err
}
type row struct {
id int64
key, eventType string
payload []byte
createdAt time.Time
}
var batch []row
for rows.Next() {
var x row
if err := rows.Scan(&x.id, &x.key, &x.eventType, &x.payload, &x.createdAt); err != nil {
rows.Close()
return 0, err
}
batch = append(batch, x)
}
rows.Close()
if err := rows.Err(); err != nil {
return 0, err
}
for _, x := range batch {
// At-least-once: if we crash after Publish and before Commit, the row is
// published again. Consumers must be idempotent (see readmodel).
if err := r.Pub.Publish(ctx, x.key, x.eventType, x.payload); err != nil {
return 0, err
}
if _, err := tx.ExecContext(ctx,
`UPDATE orders.outbox SET published_at = now() WHERE id = $1`, x.id); err != nil {
return 0, err
}
if r.Observe != nil {
r.Observe(x.eventType, r.Now().Sub(x.createdAt))
}
}
return len(batch), tx.Commit()
}
// OldestUnpublishedAge is the alerting signal: if it grows, every read model
// built from this outbox is getting staler.
func OldestUnpublishedAge(ctx context.Context, db *sql.DB) (time.Duration, error) {
var secs sql.NullFloat64
err := db.QueryRowContext(ctx, `
SELECT EXTRACT(EPOCH FROM now() - min(created_at))
FROM orders.outbox WHERE published_at IS NULL`).Scan(&secs)
if err != nil || !secs.Valid {
return 0, err
}
return time.Duration(secs.Float64 * float64(time.Second)), nil
}CQRS read model from two owners
// Package readmodel builds a CQRS read model (a "view database") from events
// published by two owners: Orders (OrderPlaced) and Catalog (ProductRenamed).
// The read model owns nothing: it can be dropped and rebuilt from the events.
package readmodel
import (
"context"
"database/sql"
"encoding/json"
"time"
)
// Envelope is the broker message after decoding the outer layer.
type Envelope struct {
EventID string `json:"event_id"`
Type string `json:"type"` // "OrderPlaced.v1" | "ProductRenamed.v1"
Version int64 `json:"version"`
OccurredAt time.Time `json:"occurred_at"`
Data json.RawMessage `json:"data"`
}
type orderPlaced struct {
OrderID string `json:"order_id"`
CustomerID string `json:"customer_id"`
TotalCents int64 `json:"total_cents"`
Lines []struct {
ProductID string `json:"product_id"`
} `json:"lines"`
}
type productRenamed struct {
ProductID string `json:"product_id"`
Name string `json:"name"`
}
// Lag is reported per event so dashboards show "how stale is this view".
type Lag func(eventType string, d time.Duration)
// Projector applies events idempotently. SQL lives in the store so the same
// projector runs against PostgreSQL in production and memory in tests.
type Projector struct {
Store Store
Lag Lag
Now func() time.Time
}
// Store is the read-model database.
type Store interface {
// Seen records the event id; false means it was already applied (inbox).
Seen(ctx context.Context, eventID string) (bool, error)
UpsertOrder(ctx context.Context, orderID, customerID string, totalCents int64, productIDs []string, version int64) error
RenameProduct(ctx context.Context, productID, name string, version int64) error
}
// Handle is called by the consumer for each message.
func (p Projector) Handle(ctx context.Context, e Envelope) error {
fresh, err := p.Store.Seen(ctx, e.EventID)
if err != nil || !fresh {
return err // duplicate delivery: nothing to do
}
switch e.Type {
case "OrderPlaced.v1":
var d orderPlaced
if err := json.Unmarshal(e.Data, &d); err != nil {
return err
}
ids := make([]string, 0, len(d.Lines))
for _, l := range d.Lines {
ids = append(ids, l.ProductID)
}
err = p.Store.UpsertOrder(ctx, d.OrderID, d.CustomerID, d.TotalCents, ids, e.Version)
case "ProductRenamed.v1":
var d productRenamed
if err := json.Unmarshal(e.Data, &d); err != nil {
return err
}
err = p.Store.RenameProduct(ctx, d.ProductID, d.Name, e.Version)
default:
return nil // tolerant reader: ignore unknown event types
}
if err == nil && p.Lag != nil {
p.Lag(e.Type, p.Now().Sub(e.OccurredAt))
}
return err
}
// SQLStore is the PostgreSQL implementation. Seen and the write must share a
// transaction in production; the tx is carried in ctx by the consumer (omitted).
type SQLStore struct{ DB *sql.DB }
// Seen inserts into the inbox; a conflict means "already processed".
func (s SQLStore) Seen(ctx context.Context, eventID string) (bool, error) {
res, err := s.DB.ExecContext(ctx,
`INSERT INTO reporting.inbox (event_id) VALUES ($1) ON CONFLICT DO NOTHING`, eventID)
if err != nil {
return false, err
}
n, err := res.RowsAffected()
return n == 1, err
}
// UpsertOrder ignores older versions so out-of-order delivery cannot go back in time.
func (s SQLStore) UpsertOrder(ctx context.Context, orderID, customerID string, total int64, productIDs []string, version int64) error {
ids, _ := json.Marshal(productIDs)
_, err := s.DB.ExecContext(ctx, `
INSERT INTO reporting.order_summaries (order_id, customer_id, total_cents, product_ids, version)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (order_id) DO UPDATE
SET customer_id = EXCLUDED.customer_id, total_cents = EXCLUDED.total_cents,
product_ids = EXCLUDED.product_ids, version = EXCLUDED.version
WHERE reporting.order_summaries.version < EXCLUDED.version`,
orderID, customerID, total, ids, version)
return err
}
// RenameProduct keeps a local copy of Catalog's reference data for joins.
func (s SQLStore) RenameProduct(ctx context.Context, productID, name string, version int64) error {
_, err := s.DB.ExecContext(ctx, `
INSERT INTO reporting.product_names (product_id, name, version) VALUES ($1, $2, $3)
ON CONFLICT (product_id) DO UPDATE SET name = EXCLUDED.name, version = EXCLUDED.version
WHERE reporting.product_names.version < EXCLUDED.version`, productID, name, version)
return err
}package readmodel
import (
"context"
"sync"
)
// MemoryStore is a test double with the same idempotency and version rules.
type MemoryStore struct {
mu sync.Mutex
seen map[string]bool
Orders map[string]OrderRow
Products map[string]NameRow
}
// OrderRow is one row of order_summaries.
type OrderRow struct {
CustomerID string
TotalCents int64
ProductIDs []string
Version int64
}
// NameRow is one row of product_names.
type NameRow struct {
Name string
Version int64
}
// NewMemoryStore returns an empty store.
func NewMemoryStore() *MemoryStore {
return &MemoryStore{seen: map[string]bool{}, Orders: map[string]OrderRow{}, Products: map[string]NameRow{}}
}
// Seen implements Store.
func (m *MemoryStore) Seen(_ context.Context, id string) (bool, error) {
m.mu.Lock()
defer m.mu.Unlock()
if m.seen[id] {
return false, nil
}
m.seen[id] = true
return true, nil
}
// UpsertOrder implements Store.
func (m *MemoryStore) UpsertOrder(_ context.Context, id, customer string, total int64, pids []string, v int64) error {
m.mu.Lock()
defer m.mu.Unlock()
if cur, ok := m.Orders[id]; ok && cur.Version >= v {
return nil
}
m.Orders[id] = OrderRow{CustomerID: customer, TotalCents: total, ProductIDs: pids, Version: v}
return nil
}
// RenameProduct implements Store.
func (m *MemoryStore) RenameProduct(_ context.Context, id, name string, v int64) error {
m.mu.Lock()
defer m.mu.Unlock()
if cur, ok := m.Products[id]; ok && cur.Version >= v {
return nil
}
m.Products[id] = NameRow{Name: name, Version: v}
return nil
}package readmodel
import (
"context"
"encoding/json"
"testing"
"time"
)
func env(id, typ string, v int64, data any) Envelope {
raw, _ := json.Marshal(data)
return Envelope{EventID: id, Type: typ, Version: v, OccurredAt: time.Unix(100, 0), Data: raw}
}
func TestDuplicatesAndOldVersionsAreIgnored(t *testing.T) {
store := NewMemoryStore()
var lags []time.Duration
p := Projector{Store: store, Now: func() time.Time { return time.Unix(102, 0) },
Lag: func(_ string, d time.Duration) { lags = append(lags, d) }}
ctx := context.Background()
steps := []Envelope{
env("e1", "ProductRenamed.v1", 2, map[string]string{"product_id": "p-1", "name": "Kettle XL"}),
env("e1", "ProductRenamed.v1", 2, map[string]string{"product_id": "p-1", "name": "Kettle XL"}), // redelivered
env("e0", "ProductRenamed.v1", 1, map[string]string{"product_id": "p-1", "name": "Kettle"}), // late, older
}
for _, e := range steps {
if err := p.Handle(ctx, e); err != nil {
t.Fatal(err)
}
}
if got := store.Products["p-1"]; got.Name != "Kettle XL" || got.Version != 2 {
t.Fatalf("read model went back in time: %+v", got)
}
if len(lags) != 2 || lags[0] != 2*time.Second {
t.Fatalf("expected two applied events with 2s lag, got %v", lags)
}
}package readmodel
import (
"encoding/json"
"fmt"
"time"
)
// FromOutbox turns what the relay publishes (event type + the outbox payload
// written by the producer, e.g. orders.OrderPlaced) into an Envelope. The
// payload carries event_id, version and occurred_at at the top level; the
// whole payload is kept as Data so the projector can decode its own fields.
func FromOutbox(eventType string, payload []byte) (Envelope, error) {
var meta struct {
EventID string `json:"event_id"`
Version int64 `json:"version"`
OccurredAt time.Time `json:"occurred_at"`
}
if err := json.Unmarshal(payload, &meta); err != nil {
return Envelope{}, fmt.Errorf("decode %s: %w", eventType, err)
}
if meta.EventID == "" {
return Envelope{}, fmt.Errorf("decode %s: missing event_id", eventType)
}
return Envelope{EventID: meta.EventID, Type: eventType, Version: meta.Version,
OccurredAt: meta.OccurredAt, Data: json.RawMessage(payload)}, nil
}package readmodel
import (
"context"
"encoding/json"
"testing"
"time"
"academy/microservices-data-ownership/orders"
)
// The producer's real event goes through the relay shape into the projector.
func TestOrderPlacedFromOutboxReachesReadModel(t *testing.T) {
evt := orders.OrderPlaced{EventID: "e-9", OrderID: "o-1", CustomerID: "c-1", TotalCents: 4800,
Lines: []orders.Line{{ProductID: "p-1", Qty: 2}}, Version: 1, OccurredAt: time.Unix(100, 0).UTC()}
payload, err := json.Marshal(evt)
if err != nil {
t.Fatal(err)
}
env, err := FromOutbox("OrderPlaced.v1", payload)
if err != nil {
t.Fatal(err)
}
store := NewMemoryStore()
p := Projector{Store: store, Now: func() time.Time { return time.Unix(101, 0) }}
if err := p.Handle(context.Background(), env); err != nil {
t.Fatal(err)
}
got, ok := store.Orders["o-1"]
if !ok || got.TotalCents != 4800 || got.ProductIDs[0] != "p-1" {
t.Fatalf("order not projected: %+v", store.Orders)
}
}Tracer write during extraction
// Package tracer shows Newman's "tracer write" in the monolith during the
// extraction of an Invoicing service. The monolith stays the source of truth
// for a while, writes go to both, reads switch by flag, and a reconciler
// proves the two agree before the old table is retired.
package tracer
import (
"context"
"errors"
"fmt"
"log/slog"
)
// Invoice is the slice of data being moved.
type Invoice struct {
ID string
CustomerID string
AmountCents int64
Status string
}
// Source is one source of truth: the old monolith table or the new service API.
type Source interface {
Save(ctx context.Context, inv Invoice) error
Get(ctx context.Context, id string) (Invoice, error)
}
// Phase is the migration step, driven by a feature flag.
type Phase int
// The phases follow "synchronize data in application": write old only,
// write both / read old, write both / read new, write new only.
const (
OldOnly Phase = iota
DualWriteReadOld
DualWriteReadNew
NewOnly
)
// Writer is used by monolith code instead of the old repository.
type Writer struct {
Old, New Source
Phase func() Phase
Log *slog.Logger
}
// Save writes to the primary for this phase first. A failed secondary write
// does not fail the user request; it is logged and repaired by Reconcile.
func (w Writer) Save(ctx context.Context, inv Invoice) error {
switch w.Phase() {
case OldOnly:
return w.Old.Save(ctx, inv)
case DualWriteReadOld:
if err := w.Old.Save(ctx, inv); err != nil {
return err
}
if err := w.New.Save(ctx, inv); err != nil {
w.Log.Warn("tracer write to new source failed", "invoice", inv.ID, "err", err)
}
return nil
case DualWriteReadNew:
if err := w.New.Save(ctx, inv); err != nil {
return err
}
if err := w.Old.Save(ctx, inv); err != nil {
w.Log.Warn("fallback write to old source failed", "invoice", inv.ID, "err", err)
}
return nil
default:
return w.New.Save(ctx, inv)
}
}
// Get reads from whichever source is the source of truth in this phase.
func (w Writer) Get(ctx context.Context, id string) (Invoice, error) {
if w.Phase() >= DualWriteReadNew {
return w.New.Get(ctx, id)
}
return w.Old.Get(ctx, id)
}
// ErrMismatch is returned when the two sources disagree.
var ErrMismatch = errors.New("tracer: sources disagree")
// Reconcile compares the two sources for a set of ids (a nightly job, or a
// sample on every read during dual-run) and repairs the follower.
func Reconcile(ctx context.Context, truth, follower Source, ids []string) (repaired int, err error) {
for _, id := range ids {
want, err := truth.Get(ctx, id)
if err != nil {
return repaired, err
}
got, err := follower.Get(ctx, id)
if err == nil && got == want {
continue
}
if err := follower.Save(ctx, want); err != nil {
return repaired, fmt.Errorf("%w: %s: %v", ErrMismatch, id, err)
}
repaired++
}
return repaired, nil
}package tracer
import (
"context"
"errors"
"io"
"log/slog"
"testing"
)
type mem struct {
rows map[string]Invoice
fail bool
}
func (m *mem) Save(_ context.Context, inv Invoice) error {
if m.fail {
return errors.New("unavailable")
}
m.rows[inv.ID] = inv
return nil
}
func (m *mem) Get(_ context.Context, id string) (Invoice, error) {
inv, ok := m.rows[id]
if !ok {
return Invoice{}, errors.New("not found")
}
return inv, nil
}
func TestDualRunThenReconcile(t *testing.T) {
ctx := context.Background()
old := &mem{rows: map[string]Invoice{}}
nu := &mem{rows: map[string]Invoice{}, fail: true} // new service is down at first
w := Writer{Old: old, New: nu, Phase: func() Phase { return DualWriteReadOld },
Log: slog.New(slog.NewTextHandler(io.Discard, nil))}
inv := Invoice{ID: "inv-1", CustomerID: "c-1", AmountCents: 4200, Status: "OPEN"}
if err := w.Save(ctx, inv); err != nil {
t.Fatalf("a failed tracer write must not fail the user: %v", err)
}
nu.fail = false
n, err := Reconcile(ctx, old, nu, []string{"inv-1"})
if err != nil || n != 1 {
t.Fatalf("expected one repair, got %d, %v", n, err)
}
w.Phase = func() Phase { return DualWriteReadNew }
got, err := w.Get(ctx, "inv-1")
if err != nil || got != inv {
t.Fatalf("read from new source: %+v, %v", got, err)
}
}The Go angle
- One
*sql.DBper owned store. The Go documentation explains that "The sql.DB database handle is safe for concurrent use by multiple goroutines" and that "each sql.DB manages a pool"; in a process that still hosts two modules, two handles with two credentials give two pools and two budgets (SetMaxOpenConns) instead of one shared pool that one module can exhaust (Connection Pooling). - Make the boundary a compile-time fact:
internal/packages per service so another module cannot import the repository (Modular Monolith). context.WithTimeoutgives the composer one latency budget across all owners;errgroupfits when the calls are independent and all are essential.FOR UPDATE SKIP LOCKEDlets several relay replicas share the outbox without blocking.- Watermill,
franz-gooramqp091-gosit behind thePublisherinterface; nothing in the services knows the broker.
Laravel
Connections per owner, read/write split and sticky reads
<?php
// config/database.php (excerpt). One connection per owned schema, each with
// its own credentials. A connection is a boundary only if its role is limited
// by GRANTs in the database; the name alone enforces nothing.
return [
'default' => env('DB_CONNECTION', 'orders'),
'connections' => [
// Orders service: writes go to the primary, reads to a replica.
'orders' => [
'driver' => 'pgsql',
'read' => ['host' => [env('ORDERS_DB_READ_HOST', '10.0.0.12')]],
'write' => ['host' => [env('ORDERS_DB_WRITE_HOST', '10.0.0.11')]],
// Read-your-writes inside one request: after a write, reads use the write PDO.
'sticky' => true,
'port' => env('ORDERS_DB_PORT', '5432'),
'database' => env('ORDERS_DB_DATABASE', 'shop'),
'username' => env('ORDERS_DB_USERNAME', 'orders_svc'),
'password' => env('ORDERS_DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'search_path' => 'orders',
'sslmode' => 'prefer',
],
// Catalog service: a different role that can see only the catalog schema.
'catalog' => [
'driver' => 'pgsql',
'host' => env('CATALOG_DB_HOST', '10.0.0.21'),
'port' => env('CATALOG_DB_PORT', '5432'),
'database' => env('CATALOG_DB_DATABASE', 'shop'),
'username' => env('CATALOG_DB_USERNAME', 'catalog_svc'),
'password' => env('CATALOG_DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'search_path' => 'catalog',
'sslmode' => 'prefer',
],
// Transitional: the legacy monolith database, reached only through the
// read-only views in the legacy_compat schema (Newman's "database view").
'legacy' => [
'driver' => 'pgsql',
'host' => env('LEGACY_DB_HOST', '10.0.0.31'),
'port' => env('LEGACY_DB_PORT', '5432'),
'database' => env('LEGACY_DB_DATABASE', 'monolith'),
'username' => env('LEGACY_DB_USERNAME', 'reporting_ro'),
'password' => env('LEGACY_DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'search_path' => 'legacy_compat',
'sslmode' => 'prefer',
],
// The legacy schema owner's own credentials, used only by its migrations.
'legacy_admin' => [
'driver' => 'pgsql',
'host' => env('LEGACY_DB_HOST', '10.0.0.31'),
'port' => env('LEGACY_DB_PORT', '5432'),
'database' => env('LEGACY_DB_DATABASE', 'monolith'),
'username' => env('LEGACY_ADMIN_USERNAME', 'monolith_owner'),
'password' => env('LEGACY_ADMIN_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'search_path' => 'public',
'sslmode' => 'prefer',
],
],
];The transitional database view, as a migration owned by the data owner
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
// Owned and run by the team that owns the legacy schema, not by its readers:
// a published view is an interface, like an API.
return new class extends Migration
{
/**
* The database connection that should be used by the migration.
*/
protected $connection = 'legacy_admin';
public function up(): void
{
DB::connection($this->connection)->statement('CREATE SCHEMA IF NOT EXISTS legacy_compat');
// Only the columns readers need; prices and supplier data stay hidden.
DB::connection($this->connection)->statement(<<<'SQL'
CREATE OR REPLACE VIEW legacy_compat.products_v
WITH (security_barrier = true) AS
SELECT p.id, p.sku, p.name, p.active
FROM public.products p
WHERE p.deleted_at IS NULL
SQL);
DB::connection($this->connection)->statement('REVOKE ALL ON SCHEMA public FROM reporting_ro');
DB::connection($this->connection)->statement('GRANT USAGE ON SCHEMA legacy_compat TO reporting_ro');
DB::connection($this->connection)->statement('GRANT SELECT ON legacy_compat.products_v TO reporting_ro');
}
public function down(): void
{
DB::connection($this->connection)->statement('DROP VIEW IF EXISTS legacy_compat.products_v');
}
};<?php
namespace App\Legacy\Models;
use Illuminate\Database\Eloquent\Attributes\Connection;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
use LogicException;
/**
* Read-only model over the transitional view. When Catalog is extracted, this
* class is replaced by an HTTP client and nothing else in the app changes.
*/
#[Connection('legacy')]
#[Table('products_v', timestamps: false)]
final class CatalogProduct extends Model
{
protected $casts = ['active' => 'boolean'];
public function save(array $options = []): bool
{
throw new LogicException('legacy_compat.products_v is read-only; write through Catalog.');
}
public function delete(): ?bool
{
throw new LogicException('legacy_compat.products_v is read-only; write through Catalog.');
}
}FK moved to code, state and outbox in one transaction
<?php
namespace App\Orders\Catalog;
use Illuminate\Support\Facades\Http;
use RuntimeException;
/**
* The foreign key moved to code: Orders asks Catalog whether products exist
* and what they cost, in ONE batched call, with a short timeout.
*/
final class HttpProductChecker
{
public function __construct(private readonly string $baseUrl) {}
/**
* @param list<string> $ids
* @return array<string, int> product id => price in cents (active products only)
*/
public function activeProducts(array $ids): array
{
$response = Http::timeout(2)
->retry(2, 100, throw: false)
->acceptJson()
->get($this->baseUrl.'/products', ['ids' => implode(',', $ids)]);
if ($response->failed()) {
throw new RuntimeException('Catalog unavailable: '.$response->status());
}
$prices = [];
foreach ($response->json() as $product) {
if ($product['active']) {
$prices[$product['id']] = (int) $product['price_cents'];
}
}
return $prices;
}
}<?php
namespace App\Orders\Actions;
use App\Orders\Catalog\HttpProductChecker;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use InvalidArgumentException;
final class PlaceOrder
{
public function __construct(private readonly HttpProductChecker $products) {}
/**
* @param list<array{product_id: string, qty: int}> $lines
*/
public function __invoke(string $customerId, array $lines): string
{
// 1. Reference check in code (was: FOREIGN KEY ... REFERENCES products).
$prices = $this->products->activeProducts(array_column($lines, 'product_id'));
$total = 0;
foreach ($lines as $line) {
if (! isset($prices[$line['product_id']])) {
throw new InvalidArgumentException("Unknown or inactive product {$line['product_id']}");
}
$total += $prices[$line['product_id']] * $line['qty'];
}
// 2. One local transaction on the service's own connection: state + outbox.
return DB::connection('orders')->transaction(function () use ($customerId, $lines, $prices, $total): string {
$orderId = (string) Str::uuid7();
$eventId = (string) Str::uuid7();
$now = now()->toImmutable();
DB::connection('orders')->table('orders')->insert([
'id' => $orderId,
'customer_id' => $customerId,
'total_cents' => $total,
'status' => 'PLACED',
'version' => 1,
'created_at' => $now,
]);
DB::connection('orders')->table('order_lines')->insert(array_map(fn (array $l): array => [
'order_id' => $orderId,
'product_id' => $l['product_id'],
'qty' => $l['qty'],
'unit_price_cents' => $prices[$l['product_id']],
], $lines));
DB::connection('orders')->table('outbox')->insert([
'event_id' => $eventId,
'aggregate_type' => 'order',
'aggregate_id' => $orderId,
'event_type' => 'OrderPlaced.v1',
'payload' => json_encode([
'event_id' => $eventId,
'order_id' => $orderId,
'customer_id' => $customerId,
'total_cents' => $total,
'lines' => $lines,
'version' => 1,
'occurred_at' => $now->format('Y-m-d\\TH:i:s.uP'),
], JSON_THROW_ON_ERROR),
'created_at' => $now,
]);
return $orderId;
});
}
}API composition with Http::pool
<?php
namespace App\Composition;
use Illuminate\Http\Client\Pool;
use Illuminate\Support\Facades\Http;
use RuntimeException;
use Throwable;
/**
* API composition at the edge (a BFF or gateway endpoint). It owns no data:
* it asks Orders for the order, then Catalog and Shipping in parallel, and
* joins in memory. Catalog and Shipping are enrichment: if they fail, the
* answer is partial instead of an error.
*/
final class OrderDetailsComposer
{
public function __construct(
private readonly string $ordersUrl,
private readonly string $catalogUrl,
private readonly string $shippingUrl,
) {}
/** @return array<string, mixed> */
public function __invoke(string $orderId): array
{
$order = Http::timeout(1)->acceptJson()->get("{$this->ordersUrl}/orders/{$orderId}");
if ($order->failed()) {
throw new RuntimeException("Orders could not return {$orderId}");
}
$ids = implode(',', array_column($order->json('lines'), 'product_id'));
$responses = Http::pool(fn (Pool $pool) => [
$pool->as('catalog')->timeout(1)->acceptJson()->get("{$this->catalogUrl}/products", ['ids' => $ids]),
$pool->as('shipping')->timeout(1)->acceptJson()->get("{$this->shippingUrl}/shipments", ['order_id' => $orderId]),
]);
$ok = fn (string $key): bool => ! $responses[$key] instanceof Throwable && $responses[$key]->successful();
$names = $ok('catalog')
? array_column($responses['catalog']->json(), 'name', 'id')
: [];
return [
'order_id' => $orderId,
'status' => $order->json('status'),
'lines' => array_map(fn (array $l): array => [
'product_id' => $l['product_id'],
'name' => $names[$l['product_id']] ?? null,
'qty' => $l['qty'],
], $order->json('lines')),
'shipment' => $ok('shipping') ? $responses['shipping']->json() : null,
'partial' => ! $ok('catalog') || ! $ok('shipping'),
];
}
}Read model projector
<?php
namespace App\Reporting\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
/**
* Consumer side of the CQRS read model, running in the Reporting service with
* its own 'reporting' connection. Idempotent (inbox) and version-aware.
*/
final class ProjectOrderPlaced implements ShouldQueue
{
use Queueable;
/** @param array<string, mixed> $event decoded OrderPlaced.v1 envelope */
public function __construct(public array $event) {}
public function handle(): void
{
DB::connection('reporting')->transaction(function (): void {
$fresh = DB::connection('reporting')->table('inbox')->insertOrIgnore([
'event_id' => $this->event['event_id'],
]);
if ($fresh === 0) {
return; // duplicate delivery from the at-least-once relay
}
DB::connection('reporting')->statement(<<<'SQL'
INSERT INTO order_summaries (order_id, customer_id, total_cents, product_ids, version)
VALUES (?, ?, ?, ?::jsonb, ?)
ON CONFLICT (order_id) DO UPDATE
SET customer_id = EXCLUDED.customer_id, total_cents = EXCLUDED.total_cents,
product_ids = EXCLUDED.product_ids, version = EXCLUDED.version
WHERE order_summaries.version < EXCLUDED.version
SQL, [
$this->event['order_id'],
$this->event['customer_id'],
$this->event['total_cents'],
json_encode(array_column($this->event['lines'], 'product_id'), JSON_THROW_ON_ERROR),
$this->event['version'],
]);
});
// Consistency lag: event time -> visible in the read model.
$lagMs = Carbon::parse($this->event['occurred_at'])->diffInMilliseconds(now());
Log::info('read_model_lag', ['event' => 'OrderPlaced.v1', 'lag_ms' => $lagMs]);
}
}Tracer write in the monolith
<?php
namespace App\Billing;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Throwable;
/**
* Tracer write inside the monolith while Invoicing is being extracted.
* config('migration.invoices_phase') moves through:
* old_only -> dual_read_old -> dual_read_new -> new_only
* A failed write to the secondary is logged and repaired by the reconciler
* (php artisan invoices:reconcile), never surfaced to the user.
*/
final class TracerWriteInvoices
{
public function __construct(private readonly string $invoicingUrl) {}
/** @param array{id: string, customer_id: string, amount_cents: int, status: string} $invoice */
public function save(array $invoice): void
{
$phase = config('migration.invoices_phase', 'old_only');
match ($phase) {
'old_only' => $this->writeOld($invoice),
'dual_read_old' => $this->primaryThenSecondary(fn () => $this->writeOld($invoice), fn () => $this->writeNew($invoice), $invoice['id']),
'dual_read_new' => $this->primaryThenSecondary(fn () => $this->writeNew($invoice), fn () => $this->writeOld($invoice), $invoice['id']),
'new_only' => $this->writeNew($invoice),
};
}
/** @return array<string, mixed>|null */
public function find(string $id): ?array
{
if (in_array(config('migration.invoices_phase'), ['dual_read_new', 'new_only'], true)) {
$response = Http::timeout(1)->get("{$this->invoicingUrl}/invoices/{$id}");
return $response->successful() ? $response->json() : null;
}
$row = DB::table('invoices')->where('id', $id)->first();
return $row ? (array) $row : null;
}
private function primaryThenSecondary(callable $primary, callable $secondary, string $id): void
{
$primary();
try {
$secondary();
} catch (Throwable $e) {
Log::warning('invoice tracer write failed', ['invoice' => $id, 'error' => $e->getMessage()]);
}
}
/** @param array<string, mixed> $invoice */
private function writeOld(array $invoice): void
{
DB::table('invoices')->upsert([$invoice], ['id'], ['customer_id', 'amount_cents', 'status']);
}
/** @param array<string, mixed> $invoice */
private function writeNew(array $invoice): void
{
// PUT with the id makes the write idempotent, so the reconciler can replay it.
Http::timeout(2)->put("{$this->invoicingUrl}/invoices/{$invoice['id']}", $invoice)->throw();
}
}Tests that keep ownership honest
<?php
namespace Tests\Feature;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;
/**
* Runs against a real PostgreSQL with the roles from the chapter's lab.
* It proves that the boundary is enforced by the database, not by goodwill.
*/
final class OwnershipBoundaryTest extends TestCase
{
public function test_orders_role_cannot_read_catalog_tables(): void
{
try {
DB::connection('orders')->table('catalog.products')->count();
$this->fail('orders_svc could read catalog.products: the boundary leaks');
} catch (QueryException $e) {
$this->assertSame('42501', $e->getCode()); // insufficient_privilege
}
}
public function test_legacy_view_hides_columns_readers_must_not_depend_on(): void
{
$view = Schema::connection('legacy');
foreach (['id', 'sku', 'name', 'active'] as $column) {
$this->assertTrue($view->hasColumn('products_v', $column), "missing {$column}");
}
$this->assertFalse($view->hasColumn('products_v', 'price_cents'), 'price leaked into the view');
}
}The Laravel angle
- Multiple connections. Laravel lets you pick a connection per call (
DB::connection('orders')), per model (the#[Connection('legacy')]attribute in Laravel 13) and per migration (protected $connection). A connection is a boundary only when its database role is limited; give each owner its own credentials. - Read/write splitting. The
read,writeandstickykeys split one owner's traffic across primary and replicas; withsticky, "any further "read" operations will use the "write" connection" after a write in the same request.PreventStaleDatabaseReadsextends that to later requests in the session "while your read replicas catch up". Neither helps across services: that is Consistency promised to clients. search_pathin thepgsqlconfig pins each connection to its schema, so unqualified table names resolve inside the owner.Http::poolruns the composer's calls concurrently; a failed connection comes back as aConnectionExceptionentry rather than throwing, which is how the composer returns a partial answer.- Queues and transactions. Jobs dispatched inside a transaction should run after commit (
after_commitinconfig/queue.php); for cross-service events still prefer the outbox (Laravel Queue Internals).
Solving the classic problems
"We need a JOIN across two services"
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| API composition | Composer calls owners, joins by id, batches | Live, simple | Latency, availability, no cross-owner filtering |
| Local copy of reference fields | Subscribe to owner's events, store needed columns | Local joins, available | Lag; must handle erasure |
| CQRS read model | Dedicated store built for the query | Fast, filterable, pageable | Projector, replay, lag |
| Move the query to the owner | The owner of the main entity enriches its own API | One call for clients | Owner grows a dependency |
| Merge the services | If every feature needs the join, the line is wrong | Local SQL | Bigger service |
"We need one transaction across two services"
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Saga + outbox | Local steps, compensations | Each service stays autonomous | No isolation; design pending states |
| Reorder steps (pivot) | Do the step that can fail first | Fewer compensations | Not always possible |
| Reservation / semantic lock | RESERVED state with expiry | Prevents double use | Expiry handling |
| Service consolidation | Merge the two | ACID | Coarser service |
"Two services write the same status column"
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Delegate | One owns the state machine; other calls a command API | One rule set | Write-path dependency |
| Table split | Each keeps its own state (account_status, verification_status) | Independence | Derived overall status needs composition |
| Data domain | Accept a jointly owned schema for tightly related services | ACID kept | Coordinated schema changes |
"Reports join everything"
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Reporting database via CDC | Debezium or logical replication into a warehouse | Analysts get SQL; OLTP untouched | Pipeline, schema mapping |
| Reporting DB via events | Projector writes star schema | Contract-based, stable | Events must carry enough |
| Nightly batch | Export per owner, load | Simple | Day-old data |
| Data products | Each domain publishes curated tables | Ownership of meaning | Platform and governance work |
"Deleting a row that other services reference"
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Soft delete / tombstone | deleted_at, keep the id resolvable | References never dangle | Storage; filters everywhere |
| Handle 404/410 gracefully | Consumers show "no longer available" | Owner free to delete | Every consumer must code it |
| Snapshot at reference time | Copy name/price into the referencing record | History stays correct | Duplication by design |
| Ask every consumer first | Owner checks before delete | Strict | Reverse dependency (the notes on Newman: "Don’t use") |
"Users do not see their own change"
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Return new state from the write | Client renders from the response | Zero lag for the writer | Others still see lag |
| Version token | Read model waits until version ≥ token or falls back | Precise | Read model exposes position |
| Route to owner for a while | After a write, read from owner for N seconds | Simple | Owner load |
| Sticky / session pinning | Within one database's replicas | Built in (Laravel) | Not across services |
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Greenfield, 2 to 10 services, one platform team | Schema per service on one managed PostgreSQL | One role per service, grant tests in CI | Real ownership at almost no cost |
| One service is hot or noisy | Move it to its own instance | Separate connection budget, own backups | Resource and failure isolation |
| Search, graph or time-series needs | Polyglot: that owner gets the right engine | CDC or events from the source owner | Ownership allows it |
| Small keyed join on a page | API composition | One batched call per owner, latency budget | Fresh and simple |
| Filtering/paging across owners | CQRS read model | Version tokens for read-your-writes | Composition cannot page across owners |
| Analytics | Reporting database or warehouse | CDC from outbox tables, not raw tables | Keeps OLTP private and fast |
| Invariant across two services must hold at every instant | Merge them (service consolidation) | Or a data domain shared by both | Saga gaps are unacceptable |
| Multi-step business process | Saga + outbox + inbox | Pending states visible to users | No 2PC between services |
| Legacy shared DB, teams cannot stop using it yet | Database view or wrapping service | Per-consumer credentials, usage logs | Stop the bleeding first |
| Moving a table to a new service | Tracer write / synchronize in application | Reconciler, flag per phase | Reversible at every step |
| Regulated or tenant-isolated data | Dedicated owner, physical isolation as required | Erasure events, region pinning | Compliance is checkable |
| Shared reference data (countries, currencies) | Replicate or library | Owner publishes changes | Availability without chatty calls |
In architecture: from a single process to a distributed system
Monolith: one process, one database
Everything is one application database in Fowler's sense, and that is fine. Ownership still matters for the future: group tables by module, name owners in a table, and avoid cross-module joins in new code. Everyday example: a small shop's Laravel app with products, orders, invoices in one PostgreSQL schema; the cheapest preparation is a repository per bounded context (one of Newman's patterns per the notes) so you can later see which code touches which tables.
Modular monolith and multiple databases
Each module gets a schema and, ideally, its own database role, while the deployable stays one (Modular Monolith). Cross-module reads go through module APIs in process; cross-module writes use in-process events plus an outbox if they must survive a crash. Example: the Go cmd/pools program above: Orders and Catalog live in one binary but have two pools, two credentials, and Orders' attempt to read catalog.products fails with 42501. This is Datadog's phase 1 in miniature: domain schemas with explicit ACLs inside the shared database.
Microservices: ownership across the network
What survives the move: the owner, the contract, local ACID. What does not: cross-owner joins (replace with composition or read models), cross-owner transactions (sagas with outbox and inbox), foreign keys across owners (checks in code, soft deletes, reconciliation). Production-style flow:
1 Client -> Orders: POST /orders (Idempotency-Key k-1)
2 Orders -> Catalog: GET /products?ids=p-1,p-2 FK in code
3 Orders: INSERT orders + order_lines + outbox one local tx
4 Relay -> broker: OrderPlaced.v1 (key = order id) publish lag observed
5 Reporting projector: inbox(event_id) + upsert summary idempotent, version-guarded
6 Client -> BFF: GET /orders/o-1 composition: Orders + Catalog + ShippingDistributed data: replicas, caches, CDC and regions
Every copy has a lag: read replicas inside one owner (Replication & Failover), caches of reference data, CDC-fed read stores, cross-region copies. Each is a place where read-your-writes can fail and where erasure must reach. Region-pinned owners satisfy residency; global read models must exclude data that may not leave its region. Two-way sync between regions or between old and new stores is the hardest case; avoid it unless you have conflict resolution (Eventual Consistency in Database Systems).
Scaling path: 1×, 10×, 100×
| Load | Data ownership shape |
|---|---|
| 1× | One cluster, schema per service, roles; composition for queries; reports on a replica |
| 10× | Hot owners on their own instances; read replicas per owner with sticky reads; read models for heavy screens; CDC into a warehouse |
| 100× | Owners shard internally (Partitioning & Sharding); per-region owners; read models per use case; data products for analytics; lag SLOs per copy |
Lab: from a shared schema to owned data, with a lag measurement
Not executed while writing this chapter (no running Docker daemon here); expected outputs are what PostgreSQL 17 prints for these statements. The Go part was run (go test ./...).
Setup:
-- docker run --rm -d --name own -e POSTGRES_PASSWORD=pg -p 5432:5432 postgres:17
-- psql -h localhost -U postgres
CREATE TABLE public.products (
id text PRIMARY KEY, sku text NOT NULL UNIQUE, name text NOT NULL,
price_cents bigint NOT NULL, active boolean NOT NULL DEFAULT true,
stock_qty int NOT NULL DEFAULT 0, warehouse_bin text, deleted_at timestamptz
);
CREATE TABLE public.orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, customer_id text NOT NULL,
product_id text NOT NULL REFERENCES public.products(id), qty int NOT NULL
);
INSERT INTO public.products (id, sku, name, price_cents, stock_qty, warehouse_bin) VALUES
('p-1', 'KET-1', 'Kettle', 3900, 12, 'A1'),
('p-2', 'MUG-1', 'Mug', 900, 80, 'B4'),
('p-3', 'TEA-1', 'Tea', 500, 0, 'C2');
INSERT INTO public.orders (customer_id, product_id, qty) VALUES ('c-1', 'p-1', 1), ('c-2', 'p-3', 2);Experiment 1: feel the shared-database coupling.
DELETE FROM public.products WHERE id = 'p-3';
-- ERROR: update or delete on table "products" violates foreign key constraint
-- "orders_product_id_fkey" on table "orders"
-- Catalog cannot even retire a product without knowing about Orders.Experiment 2: split table and move each part to its owner's schema.
CREATE SCHEMA catalog; CREATE SCHEMA inventory; CREATE SCHEMA orders;
CREATE TABLE inventory.stock AS
SELECT id AS product_id, stock_qty AS qty, warehouse_bin AS bin FROM public.products;
ALTER TABLE inventory.stock ADD PRIMARY KEY (product_id);
ALTER TABLE public.products DROP COLUMN stock_qty, DROP COLUMN warehouse_bin;
ALTER TABLE public.products SET SCHEMA catalog; -- FK follows the table
ALTER TABLE public.orders SET SCHEMA orders;
-- Compat view so old readers keep working (Newman's database view):
CREATE VIEW public.products AS
SELECT p.id, p.sku, p.name, p.price_cents, p.active, s.qty AS stock_qty, s.bin AS warehouse_bin, p.deleted_at
FROM catalog.products p JOIN inventory.stock s ON s.product_id = p.id;
SELECT id, name, stock_qty FROM public.products ORDER BY id;
-- p-1 | Kettle | 12
-- p-2 | Mug | 80
-- p-3 | Tea | 0
INSERT INTO public.products (id, sku, name, price_cents) VALUES ('p-4', 'X', 'X', 1);
-- ERROR: cannot insert into view "products"
-- DETAIL: Views that do not select from a single table or view are not automatically updatable.
-- Good: old writers are forced to the owner's API.Experiment 3: move the foreign key to code, use soft delete.
ALTER TABLE orders.orders DROP CONSTRAINT orders_product_id_fkey;
UPDATE catalog.products SET deleted_at = now(), active = false WHERE id = 'p-3';
-- Orphan check (works only while both schemas share a database; later: a reconciliation job)
SELECT o.id, o.product_id FROM orders.orders o
LEFT JOIN catalog.products p ON p.id = o.product_id WHERE p.id IS NULL;
-- (0 rows): soft delete kept p-3 resolvableExperiment 4: roles make ownership a hard error; a view is the only door for reporting.
CREATE ROLE orders_svc LOGIN PASSWORD 'o'; CREATE ROLE catalog_svc LOGIN PASSWORD 'c';
CREATE ROLE reporting_ro LOGIN PASSWORD 'r';
GRANT USAGE ON SCHEMA orders TO orders_svc; GRANT ALL ON ALL TABLES IN SCHEMA orders TO orders_svc;
GRANT USAGE ON SCHEMA catalog TO catalog_svc; GRANT ALL ON ALL TABLES IN SCHEMA catalog TO catalog_svc;
CREATE SCHEMA legacy_compat;
CREATE VIEW legacy_compat.products_v WITH (security_barrier = true) AS
SELECT id, sku, name, active FROM catalog.products WHERE deleted_at IS NULL;
GRANT USAGE ON SCHEMA legacy_compat TO reporting_ro;
GRANT SELECT ON legacy_compat.products_v TO reporting_ro;
SET ROLE orders_svc; SELECT count(*) FROM catalog.products;
-- ERROR: permission denied for schema catalog
RESET ROLE; SET ROLE reporting_ro;
SELECT id, name FROM legacy_compat.products_v ORDER BY id; -- p-1 Kettle, p-2 Mug (p-3 hidden)
SELECT price_cents FROM legacy_compat.products_v;
-- ERROR: column "price_cents" does not exist
RESET ROLE;Experiment 5: an outbox, a relay batch, and the consistency lag. The outbox has the same shape as in Mechanics and as orders.PlaceOrder writes it.
CREATE TABLE orders.outbox (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
event_id text NOT NULL UNIQUE DEFAULT gen_random_uuid()::text, aggregate_type text NOT NULL, aggregate_id text NOT NULL,
event_type text NOT NULL, payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(), published_at timestamptz
);
INSERT INTO orders.outbox (aggregate_type, aggregate_id, event_type, payload)
SELECT 'order', 'o-' || g, 'OrderPlaced.v1', jsonb_build_object('order_id', 'o-' || g) FROM generate_series(1, 1000) g;
SELECT pg_sleep(2); -- the relay is "late" by two seconds
-- One relay batch: the same claim (FOR UPDATE SKIP LOCKED) and mark (published_at) that relay.Once runs,
-- folded into one statement because there is no broker in this lab.
WITH batch AS (
SELECT id FROM orders.outbox WHERE published_at IS NULL ORDER BY id LIMIT 500 FOR UPDATE SKIP LOCKED
)
UPDATE orders.outbox o SET published_at = clock_timestamp() FROM batch WHERE o.id = batch.id;
-- UPDATE 500
SELECT count(*) AS unpublished, round(EXTRACT(EPOCH FROM now() - min(created_at))::numeric, 1) AS oldest_s
FROM orders.outbox WHERE published_at IS NULL;
-- unpublished | oldest_s
-- 500 | 2.0 (grows every second until the next batch)
SELECT round(percentile_cont(0.99) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM published_at - created_at))::numeric, 2) AS p99_s
FROM orders.outbox WHERE published_at IS NOT NULL;
-- p99_s ≈ 2.0x: every read model fed by this outbox is at least this staleExperiment 6: run the Go tests (composition, idempotent read model, tracer write).
$ cd docs/snippets/architecture/microservices-data-ownership/go && go test ./...
1 ok academy/microservices-data-ownership/composer (batched call; partial answer when Catalog is down)
2 ok academy/microservices-data-ownership/readmodel (duplicates/older events ignored; real OrderPlaced via FromOutbox projected)
3 ok academy/microservices-data-ownership/tracer (failed tracer write does not fail the user; reconciled)Clean up: docker rm -f own.
Common misconceptions
| Belief | Reality |
|---|---|
| Database per service needs a server per service | Private tables, schema per service and server per service are all valid; schema + role is the usual start |
| A shared database is always an anti-pattern | Tolerable for read-only reference data, deliberate read interfaces and short transitions |
| Splitting data means losing consistency | You lose cross-service ACID; local ACID stays; sagas and outboxes give eventual consistency |
| 2PC solves cross-service writes | It couples availability and is unsupported by many stores; avoid between microservices |
| Copies of data break single source of truth | Copies with an owner, refresh path and staleness are caches; only local writes to copies break it |
| CQRS is always better than API composition | It adds lag and moving parts; compose first, project when queries need filtering or paging |
| Views decouple writers | Join views are read-only; views help readers, not writers |
| Dropping the FK is losing integrity | Integrity moves to code, soft deletes and reconciliation; it becomes visible work |
| Read-your-writes is a database setting | Within one database's replicas, yes; across services it is a design |
| CDC on raw tables is a free event stream | It publishes your private schema; use an outbox table as the contract |
| Data mesh means sharing operational databases | It means domain-owned analytical data products |
| Separate repos and containers mean separate data | Not if they share tables; check grants, not repos |
Cheat sheet
| Topic | What to remember |
|---|---|
| Owner | Single writer + system of record; others use API, events or a published view |
| Isolation ladder | Tables, schema, database, server, engine/region; schema + role is the cheapest real barrier |
| Shared database | Development and runtime coupling; OK for reference data, read interfaces, transitions |
| Ownership scenarios | Single (assign), common (dedicated owner), joint (split, data domain, delegate, consolidate) |
| Reference data | Call, cache, replicate, library, snapshot; write down staleness |
| Queries | API composition first; CQRS read model for filtering/paging; reporting DB for analytics |
| Writes | Saga + outbox + inbox; no 2PC; design pending states |
| Read-your-writes | Return new state; version tokens; route to owner; sticky only within one DB |
| Sovereignty | Few PII owners; ids not PII in events; erasure as an event; region pinning |
| Brownfield order | Contain (view, wrapper), split table, FK to code, sync/tracer write, read new, move, retire |
| Tracer write | One source of truth per phase; secondary write never fails the user; reconcile |
| Schema change | Private schema free; published contracts use expand/contract |
| Lag | Oldest unpublished outbox row, MilliSecondsBehindSource, slot lag, projector lag |
| Tests | Grant tests, view shape tests, contract tests, per-service fixtures |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What two properties make a service the owner of a piece of data? Must-know
Answer
Answer: It is the single writer and the system of record (source of truth); others read via its contracts. See Data ownership.
2 — Name Richardson's three ways to keep a service's data private and which are cheapest. Important
Answer
Answer: Private tables per service, schema per service, database server per service; the first two "have the lowest overhead". See Database per service.
3 — Give two situations in which a shared database is tolerable. Important
Answer
Answer: Read-only static reference data with a clear owner; a deliberately published read interface (database-as-a-service, reporting DB); a short, planned transition. See Shared database.
4 — Two services write customer.status. List the four techniques in order of decoupling. Good to know
Answer
Answer: Table split, data domain, delegate, service consolidation (Hard Parts' joint-ownership techniques). See Ownership scenarios.
5 — When does API composition stop being enough? Must-know
Answer
Answer: When the query filters, sorts or pages across owners, joins large sets in memory, or its latency/availability breaks the SLO. Then use a CQRS read model or reporting store. See Cross-service queries.
6 — Why not 2PC between microservices? Must-know
Answer
Answer: It couples every participant's availability, blocks on coordinator failure, and many stores and brokers do not support it; Richardson: "Distributed transactions are best avoided". Use sagas with an outbox. See Cross-service writes.
7 — A user renames a product and the list still shows the old name. Give two fixes. Important
Answer
Answer: Render from the write response; pass a version token and have the read model wait or fall back to the owner; route reads to the owner briefly. See Consistency promised to clients.
8 — In what order would you apply view, split table, FK to code and tracer write, and why? Good to know
Answer
Answer: Contain readers with a view (or wrapper), split the table so each part has one owner, drop the FK so the data can move, then tracer-write to the new owner and switch reads. Each step is reversible on its own. See Brownfield.
9 — What must be true before you stop writing the old store in a tracer write? Important
Answer
Answer: All consumers read the new source, reconciliation shows no mismatches for an agreed period, and a reverse-sync or rollback plan exists. See Tracer write.
10 — Why is CDC on a raw table a schema-change trap? Important
Answer
Answer: The topic mirrors the private table, so any column change is a breaking event change; publish an outbox table (e.g. Debezium's outbox event router) as the contract. See Schema change.
11 — Which single metric best warns that read models are going stale even when no messages flow? Important
Answer
Answer: Age of the oldest unpublished outbox row (and its CDC equivalent, MilliSecondsBehindSource or slot lag). See Observability.
12 — How does data ownership help with a right-to-erasure request? Important
Answer
Answer: PII lives in few owners; the owner erases and publishes an erasure event every copy must handle and acknowledge. See Data sovereignty.
Glossary
| Term | Meaning |
|---|---|
| Data ownership | One service is the single writer and system of record for some data |
| Single writer | Only one service may change the data |
| System of record / source of truth | The authoritative copy everyone else trusts |
| Database per service | Each service's persistent data is private and reached only via its API/events |
| Private-tables-per-service | Ownership by table inside a shared schema |
| Schema-per-service | One database schema (and role) per service |
| Database-server-per-service | One database instance or cluster per service |
| Shared database / integration database | One database read and written by several services or applications |
| Application database | A database controlled and accessed by a single application (Fowler) |
| Blast radius | The set of services broken by one change |
| Single ownership | One service writes a table |
| Common ownership | Most services write a table; give it a dedicated owner |
| Joint ownership | A few services write the same table |
| Table split | Divide a jointly written table into per-owner tables |
| Data domain | A schema shared deliberately by tightly related services |
| Delegate | One service owns the data; others write through its API |
| Service consolidation | Merge services that must share a transaction |
| Reference data | Small, slowly changing data many services read |
| Data duplication | Deliberate copies with an owner, refresh path and staleness |
| API composition | Answering a query by calling the owners and joining in memory |
| CQRS read model | A query-specific store kept current from owners' events |
| Materialized view | A precomputed query result; in PostgreSQL CREATE MATERIALIZED VIEW, refreshed explicitly |
| Reporting database / data warehouse | A read-only copy designed for reporting or analytics |
| CDC (change data capture) | Streaming committed changes from the database log (e.g. Debezium) |
| Debezium | Open-source log-based CDC platform with connectors for PostgreSQL, MySQL, others |
| Transactional outbox | Storing outgoing events in the same local transaction as the state change |
| Inbox | A table of processed event ids that makes a consumer idempotent |
| Idempotent | Safe to apply more than once with the same result |
| Saga | Multi-service business transaction as local steps with compensations |
| Compensating transaction | A step that semantically undoes an earlier step |
| 2PC | Two-phase commit; blocking atomic commit across participants |
| Eventual consistency | Copies converge after updates stop; no instant agreement |
| Read-your-writes | A client always sees its own earlier writes |
| Consistency lag / replication lag | Time from the owner's commit to visibility in a copy |
| Sticky (Laravel) | Reads after a write in the same request use the write connection |
| PreventStaleDatabaseReads | Laravel middleware: later session requests read from the write connection for a while |
| Database view | A stored query exposed as a table; here a limited read-only face |
security_barrier | PostgreSQL view option: view conditions run before user conditions |
| WITH CHECK OPTION | Rejects writes through a view that the view would not show |
| Database wrapping service | A thin service in front of a schema, replacing direct access |
| Database-as-a-service interface | A dedicated read database published for outside consumers |
| Synchronize data in application | Copy, dual write, switch reads, retire, done by the application |
| Tracer write | Moving the source of truth incrementally, writing to both for a while |
| Dual write | Writing the same change to two stores; safe only as a managed tracer write or via outbox |
| Dual-run | Running old and new side by side and comparing |
| Reconciliation | A job comparing copies by id and repairing the follower |
| Split table | Newman's pattern for a table owned by two contexts |
| Move foreign key to code | Drop the cross-owner FK; check references through the owner's API |
| Referential integrity / orphan | Guarantee that references resolve / a reference that no longer does |
| Soft delete / tombstone | Marking a row deleted instead of removing it |
| Expand/contract | Add new, migrate readers, remove old (ParallelChange) |
| Data sovereignty / data residency | Authority over data and the jurisdiction where it must stay |
| PII | Personally identifiable information |
| Tenant isolation | Separation of one customer's data from another's |
| Data mesh / data product | Domain-owned analytical data, published with contracts and SLOs |
| Data contract / consumer-driven contract | Versioned schema and semantics for shared data / consumer-stated expectations verified by the producer |
| Polyglot persistence | Different owners using different database engines |
postgres_fdw | PostgreSQL foreign-data wrapper for querying another server |
| Logical replication | PostgreSQL replication of row changes by replica identity |
MilliSecondsBehindSource | Debezium metric: delay between change timestamp and processing |
search_path | PostgreSQL schema lookup order; pins a connection to its owner's schema |
| GRANT / REVOKE | SQL privilege statements that enforce ownership |
FOR UPDATE SKIP LOCKED | Row locking that skips locked rows; lets relay replicas share an outbox |
SetMaxOpenConns | Go database/sql pool limit per owner |
Http::pool | Laravel HTTP client concurrent requests |
| Strangler fig | Replacing a system piece by piece behind a routing layer (Strangler Fig) |
| Bounded context / aggregate | DDD model boundary / consistency unit inside it (Bounded Context) |
References
- Chris Richardson, microservices.io: Database per service, Shared database, Saga, CQRS, API Composition, Event sourcing, Transactional outbox, Transaction log tailing
- Martin Fowler, "IntegrationDatabase", 25 May 2004; "ApplicationDatabase", 3 August 2004; "ReportingDatabase", 2 April 2014; Danilo Sato, "ParallelChange", 13 May 2014
- Zhamak Dehghani, "Data Mesh Principles and Logical Architecture", martinfowler.com
- Sam Newman, Monolith to Microservices (O'Reilly, 2019), chapter 4 "Decomposing the Database" (not fetched; O'Reilly returns 403). Pattern summaries via Dan Lebrero's book notes and Ignacio Herrera's handbook pages on decomposing the database, tracer write, database view, shared database, synchronize data in application and split table (secondary)
- Neal Ford, Mark Richards, Pramod Sadalage, Zhamak Dehghani, Software Architecture: The Hard Parts (O'Reilly, 2021), chapter 7 "Service Granularity", free excerpt published by Thoughtworks; chapter 9 ownership terms named but not fetched
- AWS Prescriptive Guidance, Database decomposition: Controlling database access, Database wrapper service pattern, Decoupling table relationships
- Datadog Engineering, "Unwinding a shared database", 17 June 2025
- Debezium documentation: Features, Outbox Event Router, PostgreSQL connector (streaming metrics)
- PostgreSQL documentation: CREATE VIEW, postgres_fdw, Logical replication, pg_replication_slots
- Laravel 13: Database: Getting Started (multiple connections, read/write, sticky), Eloquent, Migrations, HTTP Client, Queues, Query Builder
- Go: Managing connections