Video in progress
Two microservices write to the same tables in one database through their own Hibernate entities. What problems does this cause, and how do you get out of it?
Each service's cache and validation know nothing about the other's writes, nobody can change the schema independently, and version agreements break down. The way out is to assign a table owner; everyone else works through an API or events.
📖 Answer
This is the most common form of a "distributed monolith". At first it is convenient: no integration needed. Then a series of problems begins.
Consistency. Service A keeps product in the L2 cache. Service B updates the price directly. A keeps selling at the old price until the TTL expires.
Invariants. Service A checks the rule "price must not be negative" in its entity, B does not. Which rule actually holds in the database is unknown.
Optimistic lock. If B has not mapped @Version in its entity, it does not increase the version, and A's lost update protection does not work.
Schema evolution. A adds a column and makes it NOT NULL, and B's INSERTs start failing. Every migration requires coordinating two teams, and independent deploys are gone.
The way out:
- Assign an owner to each table. The owning service writes; the others only read.
- Move the other services' writes to the owner's API or events.
- For reads during the transition, use database views or read-only access through a separate schema (
GRANT SELECT), with the entities marked@Immutable. - Finally, separate the data: the owner keeps it in its own schema, and the others get their own copy through CDC or events.
Database-level permissions (each service with its own DB user) reinforce these boundaries technically; an agreement alone won't be enough.
Sign up to mark studied questions and save your progress.