Video in progress

Several microservices write directly to the tables of one shared database. What problems does this cause, and how do you separate them?

A shared database couples services tightly through the schema: one team's migration breaks another's, independent deploys and scaling are lost, and who is responsible for what becomes unclear. The separation is to give each table a single owner, with the others going through an API or events, step by step.

📖 Answer

The symptoms you see in practice:

  • Nobody can answer "can we add a column to the users table?" because nobody knows who reads it.
  • One service's heavy query or wrong transaction slows down the others.
  • A business rule (say, "a blocked user can't place an order") is written three different ways in three places.

The separation plan (strangler style):

  1. Inventory. Using pg_stat_statements and a separate DB role per service: which service reads/writes which table. If everyone connects with one role, the first step is to split the roles.
  2. Assign an owner. One owning service per table. Writes by the others are forbidden (REVOKE INSERT, UPDATE ...), and reads stay for the time being.
  3. Replace the reads. The other services go through the owner's API, or keep their own copy (a local read model) based on events the owner emits.
  4. Physical separation. First a separate schema, then a separate database. The last one isn't required: separate databases on one PostgreSQL server are often enough.

I don't hide the trade-offs: an API call or a data copy instead of a JOIN, eventual consistency, more code. For some systems the right answer is "this should really be one service" and merging the services. If two services always write to the same tables together, they aren't logically separate.