Chapter 24 of 27 · Part 10: Refactoring to microservices

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

Where we are

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.

This chapter

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?

Problem

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?

Solution · Data follows the logic that changes it

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.

Aggregate exposing monolith, then extraction Step 1: the monolith exposes the aggregate Delivery service needs addresses Restaurant API on the monolith Monolith DB restaurant tables Step 2: the API shape reveals the next service boundary Delivery service calls Restaurant Restaurant service owns restaurant data Monolith now calls it too The monolith still enforces valid state changes. Expose operations, not a raw table. Use a view or CDC only if the monolith cannot be changed.

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.

Change data ownership: delivery data moves out Before After Monolith Delivery data Other tables Delivery svc source of truth Delivery DB own schema Monolith calls API Read-only view last resort If the service runs the logic that changes the data, the data belongs to it. Expect broken foreign keys and transaction boundaries (sections below).

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.

Cost

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.

Problem

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.

Logical split versus physical split Logical only Logical and physical Schema A Schema B Schema A Schema B Logical: independent change, information hiding. Views need the same engine. Physical: fewer shared failures, less resource contention, more cost.
Three ways to move one service out Code first leaves a shared database, data first moves the tables early, both at once is a big step. Code first most common Monolith Kitchen Shared database Data first tests the hard part early Monolith + kitchen code Main DB Kitchen DB Both at once avoid: big step Monolith Kitchen Main DB Kitchen DB Whatever you pick, sketch how code and data will both move before you start. A half-finished split that leaves a shared database stores up trouble.
OrderBenefitRiskPick when
Schema firstFinds broken joins, integrity and transaction problems early; easy to revertLittle short-term gain; impossible if the monolith is a black box you cannot changeYou worry about performance or consistency and can change the monolith
Code firstA deployable service sooner; shows which data the service needsTeams stop early and keep a shared database; join pain is found lateThe default for most teams, if you commit to finishing the data split
Both at onceOne stepToo big; you learn the impact lateAvoid
Solution · Prepare the split inside the monolith

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.

PatternWhat you doWhy
Repository per bounded contextSplit data-access code by context, such as one Hibernate mapping per contextShows which code touches which tables; SchemaSpy shows the foreign keys
Database per bounded contextSeparate schemas inside one deployable (a modular monolith)Hedges your bets; advised even for new systems
Monolith as data access layerThe service calls an API on the monolith for dataPostpones the split; suits a mostly stateless service
Multischema storageNew data in a new schema; old data read from the monolithStops the old schema growing; move tables later
A practical rule. If you can change the monolith and worry about performance or consistency, split the schema first. Otherwise split the code, and use it to learn who owns the data. Either way, track schema changes as versioned delta scripts, for example with Flyway.
Cost

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.

Problem

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.

Solution · Synchronize data in the application

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.

Moving data: write to both, then switch reads Bulk copy and catch up, then write to both while reading old, then read from new. 1 Bulk copy then catch up on changes Application Old DB New DB 2 Write to both still read from old Application Old DB New DB 3 Read from new keep writing to both Application Old DB New DB Teal marks the source of truth. Old DB is retired only after the new one has bedded in. This works best when only one writer (monolith or service) is active at a time.

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.

Solution · Tracer write

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.

Tracer write moves data in slices Stage 1 Assignments (new) Pickup times Delivery history Stage 2 Assignments (new) Pickup times (new) Delivery history Stage 3 Assignments (new) Pickup times (new) History (new) Two sources of truth are tolerated for a while. Consumers switch as data 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:

All three are eventually consistent. If the sync is a nightly batch, the copies can differ for up to a day.

Reconcile. With two sources of truth you need a check that the sync works, or you find out too late. Running the new source for a while with no consumers at all, as Square did, is a sensible first stage.

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.

Square: moving fulfilment data out of the Order concept Clients: restaurant and driver code Existing system Order data Background worker feature-flagged Fulfillments svc new source of truth each change goes to both The worker copied old data through the service API, not the DB, and could be switched off.
Cost

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.

Problem

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.

Solution · Change data capture

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.

Change data capture feeds a new service The monolith database feeds a change capture step, an event stream and a new service. Monolith DB Change capture Event stream New service Two ways to capture Query with a watermark simple, but may squash updates Read the database log sees every change, leaks table shape

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.

Cost

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.

Problem

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.

Solution · Split table

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 a table that serves two contexts Case 1: columns divide cleanly ORDERS items, total, courier Order items, total Delivery order id, courier, pickup Order svc owns items Delivery owns courier Case 2: two contexts change one column Accounting failed charges Consumer service owns status NOT_VERIFIED, VERIFIED, SUSPENDED Keep a state machine in one service: Accounting calls Consumer to suspend. Split the table inside the old schema first. You lose the single transaction (see the next section).

Splitting the table exposes the second problem: references between tables that now belong to different services.

Problem

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.

Solution · Move the foreign key to code

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:

A join becomes a service call In one schema a foreign key and one query join Ledger and Restaurants. After the split Accounting asks Restaurant Service for the details. Before: one schema, one query Ledger Restaurants FK The database joins and keeps integrity After: two services Accounting Restaurant ids in bulk Ledger DB Restaurant DB What if a restaurant row is deleted? Check before delete race-prone, adds coupling Handle it gracefully show "not listed", 410 Gone Do not delete soft delete or graveyard table Do not split an aggregate: order lines belong with their order, so move them together.

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.

Check the aggregate first. An order and its order lines are one aggregate (chapter 3). Never split them across services; move them together. A bigger bite can avoid breaking a key at all.
Cost

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.

Problem

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.

Four ways to share static reference data Duplicate copy per service, local schema fine if data stays inside a service risk: services disagree Dedicated schema one versioned shared schema joins possible on same engine schema change hurts everyone Library enum or file bundled in code small, rarely changing data versions may differ in production Service one source, cached by clients events refresh caches cost of one more service Example: about 249 country codes. The last new country was South Sudan in 2011.
OptionBest whenWatch out
DuplicateLarge data used inside one service, such as postal code filesCopies differ; matters if values travel in messages
Dedicated schemaOne source, with joins across schemasA shared database again: version it as an interface
LibrarySmall, stable data; consistency not criticalVersions differ in production; one tech stack
ServiceEvery consumer must agree; data has updates or eventsOverkill if new services are slow to create; can be a function
Solution · Choose by how much consistency the data needs

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.

Problem

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.

Solution · Model the process as a saga

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.

Cost

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:

From problem to pattern Many consumers read my tables View or wrapping service Clients need SQL or reports Read-only exposed database New service needs monolith data Aggregate exposing monolith Service logic changes the data Change data ownership Need fallback between old and new Sync in application Want to move data in slices Tracer write Transaction across split data Saga, or keep it together

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:

StepActionPattern
1Split data-access code into catalog, finance, warehouse and customer repositories; chart the foreign keysRepository per bounded context
2Item mixes names and stock: split it into Catalog item and Stock item inside the monolithSplit table
3Customer status is also set by Finance: Customer owns it, and Finance will call itSplit table
4Extract Catalog; the Ledger needs album titles: bulk lookup, no album deletion, tolerate missing albumsMove foreign key to code
5Move Catalog data with dual writes, then switch reads, then retire the old copyTracer write
6Give each service its own schema; country codes become a shared libraryStatic data library
7Order placement across Warehouse, Payment and Loyalty becomes a saga, with refunds as compensationSaga

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.

Cost

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

PatternProblem it solvesWhat it costs
Aggregate exposing monolithA new service needs data the monolith still ownsThe monolith must change to offer an API
Change data ownershipA service's logic changes data that lives in the monolithBroken 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 moveWork with no visible gain; the split is only postponed
Synchronize data in applicationMoving the source of truth with no downtime and a way backHard with two writers; needs reconciliation
Tracer writeA big switchover of all data at onceTwo sources of truth for a while
Change data captureChanges made outside the application code are missedExposes table shape; query-based capture misses updates and deletes
Split tableOne table, or one column, serves two contextsThe single transaction across the parts is lost
Move foreign key to codeA join and a constraint cross a service boundaryMore latency; dangling references to handle
Static data: duplicate, schema, library or serviceReference data that every service needsDrift, lock-step releases, or one more service
SagaA transaction that now spans two databasesNo atomicity or isolation; compensations to design
Read-only exposed databaseReporting that used to query everythingA reporting interface to keep compatible

Recap

Quick check

The Kitchen team splits the code first, and Kitchen Service still reads the monolith's schema. What is the main risk?
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.

Restaurant Service deletes a restaurant that closed. The next monthly payout run in Accounting crashes on a ledger row that refers to it. What went wrong, and what should change?
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.

FTGO writes delivery changes to both the old and the new database, yet a nightly check finds rows that differ. Support staff often fix pickup times with SQL. Which pattern helps?
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.

Still open

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.

Next: 25 Teams and evolutionary architecture →