Decomposing the database
FTGO's code has started to leave the monolith, but its data still sits in one shared schema full of joins and foreign keys. This chapter shows how to give each piece of data one owner and move it out without downtime, broken references or lost changes.
key idea / coordinator service / good path in progress / watch out problem / failure neutral
In chapter 23 we strangled FTGO's monolith: new features as services, Delivery extracted as a vertical slice, traffic switched through a proxy. That left one problem open: the extracted code still reads and writes the monolith's tangled schema.
How do you take a service's data out of a shared database while both sides keep running? By the end you can assign each table an owner, choose schema or code first, move data with a fallback, catch every change, and handle split tables, broken foreign keys, reference data and lost transactions.
The code moved, the data stayed: who owns it?
Delivery Service runs in its own process, but still writes courier and pickup columns in the monolith's ORDERS table and reads addresses from its RESTAURANT table. A routine monolith release renames an address column, and Delivery Service fails in the middle of the dinner peak. Nobody knew it read that table.
A shared database couples everyone who touches it (chapter 8). To end that, every piece of data needs exactly one owner. The question to ask is simple: which code changes this data?
If the service's logic changes the data, move the data to the service (change data ownership). If the data stays with the monolith for now, the service asks the monolith through an API instead of reading its tables (aggregate exposing monolith).
Restaurant addresses are changed by the monolith's restaurant code, so they stay there for now. The monolith gets a small Restaurant API, and Delivery Service calls it. That is little more work than reading the tables, and the monolith still enforces valid changes. The API's shape often shows the next service boundary.
Courier and pickup columns are different: only delivery logic changes them, and it now lives in Delivery Service. So the data moves too, and the monolith calls Delivery Service when its old screens need it. A read-only view is a last resort.
If the monolith cannot be changed at all, fall back on the coping patterns from chapter 8: a database view, a wrapping service, or a read-only database for reporting.
The monolith must change to expose an API, and moving data breaks foreign keys and transactions that cross the boundary. First, though, the team must decide whether code or data goes first.
Split the schema first, or the code?
An extraction is finished only when the code runs in its own service and its data lives in its own schema. Delivery did the code first. The Kitchen team now has to choose for Kitchen Service.
Half of the Kitchen team wants the code out first: a deployable Kitchen Service in weeks. The other half points at Delivery Service, extracted that way and still on the shared database months later.
Two decisions hide in "split the database". A logical split gives each service its own schema, possibly on one server; it gives most of the benefit. A physical split puts schemas on different servers, for more isolation at more cost. Then there is the order of work.
| Order | Benefit | Risk | Pick when |
|---|---|---|---|
| Schema first | Finds broken joins, integrity and transaction problems early; easy to revert | Little short-term gain; impossible if the monolith is a black box you cannot change | You worry about performance or consistency and can change the monolith |
| Code first | A deployable service sooner; shows which data the service needs | Teams stop early and keep a shared database; join pain is found late | The default for most teams, if you commit to finishing the data split |
| Both at once | One step | Too big; you learn the impact late | Avoid |
Whichever order you choose, first make the data boundaries visible and enforceable while everything is still in one process. Then the split itself becomes a small, reversible step.
| Pattern | What you do | Why |
|---|---|---|
| Repository per bounded context | Split data-access code by context, such as one Hibernate mapping per context | Shows which code touches which tables; SchemaSpy shows the foreign keys |
| Database per bounded context | Separate schemas inside one deployable (a modular monolith) | Hedges your bets; advised even for new systems |
| Monolith as data access layer | The service calls an API on the monolith for data | Postpones the split; suits a mostly stateless service |
| Multischema storage | New data in a new schema; old data read from the monolith | Stops the old schema growing; move tables later |
Preparation is work that customers never see. And sooner or later the rows themselves must move to a new database while FTGO keeps taking orders.
Move the data without a big switchover
With the boundaries clear, the delivery rows have to change home.
Delivery's data must move from ORDERS to the Delivery database. FTGO cannot go offline for a weekend migration, and if the new database misbehaves, the team needs a way back that loses no courier assignment.
Move the source of truth in stages, each one reversible. Copy the data in bulk and catch up on changes. Then write to both databases while still reading the old one. Then read from the new one while still writing to both. Retire the old copy only when the new one has bedded in.
You can step back at any stage. Before each step, run a reconciliation, even a simple SQL comparison. A Danish medical-records system that could never go offline moved from MySQL to Riak this way. It is easy with one writer at a time, and hard when monolith and service both write, as during a canary release.
A big switchover of all delivery data at once is still risky. The data can also move in slices.
Move the source of truth one slice at a time. The old system keeps its own copy but also writes each new slice to the new service. Consumers switch as their slice arrives. When the last consumer has moved, stop synchronizing and retire the old copy.
While two sources of truth exist, there are three ways to keep them consistent:
- Write to one and sync to the other: simple; preferred.
- Send every write to both: the client can fail between the two writes.
- Accept writes at either side, sync both ways: avoid; very hard (see chapter 23).
All three are eventually consistent. If the sync is a nightly batch, the copies can differ for up to a day.
Square's case is close to FTGO's. Its Order served customers, restaurants and drivers, and Square moved the restaurant and driver data into a new Fulfillments service. Callers wrote to both sides with two API calls; not atomic, but the gap was tiny. A feature-flagged worker copied old data through the service's API. Switching consumers became a non-event.
For a while there are two copies that can drift, and a reconciliation job to run. Worse, synchronizing in application code only sees changes that pass through that code.
Catch every change: change data capture
The reconciliation job soon finds rows that differ.
ORDERS is not changed only by the monolith's code. A stored procedure reassigns couriers, support staff fix pickup times with hand-written SQL, and a side application updates delivery status. None of this passes through the code that writes to both databases, so the Delivery database silently drifts.
Capture changes from the database itself rather than from the application code, turn them into an event stream, and let the new service consume it. Every change is seen, whoever made it.
Query-based capture polls for rows changed since a watermark, such as a last-updated timestamp. It works on any database, but it can miss intermediate updates between two polls, and it misses deletes. Log-based capture reads the database's transaction log (the log tailing from chapter 6) and sees every change.
Both kinds of capture expose the monolith's internal table shape to the new service. Where you can, translate raw row changes into events with business meaning, such as CourierAssigned. And with the data now flowing to the right place, the tables themselves must still be cut apart.
One table, two owners: splitting tables and foreign keys
Once data lives in different schemas, three things change: a table may have to be cut, a foreign key stops working, and a join turns into slower code. These patterns come from relational schemas, but they guide NoSQL moves as well.
ORDERS holds items and totals, which belong to Order Service, next to courier columns, which belong to Delivery. CONSUMER has a status column that consumer management sets, but Accounting also sets it to SUSPENDED when a charge fails. Neither table can move to one service.
Cut the table along the bounded contexts by column ownership, first inside the old schema. If two contexts change one column, give it to the service that owns that concept, and let the other one ask it to make the change.
Splitting the table exposes the second problem: references between tables that now belong to different services.
Accounting's ledger rows refer to restaurants by restaurant_id with a foreign key, and the monthly payout report joins the two tables. Once restaurant data moves to Restaurant Service, the database can neither run the join nor stop the deletion of a restaurant the ledger still refers to.
Keep the id, drop the constraint, and do the join in the calling service: query its own rows, then ask the owning service for the details in one bulk call, and merge the results.
One SELECT becomes a query, a call and a merge, so latency rises. Bulk lookups and caching help; measure with distributed tracing (chapter 17) before you worry. A monthly report tolerates the delay; a hot path may not. Integrity is the harder loss:
Checking with Accounting before every delete is racy and adds a dependency in the wrong direction. The other two combine well: Restaurant Service never really deletes (soft delete or graveyard table), and Accounting copes with a missing restaurant anyway. A 410 Gone says it once existed, which a 404 does not.
Joins become slower code, references can dangle, and one UPDATE becomes a call to another service. Two things still cross every boundary: lookup tables everyone shares, and transactions over tables now in different databases.
Shared reference data and lost transactions
Most tables have one natural owner. Reference data does not.
Restaurant, Order, Consumer and Accounting all read the monolith's COUNTRY and CUISINE tables. Splitting the schema seems to force either a shared database again or four copies that slowly disagree.
Static reference data, such as country codes or cuisine types, is small and changes rarely: there are about 249 country codes, and the last new country was South Sudan in 2011. There are four ways to share it.
| Option | Best when | Watch out |
|---|---|---|
| Duplicate | Large data used inside one service, such as postal code files | Copies differ; matters if values travel in messages |
| Dedicated schema | One source, with joins across schemas | A shared database again: version it as an interface |
| Library | Small, stable data; consistency not critical | Versions differ in production; one tech stack |
| Service | Every consumer must agree; data has updates or events | Overkill if new services are slow to create; can be a function |
Without strict consistency, use a shared library for small, simple data and local copies for larger data. When every service must see the same values, use a dedicated service. Fall back to a dedicated schema only when a service is hard to justify. Some duplication beats extra coupling.
For FTGO, country codes become a small library. Cuisine types are edited by restaurants through Restaurant Service, so that service owns them and publishes changes.
The last loss is atomicity.
When a payment failed, the monolith suspended the consumer and cancelled the order in one transaction. Now CONSUMER and ORDERS live in different databases, and a crash between the two updates leaves a suspended consumer with a live order.
Avoid distributed transactions such as two-phase commit: one failed node stalls the commit, and the more nodes take part, the more often that happens. Model the business process as a saga of local transactions with compensations (chapter 9), or keep data that must change atomically in one service.
Splitting also breaks reporting that used to be one SQL query over everything. A service can expose a small, read-only subset of its data in a database built for reports, kept compatible like any API. Feeding a cross-service warehouse is covered in chapter 8.
Sagas give up atomicity and isolation, so the business must accept eventual consistency and design compensations. Library copies can differ between versions, and every new service adds operational work.
Putting it together: from problem to pattern
This chapter offers many patterns. Start from your problem, not from a favorite pattern:
The same sequence works outside food delivery. In a side example, MusicCorp, an online music shop, keeps Item, Albums, Ledger, Customer and country codes in one schema. Its split:
| Step | Action | Pattern |
|---|---|---|
| 1 | Split data-access code into catalog, finance, warehouse and customer repositories; chart the foreign keys | Repository per bounded context |
| 2 | Item mixes names and stock: split it into Catalog item and Stock item inside the monolith | Split table |
| 3 | Customer status is also set by Finance: Customer owns it, and Finance will call it | Split table |
| 4 | Extract Catalog; the Ledger needs album titles: bulk lookup, no album deletion, tolerate missing albums | Move foreign key to code |
| 5 | Move Catalog data with dual writes, then switch reads, then retire the old copy | Tracer write |
| 6 | Give each service its own schema; country codes become a shared library | Static data library |
| 7 | Order placement across Warehouse, Payment and Loyalty becomes a saga, with refunds as compensation | Saga |
Each step shipped on its own. In the end Warehouse, Catalog, Finance and Customer each own a schema, use calls instead of joins, and accept eventual consistency. FTGO follows the same path for Kitchen, Consumer and Accounting.
Every boundary drawn in the data is also a boundary between the people who own each side. If the teams are not shaped like the services, every change still needs a meeting across them.
Patterns in this chapter
| Pattern | Problem it solves | What it costs |
|---|---|---|
| Aggregate exposing monolith | A new service needs data the monolith still owns | The monolith must change to offer an API |
| Change data ownership | A service's logic changes data that lives in the monolith | Broken foreign keys and transaction boundaries |
| Preparing patterns (repository or database per context, monolith as data layer) | Unclear data boundaries, or a service needed before its data can move | Work with no visible gain; the split is only postponed |
| Synchronize data in application | Moving the source of truth with no downtime and a way back | Hard with two writers; needs reconciliation |
| Tracer write | A big switchover of all data at once | Two sources of truth for a while |
| Change data capture | Changes made outside the application code are missed | Exposes table shape; query-based capture misses updates and deletes |
| Split table | One table, or one column, serves two contexts | The single transaction across the parts is lost |
| Move foreign key to code | A join and a constraint cross a service boundary | More latency; dangling references to handle |
| Static data: duplicate, schema, library or service | Reference data that every service needs | Drift, lock-step releases, or one more service |
| Saga | A transaction that now spans two databases | No atomicity or isolation; compensations to design |
| Read-only exposed database | Reporting that used to query everything | A reporting interface to keep compatible |
Recap
- Data follows the logic that changes it: move it with the service, or expose it from the monolith through an API instead of letting services read its tables.
- Splitting the schema first finds problems early, splitting the code first pays off sooner but risks stopping with a shared database, and doing both at once is too big a step.
- Synchronize data in the application or use tracer writes to move the source of truth in reversible steps, and always reconcile the two copies.
- Use change data capture when stored procedures, scripts or other applications change the data behind the application's back.
- Split tables by ownership, turn foreign keys into lookups in code, never split an aggregate, and handle deleted rows gracefully instead of checking before every delete.
- Share reference data by a library, a copy, a schema or a service depending on how consistent it must be, and replace lost transactions with sagas.
Quick check
Show answer
The team stops there and the shared database stays for the long term, with join and transaction problems discovered late. Plan the data split from the start and commit to finishing it.
Show answer
Moving the foreign key to code removed the database's integrity check, and nothing replaced it. Do not delete restaurants: use a soft delete or a graveyard table. And make Accounting handle a missing restaurant gracefully, for example by treating a 410 Gone as "restaurant no longer listed" rather than crashing.
Show answer
Change data capture. The hand-written SQL never passes through the application code that writes to both databases. Capturing changes from the database log sees every change, whoever made it; translate them into business events so the new service does not depend on the old table shape.
FTGO's services now own their code and their data. But each boundary is also a line between teams, and the way FTGO organizes its people will shape, or undo, the architecture.