Database per Service

Introduction

One of the most important principles in microservices is that each service owns its data. From building distributed systems, I've learned that sharing databases between services creates tight coupling that defeats the purpose of microservices. When multiple services access the same tables, schema changes become coordination nightmares.

This article covers data ownership, polyglot persistence, and strategies for maintaining data isolation.

Why Database per Service?

spinner

Trade-offs

Aspect
Shared Database
Database per Service

Coupling

Tight

Loose

Schema Changes

Coordinate all services

Independent

Data Consistency

ACID transactions

Eventual consistency

Queries

Easy joins

Cross-service calls

Scaling

Limited options

Independent scaling

Technology

One database

Polyglot persistence

Data Ownership Principles

Bounded Context Data

Data Duplication is Acceptable

Polyglot Persistence

Choosing the Right Database

spinner
Service
Database
Reason

User Service

PostgreSQL

ACID transactions, complex queries

Order Service

PostgreSQL

Transactional integrity

Product Catalog

Elasticsearch

Full-text search, faceted navigation

Session/Cart

Redis

High speed, TTL support

Analytics

ClickHouse/TimescaleDB

Time-series, aggregations

Documents

MongoDB

Flexible schema

Implementation Examples

Querying Across Services

API Composition

CQRS for Complex Queries

Schema Migration Strategies

Independent Migrations

Backward Compatible Changes

Data Synchronization Patterns

Event-Driven Sync

Change Data Capture (CDC)

Handling Referential Integrity

Practical Exercise

Exercise: Implement Database per Service

Key Takeaways

  1. Own your data - Each service has exclusive access to its database

  2. No cross-database joins - Use API composition or CQRS

  3. Duplicate when needed - Store snapshots for historical accuracy

  4. Polyglot persistence - Choose the right database for each use case

  5. Events for sync - Keep data synchronized through events

What's Next?

With separate databases, we need patterns for distributed transactions. In Article 8: Distributed Data Patterns, we'll explore Sagas, event sourcing, and CQRS.


This article is part of the Microservice Architecture 101 series.

Last updated