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
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.
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
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.
| Problem | What it means for FTGO |
|---|---|
| Hidden consumers | The Order team knows others read ORDERS, but not which tables or columns they use. |
| Unclear control | The rules for an order's state machine live in three services, and every rule change must be repeated in each one. |
| Schema as public contract | Even an old report nobody maintains freezes the table design. |
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:
| Case | Why it is safe enough |
|---|---|
| Read-only static reference data | Country codes, postal-code lookups: very stable, and changed as an admin task. |
| A database exposed on purpose as an endpoint | Designed and managed for many readers, like the reporting database later in this chapter. |
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.
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.
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.
- Repository per bounded context. Give the kitchen code its own data-access layer. It shows which tables Kitchen really uses. A tool such as SchemaSpy can also show the foreign keys that cross the line.
- Database per bounded context. Give each context its own schema while it is still one deployable. This also fits brand-new systems, where the domain is not yet stable enough to commit to services.
- Logical versus physical. Separate schemas can run on one database engine. That is simpler and cheaper, but the engine is still one point of failure. Separate engines are more robust and cost 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.
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.
The lightest one is a view.
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.
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.
| Aspect | Detail |
|---|---|
| Limits | Usually read-only. The view and its source often must sit on the same engine. Support varies by database. |
| Materialized view | Precomputed, so reads are cheaper, but the data may be stale. |
| Ownership | Treat a published view like a service interface, kept current by the team that owns the source schema. |
| Use when | Full decomposition is not practical yet. If the goal is a real service interface, prefer splitting the schema. |
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.
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.
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.
| View | Wrapping service | |
|---|---|---|
| Shape of data | Must map onto existing tables | Any projection you can code |
| Writes | Typically no | Yes, through API calls |
| Consumer change | Point at another schema | Switch from database access to API calls |
| Best with | Read-only consumers | The 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.
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.
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.
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.
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 view | Detail |
|---|---|
| Technology | The exposed database can be a different engine from the internal one. |
| Cost | More work, but more freedom to evolve the internal schema. |
| Path | Start with a view; move to a dedicated reporting database when you need to. |
| Fits | Read-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:
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.
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.
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.
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 | Data warehouse | |
|---|---|---|
| Who knows the format | The readers | The writers |
| If the structure changes | Readers adapt | Writers break unless updated |
| Good for | Large volumes, not low latency | Large volumes and structured reports |
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
| Pattern | Problem it solves | What it costs |
|---|---|---|
| Database per service | A shared database hides nothing, so no team can safely change its schema | No cross-service joins, foreign keys or ACID transactions |
| Repository, then schema, per bounded context | A live schema cannot be split in one move | A long migration; separate schemas on one engine still share a point of failure |
| Database view | Readers see, and freeze, the whole schema | Read-only, tied to existing tables and usually the same engine |
| Database wrapping service | A tangled schema keeps growing because everyone writes into it | Callers must switch to API calls; one more service; a bandage |
| Aggregate-exposing monolith | A new service needs data the monolith still owns | Works only while the monolith owns the state changes |
| Reporting database | SQL and BI readers need ad hoc queries without touching the working database | Data lags; the mapping engine must be kept correct |
| Data lake or warehouse | Queries need data from many services | One-way and after the fact; lakes push parsing to readers, warehouses push structure to writers |
Recap
- A shared database hides nothing: nobody knows who reads which column, the rules for one record live in several services, and the schema freezes into a public contract.
- Each service should own its data and offer it only through its API and events; sharing is acceptable only for static reference data and databases exposed on purpose.
- Split in stages: data-access code per bounded context first, then a schema per context, then separate services, choosing a logical or physical split.
- While a schema is still shared, views limit what readers see, a wrapping service stops a tangled schema from growing, and a monolith API serves data the monolith still owns; all of them are stepping stones.
- A reporting database is a read-only copy with its own schema, filled by a mapping engine (preferably change data capture), and treated as part of the service interface.
- Data lakes and warehouses answer cross-service questions, as long as data flows one way into them.
Quick check
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.
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.
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.
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.