Database per Service — Pros/Cons
Database per Service — Pros/Cons
Database-per-service is a core microservices principle. Each service owns its data, schema, and persistence technology. This improves autonomy but introduces distributed data management challenges.
Pros
- Service autonomy: teams can evolve schemas without cross-team coordination.
- Technology diversity: choose the best database for each domain.
- Failure isolation: one database outage does not directly impact others.
- Scaling independence: scale storage and compute per service.
Cons
- No cross-service transactions: distributed transactions are complex.
- Data duplication: each service may store denormalized copies.
- Reporting complexity: analytics require data aggregation pipelines.
- Operational overhead: many databases to monitor and backup.
Strategies to Mitigate the Cons
1. API Composition
Aggregate data through service calls instead of direct joins. Use a dedicated aggregator service to avoid N+1 call patterns.
2. CQRS and Read Models
Maintain dedicated read models for query-heavy scenarios. This keeps the write model isolated while serving efficient queries.
3. Data Warehousing
Stream events into a data warehouse for analytics. This avoids cross-service joins in production systems.
Spring Boot Example: Clear Ownership
1
2
3
4
5
6
@Entity
public class CustomerProfile {
@Id
private String id;
private String email;
}
1
2
3
4
5
6
7
8
9
10
11
12
@Service
public class CustomerService {
private final CustomerRepository customerRepository;
public CustomerService(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
public CustomerProfile getCustomer(String id) {
return customerRepository.findById(id).orElseThrow();
}
}
Summary
Database-per-service improves autonomy and scaling but trades off transactional consistency. The pattern works best when paired with event-driven integration, read models, and analytics pipelines.
This post is licensed under CC BY 4.0 by the author.