Nguyen Le Phong

Foundations of Software ArchitecturePart 8 of 15

Who Owns the Data Once Your Services Split Up?

When services stop sharing a database, you lose JOINs and cross-service transactions.

Say your team split the monolith last quarter. Orders and billing are separate services now, with separate repos and separate deploys. One Thursday the orders team renames orders.status to orders.state. It's their table, so nobody thinks twice. Friday morning, invoices stop going out. Billing had been reading that table directly the whole time.

Splitting code is the easy half of a service split. The hard half is the data: who owns each piece, what you lose when services stop sharing a database, and how you keep the numbers right without the one big transaction you've leaned on your whole career. This is part two of a short series. Part one turned a slow call chain into events. Here we sort out the data, and wherever a pattern has its own deep-dive post, I'll link it so this one can stay a map.

Nguyen Le Phong stands at a glass wall covered in a service diagram, explaining to two teammates which service owns which data and where events cross between them.
The first data conversation after a split is rarely about scale. It's about drawing ownership lines the whole team will respect.

A shared database is a contract nobody signed

When a team breaks up a monolith, the tempting shortcut is to split the code and leave every service pointed at the same database. It feels practical, since nothing has to move. In return you get a distributed monolith: the network hops, deploy pipelines and on-call load of many services, plus the coupling of one.

The coupling is the sneaky part. If billing reads the orders table, then the shape of that table is now part of the orders service's public contract, and nobody wrote that down. The orders team can't rename a column, split a table or change a type without checking every other service's queries first. You wanted independent teams. What you have is a meeting before every migration.

A quick test for a real split

Can the orders team change its schema this afternoon without asking anyone? If the honest answer involves a Slack thread with three other teams, the data is still shared, whatever the deploy diagram says.

Database per service, and the bill that comes with it

The fix has a name: database per service. Chris Richardson's version of the rule is short. Keep each service's data private and reachable only through its API, so other services can't touch the database directly (Database per service).

Private doesn't have to mean a new database server for every service. Richardson lists three ways to do it with a relational database: private tables per service, a schema per service, or a whole database server per service for the high-throughput ones. The first two cost the least to run, and a schema per service makes ownership the clearest. He also suggests giving each service its own database user, so the rule holds even on a busy Friday. In PostgreSQL that looks like this:

CREATE SCHEMA billing;
CREATE ROLE billing_svc LOGIN;
GRANT USAGE ON SCHEMA billing TO billing_svc;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA billing TO billing_svc;
-- No grant on the orders schema, so a "quick join" fails the first time someone runs it.

That buys you the independence the whole move to services was for. Each team changes its own schema, picks its own storage and deploys on its own schedule. The bill shows up right away, in two lines:

  • No more JOINs across services. "Orders with the customer's name" used to be one query. Now the rows live in two services, so you combine them in code by calling each one (Richardson calls this API composition) or you keep a read model built from events.
  • No more transactions across services. You can't wrap "charge the card" and "reserve the stock" in one BEGIN and COMMIT when they live in different databases.

The second line is the expensive one. Most of the rest of this post is about living without the cross-service transaction you used to get for free.

From "true on commit" to "true in a moment"

Inside one database you get strong consistency: once the transaction commits, every reader sees the new value. Across services you usually get eventual consistency instead. Werner Vogels, Amazon's CTO, described it in 2008 as a weak form of consistency where, if no new updates come in, all reads eventually return the last written value. The gap between a write and the moment everyone sees it is the inconsistency window, and with no failures you can estimate its size from things like network delay (Eventually Consistent).

Why accept that? Vogels sums up the CAP theorem this way: at scale, network partitions will happen, so during one you pick between staying consistent and staying available. Relax consistency and the system keeps answering. Insist on it and some requests have to wait or fail. Neither choice is wrong. The useful move is to make it per piece of data, on purpose.

Strong consistencyEventual consistency
When is it true?As soon as you commitA moment later, once the change reaches everyone
ScopeOne databaseAcross services or regions
You pay withCoupling, lock contention, harder scalingShort windows where services disagree, which you design for
Good fitA balance inside one ledger, one aggregateWorkflows across services, read models, analytics
Ask the business, not the database

The question is "would it hurt if this were true a second later?" For search indexes, notifications, recommendations and dashboards, the answer is almost always no. For "has this card already been charged?", draw the boundary so the money lives inside one service's local transaction, and let everything around it catch up. Eventual Consistency in the Real World covers what users actually see during that second.

The dual-write bug

This is the bug almost every team ships first. A service needs to save a row and tell the world about it, so it does both back to back:

// Two systems, no shared transaction
await db.orders.insert(order)                  // 1) committed
await broker.publish("OrderPlaced", order)   // 2) crash here and nobody hears about it

If the process dies between line 1 and line 2, the order exists and payment never hears about it. Swapping the lines doesn't help: publish first, crash before the insert, and now you've announced an order that was never saved.

The standard fix is the transactional outbox. You write the event into an outbox table in the same transaction as the order, and a separate relay publishes rows from that table to the broker. Richardson states the guarantee plainly: messages get sent if and only if the database transaction commits (Transactional outbox).

// The order and its event commit together, or neither does
await db.transaction(async (tx) => {
  await tx.orders.insert(order)
  await tx.outbox.insert({ type: "OrderPlaced", payload: order })
})
// A relay polls the outbox (or tails the database log) and publishes, with retries.

There's a catch you have to plan for. The relay can crash after publishing and before marking the row as sent, so the same message can go out twice. Consumers have to be idempotent, for example by tracking the IDs of messages they've already handled. Relays, ordering and cleanup get the full treatment in The Outbox Pattern.

Nguyen Le Phong sits next to a teammate at a workstation and points at a simple flow on screen: database, outbox table, relay, broker.
Once the outbox is in, the team can point at one local commit and one relay. Publishing no longer depends on the process surviving at the right moment.

Sagas: undo, step by step

Now the hard case. One business action spans three services: charge the card, reserve the stock, confirm the order. Step three can fail after steps one and two have already committed, and no ROLLBACK reaches across three databases.

The answer is older than microservices. In 1987 Hector Garcia-Molina and Kenneth Salem proposed the saga for long-running transactions inside a single database: split the work into a sequence of smaller transactions, and give each one a compensating transaction that undoes it from a business point of view, without necessarily putting the database back exactly as it was (Sagas). The microservices world borrowed the idea almost unchanged. Richardson describes a saga as a sequence of local transactions, one per service, with compensations written by hand when a step breaks a business rule (Saga).

A saga runs three steps in order: charge the card, reserve stock, confirm the order. Confirming fails, so the saga releases the stock and refunds the card, each as its own local transaction. NO ROLLBACK ACROSS SERVICES · UNDO STEP BY STEP 1 · Charge card Payment service 2 · Reserve stock Inventory service 3 · Confirm ✗ out of stock: fails undo: release stock undo: refund card each undo is a normal local transaction
No database can roll back three services at once. When step three fails, the saga walks backward through what already happened: release the stock, then refund the card. Each undo is an ordinary local transaction.

Notice what a compensation really is. A refund isn't "the charge never happened." The customer may already have seen the charge on their banking app, and your support team may get a ticket about it. Sagas make you model failure as something that happens in the real world, which is less comfortable than a rollback and a lot closer to how the business already thinks.

The part teams miss most often is isolation. Richardson lists it among the drawbacks: while a saga is halfway through, other requests can read its in-between state. Between "card charged" and "order confirmed", a second request might see an order that looks paid. The usual countermeasures are design choices, such as a PENDING status that tells everyone else the order isn't final yet. Plan them up front, because a bug from this gap is very hard to reproduce later.

You can run a saga two ways. With choreography, each service reacts to the previous service's event and nobody is in charge. With orchestration, one coordinator tells each service what to do next and handles the replies. For flows that touch money, I'd start with an orchestrator, because you can read the whole flow in one place and see exactly where a stuck order stopped. The Saga Pattern goes deeper into both styles.

Nguyen Le Phong leads an evening planning session where a small group of engineers maps each step of a multi-service workflow next to the step that undoes it.
Write the undo steps before the happy path ships, while everyone still remembers which service has to reverse what.

Read models: putting scattered data back together

Database per service took away your JOINs. So how do you render an admin screen that needs data from six services? Calling all six on every page load gets slow and fragile fast. The other option is a read model: a separate copy of the data shaped exactly for that screen, kept current by listening to events from the services that own it.

That's the read half of CQRS, Command Query Responsibility Segregation: the model you write through and the model you read from don't have to be the same. Martin Fowler first heard the pattern described by Greg Young, and much of his write-up is caution (CQRS). He says it adds risky complexity for most systems, that you should use it only on specific parts of a system, and that if your domain doesn't suit CQRS but has a few demanding queries, you can still offload those to a separate reporting database.

  • Write side: small, strict, enforces the business rules.
  • Read side: wide, fast, usually a little behind, shaped for queries.

Read models are worth it when reads and writes look very different: a product catalog read millions of times a day and edited a few times an hour, or a dashboard that joins five services. When one table serves both sides fine, which is most of the time, skip it. The CQRS post has the longer version.

Event sourcing: keep the history, compute the state

Event sourcing flips storage around. Fowler's one-line definition: capture every change to the application state as a sequence of events (Event Sourcing). So you don't store "balance is 120". You store AccountOpened, MoneyDeposited, MoneyWithdrawn, and work out the balance by replaying them.

Fowler names what you get: you can throw the current state away and rebuild it from the log, ask what the state was at any point in time, and fix a bad past event by reversing it and replaying what came after. He's just as clear about what it costs. Replays can resend emails or payments to external systems unless you put switchable gateways in front of them. Code changes over the years have to keep handling old events. Replaying from scratch gets slow, so you add snapshots. Add one more cost he doesn't cover: deleting a person's data from an append-only log takes real planning when privacy law asks you to.

Where it pays off

Event sourcing earns its cost in domains where "how did we get here" matters as much as "where are we": ledgers, approval flows, anything an auditor will read. For most other services, an outbox plus a read model gets you most of the benefit for a lot less long-term work. Event Sourcing for Beginners walks through a small one end to end.

Pick by the problem you actually have

The problem in front of youWhat usually fits
Save a row and tell other servicesTransactional outbox, plus idempotent consumers
One business action across servicesA saga with compensations, orchestrated when money is involved
A screen that needs data from many servicesAPI composition for a few calls, a read model fed by events for many
Reads and writes scale very differentlyCQRS on that part of the system, with separate write and read stores
History and audit are part of the productEvent sourcing, with its versioning and snapshot work budgeted in
Everything fits in one service and one databaseA plain ACID transaction. Keep it that way.

What changes as the company grows

  • Small team, one product: one database, real transactions, no sagas. Your biggest data advantage right now is that everything can still be correct in a single COMMIT. Don't trade that for a nicer architecture diagram. If you want to get ready for a split, give each module its own schema and stop cross-module queries in code review.
  • Growing company, first few services: give each new service its own schema and database user from day one. Add the outbox the day you publish your first event. Use a saga only for the one or two flows that really cross services and money. Add a read model when one screen starts calling half the system.
  • Large organization: eventual consistency is the default and teams know how to work with it. The work moves to shared tooling: event schemas with versioning rules, dashboards for stuck sagas, and read models that have a named owning team. Event sourcing shows up only in the few domains that need the history.

Try this week

  • List every query in your services that reads another service's tables. Each one is a hidden contract, so pick the riskiest and move it behind an API call or an event.
  • Create a separate database user per service, even if they share one server, and remove grants on schemas they don't own.
  • Search for "save, then publish" code paths. Move the one where a lost event costs the most into an outbox.
  • For each cross-service flow, write the compensation for every step next to the step itself, and decide what other requests should see while the flow is halfway done.
  • Before adding a read model, try a plain API composition and measure it. Build the read model only when the numbers ask for it.

Services can now talk through events and keep their data straight. One thing is still missing: staying up when the network drops a message, a service stalls or a dependency has a bad day. Timeouts, retries, circuit breakers and idempotency are the last part of this series: paying the distributed-systems tax.

What did you think?

Frequently asked questions

What does database per service mean?
Each service keeps its data private, and other services get it only through that service's API or events, never by querying its tables. Chris Richardson's pattern lists three ways to do it with a relational database: private tables per service, a schema per service, or a database server per service.
Does every microservice need its own database server?
No. A schema per service on a shared server is often enough, and it's cheaper to run. What matters is that no other service can read or write those tables. A separate database user per service, with grants only on its own schema, enforces that.
What is a distributed monolith?
A system split into services that still share a database or change together. You pay for many services (network calls, separate deploys, more on-call work) and still can't change one service's data without coordinating with the others.
How do you keep data consistent across services without distributed transactions?
Use a transactional outbox so saving data and publishing an event happen in one local commit, make consumers idempotent, and use a saga with compensating steps for business actions that span services. Accept eventual consistency where a short delay doesn't hurt, and keep money-critical checks inside one service's local transaction.
When should I use CQRS or event sourcing?
Use a read model (the read half of CQRS) when a screen needs data from many services or reads far outnumber writes. Martin Fowler advises applying CQRS only to specific parts of a system. Use event sourcing when the history itself matters, like ledgers and audit trails, and budget for event versioning, snapshots and data deletion.