Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 37 ยท Designing Service Boundaries

Database per Service and Data Ownership

Why each microservice owns its data, why shared tables break independence, how to trade duplication against coupling, and how to enforce ownership in code.

Separate code is easy to split. Separate data is where microservices succeed or fail. If two services read and write the same tables, they are not independent, whatever the diagram says. A change to a column in one service can break the other at 3 a.m., and neither team can deploy without worrying about the other.

The rule that prevents this is database per service (more precisely, data ownership): every piece of data has exactly one owning service, and every other service gets at it only through that service's API or events. This lesson explains why, what it costs, and how to enforce the rule in code, with a runnable stand-in that rejects illegal access.

One owner per piece of data

Private storage Only the owner touches its tables.
API is the door Others ask, they never read directly.
Free to change The owner can reshape its schema.

Independence is a data property, not a code property.

1 / 2

Why shared tables break independence

Suppose orders and shipping both read an addresses table directly. It looks efficient. Here is what you have actually built.

  • Hidden coupling. The table's columns are now an API that nobody wrote down. Renaming postcode to postal_code breaks shipping, and the owners find out in production.
  • No safe deploys. Every schema migration must be coordinated with all readers, so you are back to releasing together.
  • Unclear responsibility. When the data is wrong, which team fixes it? When it is slow, whose query is to blame?
  • Technology lock-in. Everyone must use the same database engine, even where another one (a search index, a key-value store) would fit one service far better.
  • No encapsulation of rules. Invariants such as "an address must be validated" are enforced in one service's code. Another service writing directly bypasses them.

The same applies to a "shared database, separate schemas" setup when services reach into each other's schemas. Separate schemas inside one server can be a reasonable stepping stone, but only if the ownership rule is enforced (for example with separate database users that cannot read other schemas).

Splitting a schema

Here is a typical monolith schema, and the ownership split. This is a read-only sketch in SQL; it is not run on the site.

SQL
-- Before: one database, one schema, everything joined freely.
-- SELECT o.id, c.email, p.name, i.quantity
--   FROM orders o
--   JOIN customers c ON c.id = o.customer_id
--   JOIN order_lines l ON l.order_id = o.id
--   JOIN products p ON p.id = l.product_id
--   JOIN inventory i ON i.product_id = p.id;

-- After: each service owns its tables in its own database.

-- identity-service database
CREATE TABLE accounts (
  id            BIGINT PRIMARY KEY,
  email         VARCHAR(255) NOT NULL UNIQUE,
  password_hash VARCHAR(255) NOT NULL
);

-- catalog-service database
CREATE TABLE products (
  id          BIGINT PRIMARY KEY,
  name        VARCHAR(200) NOT NULL,
  description TEXT
);

-- orders-service database
CREATE TABLE orders (
  id          BIGINT PRIMARY KEY,
  customer_id BIGINT NOT NULL,      -- an ID only: no foreign key to another database
  placed_at   TIMESTAMP NOT NULL
);
CREATE TABLE order_lines (
  order_id    BIGINT NOT NULL REFERENCES orders(id),
  product_id  BIGINT NOT NULL,      -- an ID only
  product_name VARCHAR(200) NOT NULL, -- a snapshot taken at purchase time
  unit_cents  INTEGER NOT NULL,       -- a snapshot of the price
  quantity    INTEGER NOT NULL
);

-- inventory-service database
CREATE TABLE stock (
  product_id BIGINT PRIMARY KEY,
  on_hand    INTEGER NOT NULL
);

Three things changed. The foreign key from orders.customer_id to a customers table is gone, because a database cannot enforce a foreign key into another database; it is just an identifier now. The join is gone, because the data lives in four places. And order_lines stores the product name and price as a snapshot, so that history stays correct even when the catalog changes tomorrow.

Duplication versus coupling

Splitting data forces a trade. If orders needs the customer's name, there are two choices.

  1. Ask each time. Call the identity service on every use. The data is always fresh, but every order page now depends on identity being up and fast. This is runtime coupling.
  2. Keep a copy. Store the name when the order is placed, or keep a local replica updated from events (Asynchronous Messaging and Events). Orders keeps working when identity is down, but the copy can be stale. This is data duplication.

Neither is free. A useful guideline:

  • Copy data that is a fact at a point in time: the price paid, the delivery address used, the product name on the invoice. These should not change when the source changes. A snapshot is not duplication but correct history.
  • Replicate data you read often and can tolerate being slightly stale (a catalog name for display), updated from change events.
  • Ask for data that must be fresh and is read rarely, such as a live stock level at checkout.

When a screen needs data from several services, you compose it at the edge (an API gateway or backend-for-frontend, covered in API Gateway and Backend for Frontend) or you build a read model (Event Sourcing and CQRS) instead of joining tables.

Do not replicate everything "just in case". Each copy needs update logic, and every copy can be wrong. Replicate on purpose, name the owner of every dataset, and treat all copies as read-only caches.

Enforcing ownership in code

Rules written in a wiki are ignored. Make the wrong thing impossible. In real systems you enforce ownership with separate database credentials (a service's database user can only connect to its own database), separate network access and code review. The stand-in below shows the principle in a few lines: a data store that checks who is asking, and refuses everyone except the owner.

JS A store that rejects non-owners

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second reservation fails with a business reason, and the two direct accesses fail with an error. The owner also stays free to change how it stores stock: nothing outside depends on that. Here #rows is a private field, so even in this model there is no way to reach the data except through the guard.

Referring to data you do not own

When a service holds an identifier for something it does not own, it must expect that the thing might disappear or change. Customers are deleted. Products are retired. Design for it.

JS Snapshot at purchase, ID for the rest

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The order history stays correct through the rename, the price change and the deletion. If the order had only stored productId and joined at read time, the invoice would have changed, or broken, with the catalog.

Reporting and analytics across services

Database per service makes one thing awkward: a report that joins orders, customers and payments cannot run as a single SQL query. Do not break ownership to get it. Instead, copy data out, one way, into a store built for analysis:

  • Event streams and change data capture (CDC): each service publishes its changes (as events, or by streaming its database log) and a pipeline consumes them.
  • Data warehouse or data lake: a separate analytical store collects the copies. A warehouse holds structured, modeled tables for BI tools; a data lake keeps raw files (JSON, Parquet) cheaply for later processing.
  • Read models: a service that needs data from others for its screens keeps its own denormalized copy, updated from their events (see Event Sourcing and CQRS).

This deliberately duplicates data. The owner stays the source of truth, copies may lag, and consumers must never write to them. The benefits are independent scaling (each store is optimized for its workload: transactions in the service, scans in the warehouse) and performance. Companies such as Netflix and Amazon run hundreds of services this way, each with its own data store, feeding shared analytics platforms. The costs are extra pipelines and the need to handle late or reordered data.

Practical advice

  • Name an owner for every dataset and write it down.
  • Share identifiers, not tables, and never foreign keys across databases.
  • You may use one database server for several services at first, but keep separate schemas and separate credentials, and treat it as temporary.
  • Choose the store that fits each service: relational for orders, a document store for a catalog, a search index for search. That choice is one of the quiet benefits of ownership.
  • Expect to need new patterns for consistency across services: Sagas and The Transactional Outbox and Idempotent Consumers.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a shared table between two services undermine independence?

    Anything that reads another service's tables depends on its internal structure. Schema changes then require coordination and joint releases.
  2. 2. An order line stores the product name and unit price at purchase time. What is this?

    Prices paid and names invoiced are historical facts. Copying them is the correct way to keep history stable.
  3. 3. Which data is the best candidate for 'ask the owner each time' rather than copying?

    Live stock must be fresh and read rarely, so asking is the right choice. The others are historical facts and should be snapshots.
  4. 4. Why can't an orders database enforce a foreign key to the customers table in another service's database?

    Constraints work inside one database. Across services, referential integrity becomes an application-level concern handled by events and checks.

Summary

  • Each piece of data has one owning service; others use its API or events, never its tables.
  • Shared tables create hidden coupling, forced coordinated deploys and unclear responsibility.
  • Splitting data removes joins and cross-database foreign keys: services share identifiers instead.
  • Copy point-in-time facts as snapshots, replicate read-mostly data from events, and ask for data that must be fresh.
  • Enforce ownership with separate credentials and APIs, not documentation; the in-process guard shown here only models the idea.

Next: Synchronous Communication with HTTP APIs.