Chapter 08 of 27 · Part 5: Data management

Database per service and the shared database

FTGO's services are deployed separately, but they still read and write one shared database, so a change to one table can break a service nobody thought of. This chapter shows how to give each service its own data, and how to cope safely while you get there.

key idea / coordinator service / good path in progress / watch out problem / failure neutral

Where we are

In chapter 7 we decided what FTGO's events carry and how to change them without breaking consumers. Order, Kitchen and Accounting now talk through well-shaped events. That left one problem open: underneath, the services still share the monolith's single database, and that database couples them more tightly than any event.

This chapter

Why must each service own its data, and how do you get there without a big-bang migration? By the end you can explain what a shared database costs, split data in stages, and use views, wrapping services, reporting databases and data warehouses to serve other readers without giving away your tables.

One database, many owners: why sharing hurts

Problem

Order Service, Kitchen Service and Accounting all read and write the same ORDERS table. The Kitchen team renames a status column to fit its new ticket flow and deploys at 11:00. At noon, Accounting's settlement query starts failing, and a refund job nobody remembered, owned by a fourth team, writes orders back in a state Order Service does not allow. Nobody can say who owns an order.

Sharing one database between services is the most common form of implementation coupling. The core problem is that the owner no longer decides what is shared and what is hidden. Every table and column is visible to everyone, so nobody knows which parts are safe to change.

Three services writing to one orders table Order Service changes order Kitchen Service changes order Accounting changes order Shared ORDERS table one state machine, three rule sets Who owns the rules? If behavior differs between services, the data breaks.
ProblemWhat it means for FTGO
Hidden consumersThe Order team knows others read ORDERS, but not which tables or columns they use.
Unclear controlThe rules for an order's state machine live in three services, and every rule change must be repeated in each one.
Schema as public contractEven an old report nobody maintains freezes the table design.
A side example from a bank. A credit-derivatives platform needed faster writes. More than 20 outside applications used one shared database login, so nobody knew who read or wrote what. The team first tracked down every writer, then built a schema of views that looked like the old one for the readers. The lesson: give each client its own credentials from the start, so access is visible and can be revoked. A secret store makes that practical.
Solution · Database per service

Each service owns its data. Other services never touch its tables; they go through its API or listen to its events. The owner can then change its schema freely, as long as the API and events stay compatible.

"Database" here means a logically isolated schema. One database engine can host many of them. Sharing is still acceptable in two narrow cases:

CaseWhy it is safe enough
Read-only static reference dataCountry codes, postal-code lookups: very stable, and changed as an admin task.
A database exposed on purpose as an endpointDesigned and managed for many readers, like the reporting database later in this chapter.
Cost

Private databases take away cross-service joins, foreign keys and transactions; chapter 9 deals with the last of these. And FTGO cannot get there in one deployment: the monolith's tables are tied together by foreign keys and dozens of queries.

Get there in stages: split the data along the service lines

A service boundary is only real if it owns its data, but you cannot cut a live schema in one move.

Problem

The FTGO team wants to extract Kitchen Service. Nobody knows exactly which tables the kitchen code uses. Its queries join TICKETS with ORDERS and RESTAURANTS, and a foreign key ties tickets to orders. Pulling the tables out in one go would break the monolith at lunchtime.

Solution · Split data access, then schemas, then services

First give each bounded context its own data-access code, then its own schema inside the same application, and only then move it into its own service with its own database.

Splitting the data along the same lines First split data access code, then the schemas, then the services, each with its own data. 1 Repositories one app, one schema Order Kitchen Payment One shared schema 2 Schemas one app, three schemas Order DB Kitchen DB Payment DB 3 Services three services, own data Order DB Kitchen DB Payment DB Stage 2 is a hedge: a modular monolith with separate schemas can stay a monolith. Logical split can share one database engine. A physical split adds robustness but costs more.

Splitting a large live schema has its own patterns: which data to move first, how to keep both sides in sync, how to split tables and keys. Chapter 24 covers them when FTGO refactors its production monolith.

Cost

The split takes months. Meanwhile, new services still need data that lives in the monolith's tables, and old reports and tools still read those tables directly. FTGO needs ways to limit the damage of sharing while it lasts.

Show less of the schema: database views

While the split is in progress, the goal is to stop things getting worse: limit what others can see, and make it clear what is yours. Four coping patterns do that. They are stepping stones, not the destination.

Four ways to live with a shared database A view, a wrapper service, a read-only copy database and an API on the monolith. 1 View New service Database view Monolith schema 2 Wrapper Other apps Wrapper service Tangled schema 3 Read-only DB Reporting client Read-only copy Internal DB 4 Monolith API New service Monolith API Monolith DB All four are stepping stones. They limit or hide the shared schema; they do not remove it. Arrows show calls or reads. In option 3 the copy is filled from the internal DB.

The lightest one is a view.

Problem

The new Delivery Service needs each consumer's delivery address. The address lives in the monolith's CONSUMERS table, next to payment card details and loyalty data. If Delivery reads the table directly, it can see every column, and the Consumer team can never rename one without asking.

Solution · Database view

Publish a view: a limited, read-only projection of the schema. The reader sees only the columns it needs. The owner can change the tables underneath as long as the view keeps working.

A view projects only part of a table CONSUMERS table name, address, card Database view consumer ID + address Delivery Service reads the view only Other columns and tables stay invisible. The reader sees a projection, not your schema.
AspectDetail
LimitsUsually read-only. The view and its source often must sit on the same engine. Support varies by database.
Materialized viewPrecomputed, so reads are cheaper, but the data may be stale.
OwnershipTreat a published view like a service interface, kept current by the team that owns the source schema.
Use whenFull decomposition is not practical yet. If the goal is a real service interface, prefer splitting the schema.
Cost

A view only helps readers, and its shape must map onto existing tables. It does nothing about the many writers that already change a messy schema directly.

Stop a tangled schema from growing: wrappers and a monolith API

Views control who reads. Writers need a different fence.

Problem

FTGO's restaurant-commission rules live in stored procedures in the monolith database. Restaurant tools, Accounting and an old admin app all call them and write to the same tables, and each team keeps adding a column or a procedure. The schema is too tangled to split now, and it gets worse every sprint.

Solution · Database wrapping service

Put a thin service in front of the tangled schema and make everyone go through its API. Nobody adds to the schema any more; new data goes into each application's own store. Database dependencies become service dependencies, and later you can split the schema behind the wrapper.

The pattern comes from a real case, the same bank as before: its entitlements logic, tangled in stored procedures, was hidden behind a new service so other teams stopped adding data and behavior to it.

Wrapping a hard-to-split database in a service Before After App 1 App 2 App 3 Entitlements schema (stored procs) App 1 App 2 App 3 Wrapper service thin API in front Entitlements schema New data goes in app-local stores no more growth Everyone writes straight in Database dependencies become service dependencies. Later you can split the schema.
ViewWrapping service
Shape of dataMust map onto existing tablesAny projection you can code
WritesTypically noYes, through API calls
Consumer changePoint at another schemaSwitch from database access to API calls
Best withRead-only consumersThe same team owns the schema and the wrapper

The fourth coping pattern turns the same idea around. When a new service needs data the monolith still owns, the monolith itself offers an API for it, instead of the new service reaching into its tables. This is the aggregate-exposing monolith, also called the monolith as data access layer. Delivery Service could ask the monolith's new /consumers/{id}/address endpoint rather than read a view. It works as long as the monolith still owns the state changes.

Call them what they are. Views, wrappers and a monolith API are bandages. They are worth it as stepping stones, and when they let you say clearly what is yours and what is not.
Cost

Every caller of a wrapper must switch from SQL to API calls, and the wrapper is one more service to run. None of these patterns helps a reader that really wants SQL: an analyst with a BI tool cannot point it at a REST API.

Give SQL readers their own copy: the reporting database

Some readers do not want an API at all. They want a database they can query in any way they like.

Problem

FTGO's finance analysts build dashboards with a BI tool that runs large SQL joins over orders. Pointed at Order Service's own database, their Monday-morning report slows down order writes at the start of lunch, and every column they touch becomes one the Order team cannot change.

Solution · Reporting database (database-as-a-service interface)

Do not hand readers your working database. Build a separate, read-only database shaped for them, and fill it from the internal one with a mapping engine. The service keeps its read/write API and events; the reporting database is one more endpoint it offers.

The reporting database pattern Order Service Read/write API Internal database (hidden) Mapping engine CDC, batch or events Reporting DB read-only, own schema BI and ad hoc SQL The owning team keeps this endpoint compatible, like any API.

Two rules make it work. Expose only the minimum, so the reporting schema can be shaped for its readers, even on a different database technology: Order Service could store orders in Cassandra and still offer a SQL reporting database. And treat it as part of the service interface: when the internals change, the mapping changes, not the readers. The pattern is called a reporting database, but reporting is only one use; the same idea serves any ad hoc query. Compared with a view:

Compared to a viewDetail
TechnologyThe exposed database can be a different engine from the internal one.
CostMore work, but more freedom to evolve the internal schema.
PathStart with a view; move to a dedicated reporting database when you need to.
FitsRead-only clients and large joins over one service's data. It can also feed a larger warehouse.

The mapping engine is the real work. There are three ways to build it:

Ways to build the mapping engine Change data capture Most robust Freshest view e.g. Debezium Service events Service fires events A listener updates the DB Doubles as public events Batch copy Longest lag Hard to pick changed rows Jobs can silently fail Tip: expose when the external database was last updated, so readers can judge freshness.

Change data capture (CDC) reads the database's own change log, as in chapter 6, so it is the most robust and the freshest. Listening to the service's events works well if Order Service already publishes them. A batch copy lags the longest, struggles to find only the changed rows, and can fail without anyone noticing.

Move away from batch. Batch jobs often do not run, or run too long. Prefer CDC, and do not underestimate the work of keeping the projection correct.
Cost

The copy always lags the source, so readers see slightly old data. Someone must keep the mapping working through every internal change. And it covers one service's data: the analysts' next question joins orders with deliveries and payments.

Query across services: data lakes and warehouses

A reporting database per service still leaves cross-service questions unanswered.

Problem

The monthly business review asks: "Which restaurants had the most late deliveries and the most refunds?" The answer needs data from Order, Delivery and Accounting. With private databases there is no single place to run that join.

Solution · One-way flow into a lake or warehouse

Each service pushes its data into one shared analytical store, and analysts read from there. Data flows one way only: services write, readers read later.

This is "communication through common data": one side writes, others read later, usually by polling. The two best-known forms sit at opposite ends of a coupling scale.

Data lake versus data warehouse One-way flow: services write, others read Data lake raw data in any format Data warehouse structured store with a schema coupling Looser: readers must know how to parse it Tighter: writers must know the structure
Data lakeData warehouse
Who knows the formatThe readersThe writers
If the structure changesReaders adaptWriters break unless updated
Good forLarge volumes, not low latencyLarge volumes and structured reports
Keep the flow one-way. The pattern works because data flows in one direction. If several services both read and write the same records in the shared store, you have rebuilt the shared database: that is common coupling. For near-real-time data, a stream such as Kafka suits better than polling files.
Cost

A lake or warehouse answers questions after the fact; it is never the place to make a decision that must be correct now. With every service owning its data, placing one FTGO order now changes four databases, and no single ACID transaction can cover them.

Patterns in this chapter

PatternProblem it solvesWhat it costs
Database per serviceA shared database hides nothing, so no team can safely change its schemaNo cross-service joins, foreign keys or ACID transactions
Repository, then schema, per bounded contextA live schema cannot be split in one moveA long migration; separate schemas on one engine still share a point of failure
Database viewReaders see, and freeze, the whole schemaRead-only, tied to existing tables and usually the same engine
Database wrapping serviceA tangled schema keeps growing because everyone writes into itCallers must switch to API calls; one more service; a bandage
Aggregate-exposing monolithA new service needs data the monolith still ownsWorks only while the monolith owns the state changes
Reporting databaseSQL and BI readers need ad hoc queries without touching the working databaseData lags; the mapping engine must be kept correct
Data lake or warehouseQueries need data from many servicesOne-way and after the fact; lakes push parsing to readers, warehouses push structure to writers

Recap

Quick check

Kitchen Service and Accounting both read and write FTGO's CONSUMERS table because it was quicker. The Consumer team wants to split the address into several columns. What goes wrong, and what is a safe first step?
Show answer

Nothing is hidden, so the change can break both other services, and the rules for a consumer now live in three places. Give the table one owner, the Consumer Service. Let the others read through a view or the owner's API until they have what they need from its events, and route any writes through the owner's API.

The finance team wants to run heavy SQL over orders from their BI tool. Why not just give them a read-only login to Order Service's database?
Show answer

Their queries would compete with live order traffic, and every column they use would become a public contract the Order team cannot change. Offer a reporting database instead: a read-only copy shaped for them, filled by change data capture, that shows when it was last updated.

Why should data flow only one way into a data warehouse?
Show answer

If services also read and write the same records there, the warehouse becomes a shared read/write database again, with all the coupling this chapter set out to remove.

Still open

Every FTGO service now owns its data. But creating one order touches Order, Consumer, Kitchen and Accounting, each with its own database, and there is no longer one ACID transaction that can make all four changes together or not at all.

Next: 09 Managing transactions with sagas →