Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Concept · 25 min · revision 1

Database per service and querying across services

See why shared tables quietly undo a split, choose how strictly to separate each service's data, and answer a question that needs two owners' data by API composition or by a read model fed by events, measuring what each one moves, how fresh it is and what happens in an outage.

Contentsand lesson path

What you will learn

  • Assign data ownership per service and choose how other services read that data (API composition, replicated read models or events).

Prerequisites: Strategic Domain-Driven Design

01. Why it matters

In the monolith, the support screen latest orders from gold-tier customers was one SQL query joining orders to customers. After the split in lesson 3, Orders owns the orders and Customers owns the tiers, each in its own database. The join is gone, the screen is still needed, and someone suggests the obvious shortcut: let the support service read both databases.

This lesson explains why that shortcut quietly brings back the coupling the split was meant to remove, how strictly to separate each service's data, and the two main ways to answer a question that spans owners, with numbers from a small experiment.

02. Why shared tables break autonomy

A shared database is not a foolish choice. It gives joins, transactions across all tables and one backup, and in a modular monolith or a small service-based system it is often right. It fails the goal of microservices for four reasons:

  • The schema becomes a contract. If any other service reads a table, renaming or splitting a column needs that service's agreement and a coordinated release. A read-only database user or a view across databases does not help: the reader still depends on the table's shape and meaning.
  • Writers share invariants. If two services write one table, neither can enforce its rules alone, and a bug in one corrupts the other's data.
  • Load is shared. One service's heavy report can slow every service on the same database.
  • Technology is fixed. A service that would be better served by a document store or a search index cannot switch.

So under database per service, only the owning service reads or writes its data, and everyone else goes through its API or its events. Some databases can join across schemas or servers, but using that between services reads another service's storage, which is exactly what the rule forbids.

03. How strictly to separate, and where invariants live

The pattern catalogue at microservices.io lists three levels. Private tables per service and schema per service share one database server and cost the least to run; a schema makes ownership easier to see, and separate database users with grants turn the convention into a rule. Database server per service costs the most, but it is the simplest way to give a service its own CPU, memory and disk, and its own server-level operations. Some operations act on a whole server: PostgreSQL's documentation says point-in-time recovery can restore only an entire database cluster, not a subset, and a major-version upgrade or a restart touches every database on it. Per-role connection limits or a read replica for heavy reports help, but only partly. A common path is to start with a schema per service and move a service onto its own server when its load, its recovery needs or its upgrade schedule justify it.

Data ownership also decides where business rules can be strict. Inside one service, a rule such as stock never goes below zero is still enforced by a local transaction, exactly as before. A rule that spans two owners, such as an order may not exceed the customer's credit limit when Customers owns the limit, can no longer be one transaction. Either the rule moves inside one service (Orders keeps the credit it is allowed to use), or it becomes a workflow of local steps that can be compensated, covered in distributed data patterns. Copies of data held by other services are allowed to lag; the owner's record is the one that must be right.

04. Querying across services: an experiment

There are two main ways to answer the support screen. API composition: a composer (the support service, a gateway or a backend) calls each owner's API and joins the results in memory. A read model: a separate store shaped for the question and kept up to date from the owners' events, the query side of CQRS (command query responsibility segregation), which queues, topics and logs gives the messaging background for.

The experiment builds both with SQLite in memory: 2,000 customers, about 5% of them gold, and 50,000 orders, from a fixed random seed. Each "API" function reads only its own service's database, and every row an API returns counts as a row moved over the network. Composition is tried twice: once when Orders can only page through orders by date (A), and once when it also accepts a list of customer ids (B). Python 3.12 or newer; put both files in one folder.

Python · stores.py
"""stores.py: two services that each own a SQLite database, and a read model.

Each "API" function reads only its own service's database. Rows an API returns
are counted as rows moved over the network.
"""
import random
import sqlite3

rng = random.Random(7)
up = {"customers": True}  # flip to False to simulate an outage

customers_db = sqlite3.connect(":memory:")  # owned by the Customers service
customers_db.execute("CREATE TABLE customers (id INTEGER PRIMARY KEY, tier TEXT)")
customers_db.executemany("INSERT INTO customers VALUES (?, ?)", [
    (c, "gold" if rng.random() < 0.05 else "standard") for c in range(1, 2001)])

orders_db = sqlite3.connect(":memory:")  # owned by the Orders service
orders_db.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INT)")
orders_db.executemany("INSERT INTO orders VALUES (?, ?)", [
    (o, rng.randint(1, 2000)) for o in range(1, 50_001)])  # higher id = newer

moved = {"calls": 0, "rows": 0}


def api(rows: list) -> list:
    moved["calls"] += 1
    moved["rows"] += len(rows)
    return rows


def customers_api(sql: str, args=()) -> list:
    if not up["customers"]:
        raise ConnectionError("Customers service unavailable")
    return api(customers_db.execute(sql, args).fetchall())


def orders_page(before: int, size: int = 200) -> list:  # GET /orders?before=..
    return api(orders_db.execute("SELECT id, customer_id FROM orders WHERE id < ? "
                                 "ORDER BY id DESC LIMIT ?", (before, size)).fetchall())


def compose_by_paging() -> list:
    """A: Orders can only page by date, so read pages and ask Customers for tiers."""
    found, before = [], 10**9
    while len(found) < 10:
        page = orders_page(before)
        if not page:  # ran out of orders: fewer than 10 match
            break
        ids = sorted({c for _, c in page})
        marks = ",".join("?" * len(ids))  # GET /customers?ids=..
        tiers = customers_api(f"SELECT id, tier FROM customers WHERE id IN ({marks})",
                              ids)
        gold = {c for c, t in tiers if t == "gold"}
        found += [o for o, c in page if c in gold]
        before = page[-1][0]
    return found[:10]


def compose_by_ids() -> list:
    """B: Customers lists gold ids; Orders accepts a list of customer ids."""
    gold = [c for (c,) in customers_api("SELECT id FROM customers WHERE tier = 'gold'")]
    marks = ",".join("?" * len(gold))
    return [o for (o,) in api(orders_db.execute(
        f"SELECT id FROM orders WHERE customer_id IN ({marks}) "
        "ORDER BY id DESC LIMIT 10", gold).fetchall())]


# C: a read model owned by the reporting side, built only from events.
view_db = sqlite3.connect(":memory:")
view_db.execute("CREATE TABLE tier (customer_id INTEGER PRIMARY KEY, tier TEXT)")
view_db.execute("CREATE TABLE order_view (order_id INT, customer_id INT, tier TEXT)")
view_db.execute("CREATE INDEX by_tier ON order_view (tier, order_id)")


def on_event(kind: str, data: tuple) -> None:
    if kind == "CustomerTierChanged":
        view_db.execute("INSERT OR REPLACE INTO tier VALUES (?, ?)", data)
        view_db.execute("UPDATE order_view SET tier = ? WHERE customer_id = ?",
                        (data[1], data[0]))
    elif kind == "OrderPlaced":
        (tier,) = view_db.execute("SELECT tier FROM tier WHERE customer_id = ?",
                                  (data[1],)).fetchone()
        view_db.execute("INSERT INTO order_view VALUES (?, ?, ?)", (*data, tier))


def read_model() -> list:
    return [o for (o,) in api(view_db.execute(
        "SELECT order_id FROM order_view WHERE tier = 'gold' "
        "ORDER BY order_id DESC LIMIT 10").fetchall())]


for row in customers_db.execute("SELECT id, tier FROM customers"):
    on_event("CustomerTierChanged", row)
for row in orders_db.execute("SELECT id, customer_id FROM orders ORDER BY id"):
    on_event("OrderPlaced", row)
Python · query_across.py
"""query_across.py: "the 10 most recent orders by gold-tier customers", three ways."""
import stores as s

gold = s.customers_db.execute(
    "SELECT COUNT(*) FROM customers WHERE tier = 'gold'").fetchone()[0]
print(f"gold customers: {gold} of 2,000; orders: 50,000")
answers = []
for label, ask in [("A) compose, page by date", s.compose_by_paging),
                   ("B) compose, filter by ids", s.compose_by_ids),
                   ("C) read model from events", s.read_model)]:
    s.moved.update(calls=0, rows=0)
    answers.append(ask())
    print(f"  {label:<27} calls {s.moved['calls']:3}  rows moved {s.moved['rows']:6,}")
print("  same 10 orders in A, B and C:", answers[0] == answers[1] == answers[2])

newest, buyer = s.orders_db.execute(
    "SELECT id, customer_id FROM orders ORDER BY id DESC LIMIT 1").fetchone()
s.customers_db.execute("UPDATE customers SET tier = 'gold' WHERE id = ?", (buyer,))
print(f"\ncustomer {buyer} becomes gold; their order {newest} is the newest")
print("  B) composition includes it: ", newest in s.compose_by_ids())
print("  C) read model includes it:  ", newest in s.read_model())
s.on_event("CustomerTierChanged", (buyer, "gold"))  # the event arrives later
print("  C) after the event arrives: ", newest in s.read_model())

s.up["customers"] = False
print("\nCustomers service is down")
try:
    s.compose_by_ids()
except ConnectionError as err:
    print(f"  B) composition fails: {err}")
print(f"  C) read model still answers: {len(s.read_model())} orders")

Before you run it, predict: which approach moves the fewest rows, which one sees a tier change first, and which one still answers when Customers is down?

Terminal
python3 query_across.py
Expected output (seeded, so it matches exactly)
gold customers: 120 of 2,000; orders: 50,000
  A) compose, page by date    calls   4  rows moved    782
  B) compose, filter by ids   calls   2  rows moved    130
  C) read model from events   calls   1  rows moved     10
  same 10 orders in A, B and C: True

customer 1319 becomes gold; their order 50000 is the newest
  B) composition includes it:  True
  C) read model includes it:   False
  C) after the event arrives:  True

Customers service is down
  B) composition fails: Customers service unavailable
  C) read model still answers: 10 orders

All three return the same ten orders, at very different costs. Composition by paging (A) reads 200 orders at a time and asks Customers for the tiers of each page until ten gold orders turn up: 782 rows for a 10-row answer. With an id filter (B) it fetches the 120 gold ids, sends them to Orders and gets 10 rows back: 130 rows, plus 120 ids in the request. The read model (C) answers from one indexed table: 10 rows in one call.

Freshness runs the other way. When customer 1319 becomes gold, composition sees it at once because it asks the owner, while the read model stays stale until the CustomerTierChanged event arrives. And when Customers is down, composition fails, while the read model still answers, possibly with slightly old tiers.

Now change the share of gold customers. In a run with 1% gold (24 customers), A needed 16 calls and moved 3,114 rows, because gold orders were rare and it paged much further, while B moved only 34. The cost of composition depends on how selective the cross-service filter is, which the composer cannot know in advance. The model is simplified: real APIs add latency per call, payload limits on long id lists and pagination of their own, and a real read model is fed by a broker, so its lag is seconds or minutes, not one function call.

05. Choosing per query

Decide for each query, not once for the system:

  • API composition fits when few owners are involved, results are small, the answer must be current and the volume is low, such as an admin screen that checks one account. It costs a call per owner per request, it is only as available as all the owners together, and filters or sorts that span owners get expensive.
  • A read model fits when the volume is high, the query filters or sorts across owners, a lag of seconds is acceptable, and the screen must work while an owner is down, such as an order-history page. It costs another store to run, an event feed to keep healthy, lag to monitor, and a rebuild from events when its shape changes; event sourcing and CQRS goes further.
  • A local copy of a few fields fits when one service repeatedly needs a little of another's data, as fulfilment kept order_copy in lesson 3.

Events have to reach the read model reliably even when a service crashes between saving its data and publishing; that is the job of the outbox pattern or of change data capture. When should you use neither? If two services keep needing each other's data in every request, the boundary may be wrong, and merging them, as in lesson 3, can beat any query pattern.

06. Check your understanding

Practice check · 3 questions

Data ownership and queries

Reason about ownership and cross-service queries.

Q1. Orders owns orders, and Customers owns customer tiers and addresses. Which screen is hardest to serve well with API composition alone?
Q2. Payments and Orders keep their tables in separate schemas on one PostgreSQL server, with grants that stop each service reading the other. Which new requirement is the strongest reason to give Payments its own database server?
Q3. In query_across.py, suppose 40% of customers were gold instead of 5%, with everything else unchanged. Before you run it, which approach would move more rows than in the 5% run?
Practice only: not graded, not saved, not evidence.

07. Apply it

Extend the ownership table of your online grocery.

  1. For every table, confirm one owner and choose a separation level (private tables, schema or server), with a reason.
  2. Pick the screen that needs the most owners, such as my upcoming deliveries with items, substitutions and driver. Decide between API composition and a read model, stating the freshness it needs, its expected volume and what it should show when one owner is down.
  3. Name one business rule that spans two owners and say whether you move it inside one service or turn it into a workflow.

08. Review prompt

Without looking back: give four reasons why shared tables break service autonomy, including why a read-only user does not fix them. Compare the three separation levels by cost and isolation. From the experiment, explain why composition by paging and by id filter move different numbers of rows, why the read model was stale for a moment, and which approach survived the outage.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check