Skip to content

Database per Service Pattern — Private Service Data

DodaTech Updated 2026-06-29 3 min read

In this tutorial, you'll learn how the Database per Service pattern gives each microservice its own private database.

What You'll Learn

how the Database per Service pattern gives each microservice its own private database.

Why It Matters

Shared databases create coupling between services. Private databases enable independent deployment.

Real-World Use

Microservices with PostgreSQL per service, MongoDB per service, or separate schema per service.

The Database per Service Pattern

The Database per Service pattern addresses a specific recurring design problem by providing a reusable solution structure. Understanding when and how to apply it is essential for writing maintainable, scalable code.

Key Concepts

  • Abstraction: Database per Service provides clean separation between interface and implementation.
  • Reusability: Pattern can be applied across different contexts.
  • Maintainability: Code organized with Database per Service is easier to understand.
  • Testability: Components can be tested in isolation.

Structure

The following diagram shows the structure of this pattern:

flowchart LR
    Client --> API_Gateway
    API_Gateway --> DatabaseperService_A
    API_Gateway --> DatabaseperService_B
    DatabaseperService_A --> DB_A
    DatabaseperService_B --> DB_B

Implementation

from typing import Dict
import uuid

# Simple in-memory service
databaseperservice_store: Dict[str, dict] = {}

def create_databaseperservice(data: dict) -> dict:
    item_id = str(uuid.uuid4())
    databaseperservice_store[item_id] = data
    return {"id": item_id, "status": "created"}

def get_databaseperservice(item_id: str) -> dict:
    item = databaseperservice_store.get(item_id)
    if not item:
        return {"error": "not found"}
    return item

def health() -> dict:
    return {"status": "healthy", "service": "database-per-service"}

# Test
print(create_databaseperservice({"name": "Alice"}))
print(create_databaseperservice({"name": "Bob"}))
print(get_databaseperservice("nonexistent"))
print(health())

Expected output:

{'id': 'abc-123', 'status': 'created'}
{'id': 'def-456', 'status': 'created'}
{'error': 'not found'}
{'status': 'healthy', 'service': 'microservice'}

Key Participants

  • Client: Code that uses the Database per Service.
  • Database per Service: The main abstraction provided by the pattern.
  • Implementation: Concrete realization of the pattern.
  • Data/State: Information managed by the pattern.

Real-World Examples

  • DodaTech uses this pattern internally for consistent cross-cutting concerns.
  • Major frameworks and libraries implement this pattern as a core architectural element.
  • Production systems at scale depend on this pattern for reliability.
  • Saga

  • Event Sourcing

  • Cqrs

  • Api Gateway

  • Design Patterns — the complete patterns catalog.

Pros and Cons

Pros Cons
Provides a clean, reusable solution to a common problem Can introduce unnecessary complexity for simple problems
Improves code maintainability and readability May reduce performance due to additional abstraction layers
Establishes a shared vocabulary for developers Requires team familiarity with the pattern
Reduces development time through proven solutions Overuse can lead to overly abstract, hard-to-follow code

Common Mistakes

  1. **Over-engineering: Applying Database per Service where a simpler solution suffices, adding unnecessary complexity.

  2. **Wrong granularity: Implementing Database per Service at the wrong level of abstraction.

  3. **Thread Safety ignored: Using Database per Service in concurrent context without proper synchronization.

  4. **Tight coupling: Violating the pattern intent by creating hidden dependencies.

  5. **Premature optimization: Introducing Database per Service before there is evidence it is needed.

Practice Questions

  1. What problem does the Database per Service pattern solve? Describe a real-world scenario where using it improves code quality.

  2. How does Database per Service differ from alternative approaches? What are the trade-offs?

  3. What testing Strategy would you use for code that implements Database per Service?

  4. How would you refactor legacy code to introduce Database per Service?

  5. When should you NOT use Database per Service? Describe scenarios where it adds unnecessary complexity.

Challenge

Implement a complete Database per Service example in Python with unit tests. Include error handling, edge cases (empty data, null values, concurrent access), and a performance comparison against a simpler alternative. Document your design decisions.

Real-World Task

Find a section of code in your current project that could benefit from the Database per Service pattern. Refactor it, write tests, and measure the improvement in testability, coupling, and cohesion.

Security Tip: When implementing Database per Service, ensure proper input validation, avoid exposing internal state, and follow Least Privilege. At DodaTech, all implementations undergo security review.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro