Database per Service: Data Ownership and Boundaries

Decide how microservices should own data, when to separate database infrastructure, and how to handle cross-service reads, consistency, and analytics.

published: reading time: 21 min read author: Geek Workbench updated: November 12, 2026
Quick Summary

A service boundary starts with data ownership: one service controls the writes to its authoritative records. That boundary does not require a separate physical database for every service. Separate schemas, roles, or infrastructure each offer different isolation and operational costs. This guide helps teams choose a boundary, handle cross-service queries, and decide when APIs, local read models, or an analytics pipeline fit the work.

Database per Service: Data Ownership and Boundaries

The pattern is about data ownership: one service controls writes to the records for which it is authoritative. A separate database deployment is one way to enforce that boundary, but it is not a requirement. Teams may start with separate schemas or database roles on a shared cluster when those controls meet their isolation needs.

The choice affects deployment, security, scaling, recovery, and the cost of operating another database. The boundary should follow the domain and the team’s ability to operate it, not a rule that every service gets its own server.

Introduction

The database per service pattern means that a microservice is the authority for writes to its data. Other services should not modify those records directly. They can read what they need through an API, a purpose-built read model, or a controlled analytics pipeline.

Think of it like a neighborhood where each house has its own yard and front door. Your neighbor cannot just walk into your kitchen, even though you might chat over the fence. If you want something from your neighbor’s kitchen, you knock on the door and ask.

The boundary is intentional. If several services depend on the same tables, schema changes can couple their deployments even when the code lives in separate repositories.

Choose the boundary before the database

Use this checklist to decide how much isolation a service needs:

  • Name the service that owns writes and the team responsible for the schema and recovery.
  • Identify which reads cross the boundary, how fresh they must be, and what happens when the owning service is unavailable.
  • Decide whether separate schemas and credentials on a shared cluster meet security, availability, and operational requirements.
  • Choose a separate database deployment when isolation, scaling, compliance, or failure-domain needs justify its extra cost and on-call work.
  • Record backup, restore, migration, and monitoring ownership before splitting infrastructure.

Separate physical databases can provide stronger resource and failure isolation, but they add connection management, upgrades, backups, monitoring, and recovery work. A shared cluster with per-service roles or schemas can be a reasonable boundary when access controls are enforced and the team accepts the shared failure domain. Neither option creates service ownership by itself.

What This Looks Like in Practice

The diagram uses separate stores to show ownership. Those stores can run on separate infrastructure or on a shared cluster with enforced roles and schema boundaries.

A user service manages user accounts and authentication data in its own database. An order service handles orders and line items separately. A product catalog service maintains its own product information. None of these services reaches into another service’s database.

When the order service needs to know who placed an order, it does not query the user database directly. Instead, it either receives user information as part of the API response when the order is created, or it calls a user service API to look up the information it needs.

graph TB
    UserService --> UserDB[(User Database)]
    OrderService --> OrderDB[(Order Database)]
    ProductService --> ProductDB[(Product Database)]
    InventoryService --> InventoryDB[(Inventory Database)]

    OrderService -->|REST/gRPC| UserService
    OrderService -->|REST/gRPC| ProductService
    OrderService -->|REST/gRPC| InventoryService

    class UserService,OrderService,ProductService,InventoryService service
    class UserDB,OrderDB,ProductDB,InventoryDB database

Why Teams Embrace This Pattern

The database per service pattern delivers real advantages for teams building things.

Team Autonomy

When each team owns a service and its data, work can happen independently without coordination bottlenecks. The ordering team can change their database schema, optimize queries, or even switch database technologies without getting permission from the user team or the product team.

This autonomy extends to deployment. Teams can release updates on their own schedule, roll back if something breaks, and experiment with different approaches without risking the entire system.

Schema changes can proceed on the owning team’s schedule when other services use an API or published event instead of querying the tables directly. Technology changes are also easier to isolate when the service contract remains stable, though downstream clients still need compatible API or event changes.

The failure mode to avoid is a shared database with informal ownership boundaries. If the order team needs the user team to add an index for a query they own, autonomy collapses into a ticket queue. Database per service makes ownership explicit and self-service.

Independent Scaling

Different services have different resource needs. Your product catalog might need heavy read throughput during a sale event, while your order processing needs more write capacity during checkout. With separate databases, you can scale each service’s data layer independently.

You might run three replicas of your product database during a flash sale while keeping your order database on beefy write-optimized hardware. No single database becomes a bottleneck that throttles the entire system.

The workloads may differ: a catalog can be read-heavy while order processing has stricter write and transaction requirements. Separate infrastructure may let each scale independently, but the benefit depends on measured contention and the database platform. Benchmark the real query mix before using replica counts or throughput figures as a sizing rule. See Database Scaling for a capacity test plan.

Technology Diversity

Not every problem needs the same tool. A product catalog with complex, hierarchical search might work well with MongoDB or Elasticsearch. User accounts with strict transactional requirements might belong in PostgreSQL. Session data that needs extreme read speeds might live in Redis.

Database per service lets you pick the right tool for each job rather than compromising everything on a single technology that has to serve all your needs.

The reasoning behind the picks matters more than the picks themselves. Relational databases work when your data has fixed structure and relationships that matter: orders have line items, line items reference products, products belong to categories. These foreign key constraints are not bureaucratic overhead, they are business rules enforced at the database level. If you remove them and move to a document store, you now need application code to enforce what the database used to handle for free.

Document databases make sense when the shape of your data varies in ways you cannot predict. A product catalog where each product type has different attributes, a user profile where you need to store arbitrary metadata, a content management system where pages have dynamic schemas. The flexibility is real, but it comes at a cost: you trade schema enforcement for freedom, and that trade-off only pays off when the schema truly varies and variation is a feature, not a bug.

Key-value stores fit workloads centered on keyed lookups, such as sessions or cache entries. Their latency and throughput depend on the data size, network, persistence settings, and workload. They do not replace a relational store when the service needs joins, transactions, or queries beyond the key access pattern.

The Challenges Nobody Talks About Upfront

The benefits are real, but so are the difficulties. Before you commit to this pattern, you need to understand what you are signing up for.

Cross-service queries

A query that needs records from several owners must choose between request-time calls, a local read model, and an analytical pipeline. Compare the freshness requirement, request latency, availability dependencies, and maintenance cost. The Cross-Service Reads section outlines those options.

Data Consistency Across Services

When a workflow writes to several service-owned databases, there is no single local transaction covering all of them. Choose consistency from the business invariant and decide how partial progress is handled.

Patterns like the saga pattern handle this. Instead of ACID transactions across services, you coordinate a series of local transactions through messaging. It is more complex, but it works.

For checkout, make reservation an operation owned by the inventory service and make it safe under concurrent requests, for example with an atomic conditional update and an idempotency key. If checkout spans local transactions in several services, a saga can coordinate steps and compensation. A saga does not replace atomic writes inside one database.

Reporting and analytics

Reports that cross service boundaries usually belong in an analytical store with an explicit freshness target. The pipeline adds operational work and can affect source systems, so measure its load and monitor data freshness. See Reporting Across Services for the boundary decision.

Cross-Service Reads

First decide how fresh the result needs to be and how often the query runs. API composition calls the owning services at request time; it keeps data current but adds network latency and makes the caller depend on those services being available. It fits occasional views where that cost is acceptable.

A read model can serve repeated queries without calling several services on every request. CQRS separates the write model from a read model that is updated from events or other change feeds. The read model can be stale, so define its freshness target and recovery process. See CQRS for the pattern and its trade-offs.

Event sourcing stores changes as events and rebuilds projections from them. It is a separate modeling choice, not a requirement for service-owned data. See Event Sourcing before choosing it; the saga pattern addresses multi-service workflows that need coordinated local transactions.

For reporting and analytics, move data into an analytical model designed for those queries rather than adding cross-service joins to a user-facing request. Data Warehouse Architecture covers the system boundaries; Data Warehousing covers warehouse modeling.

Data Ownership and Bounded Contexts

The database per service pattern forces you to think carefully about where data belongs. This is a domain modeling decision as much as a technical one.

Defining Service Boundaries Around Data

You need to identify bounded contexts in your domain: areas where a clear and consistent model applies. A user context and an ordering context might share the concept of a “customer,” but they model it differently for their own needs.

The ordering context cares about customer IDs, shipping addresses, and contact preferences for fulfilling orders. The user context cares about login credentials, profile information, and communication preferences. These are related but distinct models of the same real-world entity.

Each service owns its bounded context completely. If two services need similar data, they each maintain their own copy, synchronized through events or API calls.

Two practical signals identify bounded contexts. Ubiquitous language is the first: a term means the same thing everywhere within a bounded context but differs across contexts. In the ordering context, “order” means a purchase transaction with line items, pricing, and fulfillment state. In the shipping context, “order” means a parcel with a tracking number, carrier, and delivery window. The same word meaning different things signals separate contexts. Independent deployment is the second signal: if two things change for unrelated reasons, deployed on different schedules by different teams, they are likely separate bounded contexts. If changing the fraud detection rules in the payment service never requires changing anything in the product catalog service, those are separate contexts. If a change to one always seems to require a change to the other, they may belong in the same service.

When to Duplicate Data

Data duplication is not always a problem to avoid. Sometimes it is the right trade-off.

If your order service stores a copy of the product name and price at the time of purchase, you have an accurate record of what the customer actually ordered, even if the product catalog changes later. This immutability of historical records is often more valuable than a single source of truth.

The cost is keeping the copies synchronized when things change. You have to decide which data changes slowly versus frequently, which historical accuracy matters, and which services can tolerate stale reads.

Duplication makes sense for immutable data. An order record is immutable; you never change the amount charged or the products ordered after checkout. The product name and price stored in the order are correct by definition, regardless of what the product catalog later shows. Duplication also makes sense when the downstream service needs the data at read time without a network call and stale data is acceptable. A product recommendation cache storing product names and categories serves reads instantly from local memory even if the catalog updates the name a few hours ago. Duplication does not make sense when data changes frequently and downstream services need the current value. Storing a product’s real-time inventory count in the order service creates a synchronization burden that rarely pays off; the order service should call the inventory service at order placement time instead.

Choose storage for the service’s access patterns

This page is about ownership boundaries, not a ranking of database products. Choose storage from the service’s data model, query patterns, consistency needs, recovery requirements, team skills, and ability to operate it.

Workload Starting point Questions to answer
Transactional records with relationships Relational database Which constraints and transactions must the database enforce?
Records with intentionally variable shape Document database How will the team validate fields and handle schema evolution?
Keyed lookups or ephemeral state Key-value store What are the persistence, eviction, and recovery requirements?
Time-windowed measurements Time-series store or relational extensions Which retention, aggregation, and write patterns need benchmarking?
Full-text retrieval Search index Which source remains authoritative, and how will the index be rebuilt?

A service can use more than one store, but every copy needs a named owner and recovery plan. Treat search indexes and caches as derived data unless the system explicitly assigns them authority. Avoid selecting a product from a benchmark or feature list that does not match your data and query mix.

Reporting Across Services

Analytical queries often need records from several services and can tolerate a different freshness target than checkout or account updates. Feed a warehouse or analytical store through a controlled batch or change-data-capture pipeline. Define source ownership, schema-change handling, freshness monitoring, and access controls for each dataset. Avoid running broad reporting queries against operational databases without measuring their impact.

For a deeper discussion of layer boundaries, see Data Warehouse Architecture. The modeling guide is Data Warehousing, while Data Migration covers moving records between systems.

Decide how much isolation the service needs

Decision factor Shared cluster with service-owned schema or role Separate database deployment
Write ownership Enforce ownership with grants and migration rules Enforce ownership at the deployment boundary
Resource contention Services share the cluster’s capacity Capacity can be managed per deployment
Failure domain Cluster incidents can affect several services Failures can be isolated, depending on shared infrastructure
Operations Fewer upgrades, backups, and monitoring targets More independent upgrades, backups, monitoring, and recovery work
Cross-service transactions Possible only where one database transaction covers the required data Require an application workflow across owners

Choose separate infrastructure when measured resource contention, recovery objectives, security boundaries, or independent scaling justify the additional operational work. For regulatory requirements, confirm the design with the organization’s security and compliance owners; a separate database alone does not establish compliance.

A shared cluster can be a sensible starting point when the team is small, workloads do not interfere, and its shared failure domain is acceptable. Give each service its own database role or schema, prohibit writes into another service’s tables, and test that the owning team can back up and restore its data. Split infrastructure when evidence or requirements justify it, rather than assigning a server to every service by default.

Before committing, answer these questions:

  • Which service owns writes to each record, and who approves schema changes?
  • Which reads cross the boundary, and what freshness and availability do they require?
  • What consistency invariant must hold when a workflow touches multiple services?
  • Who owns backups, restore tests, migrations, capacity, and on-call response?
  • What measured benefit will justify the cost of a separate deployment?

Use Cross-Service Reads to choose request-time calls, a read model, or an analytics pipeline. See CQRS, Event Sourcing, and sagas for those separate patterns.

Production Failure Scenarios

Failure Impact Mitigation
Database for one service goes down Only that service fails; other services continue Isolate service failures; implement circuit breakers; health checks
Cross-service query timeout API gateway or BFF times out Set appropriate timeouts; implement fallback; degrade gracefully
Data inconsistency between services Services show different states for same entity Implement idempotent operations; saga pattern for consistency; monitoring
Schema migration in shared DB blocks All services using DB are blocked Use online schema migration tools; avoid locking operations
Connection pool exhaustion Service cannot connect to its DB Configure appropriate pool sizes; monitor connections; implement connection timeouts
Backup failure for isolated DB Data loss risk for that service Regular backup verification; multi-region backup storage; test restores

Data Consistency Flow

graph TD
    Start[Order Request] --> CheckInventory{Check Inventory}
    CheckInventory -->|Sync Call| InvDB[Inventory DB]
    InvDB -->|Reserve| InvReserve[Reserved: 5 units]
    CheckInventory -->|Reserve OK| CheckPayment{Check Payment}
    CheckPayment -->|Sync Call| PayDB[Payment DB]
    PayDB -->|Authorize| PayAuth[Authorized: $100]
    CheckPayment -->|Auth OK| CreateOrder[Create Order]
    CreateOrder --> OrderDB[(Order DB)]
    CreateOrder -->|Publish Event| InvEvent[Inventory Event]
    InvEvent --> UpdateInv[Update Inventory Read Model]
    CreateOrder -->|Publish Event| PayEvent[Payment Event]
    PayEvent --> UpdatePay[Update Payment Read Model]

API Composition Flow

graph LR
    Client[Client] --> Gateway[API Gateway]
    Gateway --> UserSvc[User Service]
    Gateway --> OrderSvc[Order Service]
    Gateway --> ProductSvc[Product Service]

    UserSvc --> UserDB[(User DB)]
    OrderSvc --> OrderDB[(Order DB)]
    ProductSvc --> ProductDB[(Product DB)]

    subgraph Composition
        OrderSvc -->|Get User| UserSvc
        OrderSvc -->|Get Product| ProductSvc
    end

    OrderDB --> Aggregate[Aggregate Results]
    UserDB --> Aggregate
    ProductDB --> Aggregate
    Aggregate --> Client

Trade-offs to record

Choice Helps with Adds or requires
Shared cluster with per-service roles or schemas Lower infrastructure and on-call overhead while preserving write ownership Shared resource limits and failure domain; access controls must be enforced
Separate database deployment Independent capacity, maintenance, and some failure isolation More upgrades, backups, monitoring, connection management, and recovery procedures
API composition Current data for an occasional cross-service view Request-time latency and dependency on each service being available
Local read model Repeated queries without calling every owner at request time A freshness target, replay or rebuild process, and monitoring
Cross-service workflow A business process spanning several owners Explicit partial-failure handling, often through a saga or another distributed transaction design

There is no service-count threshold that determines when to split infrastructure. Compare measured contention, recovery objectives, access requirements, workload shape, and the team’s operating capacity. For a monolith migration, extract a cohesive service and enforce its data boundary incrementally; a shared cluster can remain in place while ownership rules change.

A local database transaction protects invariants within its database. Workflows that write to several service-owned stores need an explicit coordination policy. Read Saga Pattern for local transactions with compensation and Two-Phase Commit for the coordinator-based alternative and its blocking trade-offs.

For schema changes within one database, see Database Migration Strategies. Moving records between systems is a separate task covered by Data Migration.

Common Pitfalls / Anti-Patterns

Looking at how teams struggle with this pattern, a few mistakes come up repeatedly.

A shared cluster does not have to become a shared ownership model. Give each service its own role or schema, keep other services from writing its tables, and document any cross-service reads. If later measurements or isolation requirements call for separate deployments, the migration still needs an owner, compatibility plan, and recovery rehearsal.

Over-normalizing to match the monolith leads to chatty APIs. If you model every table as its own microservice, you will spend all your time coordinating network calls. Look for natural aggregates that can live together in a single service.

Ignoring saga or compensation logic until production is a recipe for corrupted data. Design your cross-service workflows before you deploy, not after users start encountering inconsistencies.

Do not accept stale reads by default. Write down which views can lag, how long they may lag, and what action to take when freshness falls outside that target. Keep operations that must be atomic within the owning service where possible.

Interview Questions

1. What does service data ownership mean?

One service is responsible for authoritative writes, schema changes, and recovery for a set of records. Other services use an agreed interface or derived read model rather than editing those records directly.

2. Does database per service require a separate database server?

No. Separate roles or schemas on a shared cluster can enforce ownership when access controls and the shared failure domain meet the requirements. A separate deployment adds resource and failure isolation, with more operational work.

3. How should a service read data owned by another service?

Use an API for occasional reads that need current data, or a local read model for repeated queries that can tolerate a defined freshness delay. Keep analytics in a pipeline designed for cross-service reporting.

4. When is a saga useful?

Use a saga when a business workflow spans local transactions in multiple services and needs explicit handling for partial completion. Keep each service's own invariant atomic in its database; a saga coordinates steps and compensation across owners.

5. What should be documented before a service gets a separate database deployment?

Record the isolation or scaling need, the owner, expected workload, backup and restore procedure, monitoring, migration process, and on-call responsibility. A separate server without those operational plans only moves the coupling.

6. How do you test whether a read model is suitable for a cross-service query?

Define its freshness objective, measure update lag, test rebuild and replay, and verify how consumers behave when the read model is stale or unavailable. Compare that cost with request-time calls to the owning services.

Quick Recap

  • Assign one service as the authority for writes and schema changes.
  • Choose shared or separate infrastructure from isolation, capacity, recovery, and operating requirements.
  • Route cross-service reads through APIs, derived read models, or an analytics pipeline.
  • Keep local invariants atomic; use a saga only for workflows that span owners.
  • Assign an owner and restore procedure to every database and derived copy.

Further Reading

Conclusion

Start with the owner of each record and the writes that must remain consistent. Then choose whether a shared cluster, separate schemas, or separate database deployments meet the isolation and capacity needs. The more infrastructure you split, the more backup, monitoring, upgrade, and recovery work your teams take on.

Use APIs for occasional cross-service reads, read models for repeated queries with an explicit freshness target, and an analytical pipeline for reporting. Keep CQRS, event sourcing, and saga design in their focused guides linked above.

Implementation Example: keep writes with the owner

This pseudocode shows the boundary only. Production code still needs request timeouts, idempotency, validation, and an explicit policy for partial failure.

def create_order(request, user_api, order_store):
    customer = user_api.get_customer(request.customer_id)
    if customer is None:
        raise CustomerNotFound(request.customer_id)

    # Persist the order only through its owning service's store.
    return order_store.insert({
        "customer_id": customer.id,
        "items": request.items,
        "status": "pending",
    })

Do not pass another service’s database connection into this handler. If the workflow also reserves inventory or charges payment, define those as separate steps and use the saga guide when coordinated recovery is required.

Category

Related Posts

GraphQL Federation: Subgraphs, Routing, and Trade-offs

Learn how GraphQL federation composes subgraphs, routes operations, and affects service ownership, query planning, latency, failure handling, and authorization.

#graphql #federation #microservices

Amazon Architecture: History and Service Design

Separate documented Amazon and AWS milestones from popular retellings, then apply the lesson about service boundaries to a current request flow.

#microservices #amazon #architecture

Asynchronous Communication: From Outbox to Consumer

Choose when to use asynchronous messaging and follow an order event through an outbox, delivery, idempotency, retries, dead-letter handling, and monitoring.

#microservices #asynchronous #event-driven