Tutorials Microservices Mastery

Database Per Service: Handling distributed data consistency

On this page

Database Per Service

The most controversial yet essential rule of microservices: Every service must own its own data. No other service is allowed to talk to your database. This ensures total decoupling, but it introduces the hardest problem in distributed systems: Distributed Data Consistency.

1. Why isolate the DB?

If Service A and Service B share a database, you cannot change the schema of Table X without breaking both. You have created a Shared-Database Monolith. By isolating the DB, Service A can switch to MongoDB while Service B uses PostgreSQL, and neither side cares.

2. How to "Join" data across services?

You cannot use a SQL JOIN across two microservices. There are two solutions:

  • API Aggregation (Facade): Call Service A, call Service B, and merge the results in your Gateway. (Slow).
  • Data Duplication (Projection): Service B listens for an event when Service A changes, and saves a "Copy" of the relevant data in its own database. (Fast, but eventually consistent).

4. Interview Mastery

Q: "If my services have separate databases, how do I handle a transaction that spans both (e.g., Create Order and Deduct Money)?"

Architect Answer: "You cannot use traditional ACID transactions (BeginTran/Commit) over a network. Instead, we use the **Saga Pattern**. A Saga is a sequence of local transactions. One service finishes its work and publishes a 'Success' event. The next service hears it and does its work. If a step fails, you must execute **Compensating Transactions** (Undo actions) to manually revert the previous steps. This is the price we pay for massive scalability."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

Microservices Mastery
Course syllabus
1. Distributed Systems Fundamentals
2. Containerization & Orchestration
3. Service Communication
4. Event-Driven Architecture
5. Resilience & Scalability
6. Observability & Security
7. Advanced Cloud Topics
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details