Database Per Service Pattern: Definition, Example, and Use Cases
database per service pattern means each microservice has its own separate database to store its data independently. This pattern helps services stay isolated, avoid conflicts, and scale better by managing their own data.How It Works
Imagine a group of friends each keeping their own diary instead of sharing one big notebook. Each friend writes and manages their own stories without mixing with others. In microservices, the database per service pattern works the same way: every service has its own database to store its data.
This separation means services do not depend on a shared database, so they can change or scale their data storage independently. It also reduces the risk of one service accidentally breaking another by changing shared data. Each service controls its data, making the system more flexible and easier to maintain.
Example
This example shows two simple microservices, UserService and OrderService, each with its own database represented as Python dictionaries.
class UserService: def __init__(self): self.users_db = {} def add_user(self, user_id, name): self.users_db[user_id] = name def get_user(self, user_id): return self.users_db.get(user_id, None) class OrderService: def __init__(self): self.orders_db = {} def add_order(self, order_id, user_id, item): self.orders_db[order_id] = {'user_id': user_id, 'item': item} def get_order(self, order_id): return self.orders_db.get(order_id, None) # Using the services user_service = UserService() order_service = OrderService() user_service.add_user(1, 'Alice') order_service.add_order(101, 1, 'Book') print('User:', user_service.get_user(1)) print('Order:', order_service.get_order(101))
When to Use
Use the database per service pattern when you want to keep microservices independent and scalable. It is ideal if services have different data needs or use different database types (like SQL for one and NoSQL for another).
This pattern fits well in large systems where teams work on separate services and want to avoid conflicts or tight coupling caused by sharing a single database. It also helps when you want to deploy or update services without affecting others.
Key Points
- Each microservice owns and manages its own database.
- Improves service independence and reduces coupling.
- Supports different database technologies per service.
- Helps scale and deploy services separately.
- Requires careful design for data consistency across services.