Video in progress

Staff 🌱 Spring

Two services share tables in one database. How do you separate them step by step?

First find out who writes to which table and assign one owner per table; the other service switches from reading directly to getting data through an API or events; then the schema is split, and finally the database is physically separated. Every step has to be reversible.

📖 Answer

A shared database is the tightest coupling there is: if one team renames a column, the other's service breaks; one heavy query slows down both; you have to coordinate deploys.

  1. A map. For every table: who writes, who reads, with which queries. Get this from the database itself, not by searching code: use pg_stat_statements and give each service its own DB user, then look at the log. Often a service thought to be "read-only" turns out to write in one place.

  2. Assign ownership. One owner per table. A table written by two services is the hardest case; usually one service takes the logic over and the other sends it commands.

  3. Replace the access.

  • The other service's writes → through the owner's API.
  • Its reads → an API (low frequency) or keeping its own copy via events (for data that is read a lot). Publish the events for the copy with an outbox or CDC (Debezium).
  • During the transition, a read-only view, then remove that as well.
  1. Split the schemas. First separate schemas and separate DB users inside one database: orders_svc has rights only on the orders schema. This is cheap and the database itself enforces the rule: if someone tries to go in the old way, they get an error immediately.

  2. Physical separation is the last step, and by now it's just a data migration operation.

The hard parts:

  • JOINs. Reporting queries across the two services' tables no longer work. You'll need a separate analytics store (fed through CDC) for reports.
  • Transactions. Writing two tables in one transaction is no longer possible: you need a saga or an outbox, and you have to agree on the intermediate states with the business.
  • Foreign keys don't cross service boundaries: you store the ID, and integrity is checked by the application and reconciliation.

I release each step separately and keep a way back to the previous state. Splitting in one day with a "big bang" almost always ends in an incident.