0
0
Microservicessystem_design~7 mins

Database per service pattern in Microservices - System Design Guide

Choose your learning style9 modes available
Problem Statement
When multiple microservices share a single database, changes by one service can break others, causing data corruption and deployment delays. This tight coupling reduces service autonomy and makes scaling or evolving services independently very difficult.
Solution
Each microservice owns and manages its own database, isolating its data from others. Services communicate through APIs or messaging to share data, ensuring loose coupling and independent evolution. This separation allows teams to choose the best database type per service and deploy changes without impacting others.
Architecture
Microservice A
┌───────────┐
API / Messaging Bus

This diagram shows three microservices each with its own database. They communicate through an API or messaging bus, avoiding direct database sharing.

Trade-offs
✓ Pros
Enables independent deployment and scaling of each microservice.
Prevents data corruption caused by shared database schema changes.
Allows use of different database technologies optimized per service.
Improves fault isolation; one database failure doesn't affect others.
✗ Cons
Data consistency across services becomes more complex and often eventual.
Requires additional effort to implement inter-service communication.
Increases operational overhead managing multiple databases.
When building a microservices architecture with multiple teams needing autonomy, or when services have distinct data models and scaling needs beyond 1000 requests per second.
For small applications with fewer than 5 services or low data volume where the complexity of multiple databases outweighs benefits.
Real World Examples
Amazon
Each microservice owns its own database to allow independent scaling and deployment, avoiding cross-service data conflicts.
Netflix
Uses database per service to isolate failures and optimize data storage per service type, improving resilience and performance.
Uber
Separates databases per service to handle diverse data models like trips, payments, and user profiles independently.
Alternatives
Shared database pattern
Multiple services share the same database schema and instance.
Use when: When services are tightly coupled or the system is small and simple, requiring less operational overhead.
Command Query Responsibility Segregation (CQRS)
Separates read and write models, often with different databases, but still can be per service or shared.
Use when: When read and write workloads differ significantly and require optimization.
Summary
Database per service pattern isolates data ownership to each microservice, preventing tight coupling.
It enables independent scaling, deployment, and technology choices per service.
This pattern requires careful design of inter-service communication and data consistency.