AlgoViz

Database per service

medium 28 min

Each service owns its data, and only that service may touch it.

Video lesson · Chapter 1 of 5

Three departments scribble in the same ledger

0:00 / 3:56

Every band its own trunk, in 80 seconds

1:20Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Database per service means that each service has private data that only it reads and writes directly. Other services reach that data through its published API, or through events that it publishes.

The pattern is about ownership, not about hardware. Private tables with their own login, a schema of their own, or a separate server all satisfy it, as long as nobody else can get in.

Why it exists

When several services use the same tables, the tables become a contract nobody wrote down. Renaming a column needs every team, and a slow report of one service blocks the payments of another.

Private data removes that coupling. A service can change its schema, release on its own, scale its store, and choose a kind of database that fits.

The price is that the database no longer does three things for you across services: joins, foreign keys and transactions. The rest of this topic is about replacing them.

A short history

  1. 1998

    Amazon's Distributed Computing Manifesto, dated 24 May, names applications that access the database directly as a problem and proposes services.

  2. 2002

    PostgreSQL 7.3, released on 27 November, adds schemas, which let one server keep objects in separate namespaces.

  3. 2011

    On 16 November Martin Fowler writes Polyglot Persistence: using different kinds of data store for different needs.

  4. 2014

    On 25 March Lewis and Fowler list decentralised data management among the characteristics of microservices.

Words to know

Owner
The one service that may write a piece of data. It is the source of truth.
Reference ID
The id of something another service owns, stored without a foreign key.
API composition
Answering a question by calling several services and joining the results in memory.
Local copy
Data of another service, kept from its events, read-only and a little behind.
Snapshot
A value copied on purpose because it must not change later, such as the price at the time of order.
Polyglot persistence
Different kinds of database for different jobs.
Shared database
Several services on the same tables: the anti-pattern.

How it works

Step through the idea, or press Play.

Step 1 of 3

Own. One service writes each fact

Understand it

Start here

Every band keeps its own trunk

Three bands practise in the same hall. At first they share one instrument trunk. Then each band gets its own. Who can open what, and how do the others find out what is inside?

Trunks in the hall
MaxLeeNoorOne shared trunk

A family with one shared notebook has the same trouble: someone always erases a page. Own notebooks, and sticky notes for news, work better.

The pattern

Private data

Three services, three private databases

An API gateway calls an order service, a user service and a stock service. Each service sits in its own box together with its own database.
No arrow goes from one service into the database of another.

How private?

FormSeparationCost
Private tablesOwn login, rights only on own tablesLowest
Own schemaClear names and rights, same serverLow
Own serverAlso own CPU, memory, version and backupHighest
All three are database per service. On a shared server one service can still slow the others down, so begin with schemas and move the busy ones out.
SQL
CREATE ROLE order_service LOGIN;CREATE ROLE user_service LOGIN;CREATE SCHEMA orders AUTHORIZATION order_service;CREATE SCHEMA users AUTHORIZATION user_service;-- As order_service:-- SELECT * FROM users.profile;-- ERROR: permission denied for schema users
Make the rule a fact: rights, not good intentions. In PostgreSQL a role cannot use objects in a schema it does not own unless it was granted.

What follows from it

  • Private access

    Only the owner touches its data.

  • APIs

    Others ask the owner.

  • Events

    The owner announces changes.

  • Freedom

    Each service may use another kind of database.

  • Independent release

    The schema changes without coordination.

  • Later consistency

    Copies agree after a short time.

The opposite

Why not one shared database?

The shared database

An order service, a user service and a stock service all read and write one shared database that holds all tables.
Simple to query, and everybody depends on everybody's tables.
ProblemWhat happensExample
Tight couplingAll services depend on the schemaA change to users breaks four services
Release lockSchema and services must move togetherA migration needs a common evening
Shared loadOne service takes the capacity of allA report slows down checkout
One technologyAll must use the same databaseSearch in tables not made for search
The second service may call a cache or a search engine anyway. The point is that the system of record is shared, and so is its schema.

What you gain with your own

  • Loose coupling: change the order schema without stock
  • Independent release: orders five times a day, users once a week
  • The right tool: a relational store for orders, documents for a catalogue
  • Scale: read replicas only for orders

What you lose

  • Joins across services
  • Foreign keys across services
  • One transaction across services
  • One place for reports

Lost: foreign keys

Reference IDs

SQL
-- one databaseCREATE TABLE orders (  id       UUID PRIMARY KEY,  user_id  UUID NOT NULL REFERENCES users(id));-- separate databasesCREATE TABLE orders (  id          UUID PRIMARY KEY,  user_id     UUID NOT NULL,       -- owned by the user service  price_cents BIGINT NOT NULL      -- snapshot at order time);
Before: the database checks the user. After: only the id is kept. Keep the same type.

Nobody checks the id for you. The user may be deleted a second after you asked. So treat a missing user as a normal case: show a placeholder, and let the owner announce deletions so that you can clean up. Asking the user service before each order gives a better message, not a guarantee.

Lost: joins

Three ways to combine data

API composition

The gateway often composes. Ask for all products in one call: one call per line is the N+1 problem over a network.

What a composed page waits for

10+max⁡(20,30)=40 ms10+20+12×30=390 ms10 + \max(20, 30) = 40 \text{ ms} \qquad 10 + 20 + 12 \times 30 = 390 \text{ ms}
Assumed: order 10 ms, user 20 ms, products 30 ms. Left: parallel, one batch call. Right: one after the other with a call for each of 12 lines.

A local copy from events

The reader depends on nobody at read time, and shows a name that may be some seconds old.
WayGood forPrice
API compositionOne order with detailsWaits for all, fails with any, poor for filters over many rows
Local copyNames and prices in listsSlightly old, a consumer to run, storage
Read model (CQRS)Search and filters over several servicesA separate view to build: see CQRS
WarehouseReports and analyticsMinutes or hours behind: see OLAP

Which way?

Python
ORDERS = {7: {"user": 3, "lines": [(5, 2), (9, 1)]}}USERS = {3: "Ana"}PRODUCTS = {5: "Lamp"}                     # product 9 was deleteddef get_users(ids):    return {i: USERS[i] for i in ids if i in USERS}def get_products(ids):    return {i: PRODUCTS[i] for i in ids if i in PRODUCTS}def order_page(order_id):    order = ORDERS[order_id]    users = get_users([order["user"]])    products = get_products([p for p, _ in order["lines"]])   # one call    return {        "buyer": users.get(order["user"], "unknown user"),        "lines": [(products.get(p, "no longer sold"), n) for p, n in order["lines"]],    }print(order_page(7))
A composer that survives a missing part
Edit and run it in your browser

Lost: transactions

Work that spans services

Inside one service you still have full ACID. Across services, use a saga: local transactions with a compensation for each completed step.

An order as a saga

StepServiceUndo
1. Create orderOrderCancel the order
2. Reserve stockStockRelease the stock
3. Take paymentPaymentRefund
4. Confirm orderOrderNone: the end
How sagas are driven, and what can go wrong, is in the saga topic.

Read more in the saga pattern. Two-phase commit across services is possible in some databases, but it holds locks while everybody waits, needs a coordinator that must not be lost, and needs support on every side. Brokers and HTTP services usually do not take part.

Order and stock, one event

Publishing right after the commit, without the outbox, can lose the event. See multi-system synchronization.

The short time in between

TimeEventState
T0Order savedOrder database has it
T1Event publishedBroker has it
T2Stock reservedStock database has it
T3Confirmation readAll agree
Often milliseconds to seconds, but hours if a consumer is down. Measure the delay, and show pending in the interface.

How many orders are in between?

864,00086,400=10/speak 3×10=30/s30×2 s=60 orders\frac{864{,}000}{86{,}400} = 10/\text{s} \qquad \text{peak } 3 \times 10 = 30/\text{s} \qquad 30 \times 2 \text{ s} = 60 \text{ orders}
Assumed 864,000 orders a day and a delay of 2 seconds. Sixty orders are pending at peak, so two buyers can want the last lamp: the stock service decides who gets it.

The safe write is one conditional statement: UPDATE stock SET reserved = reserved + 2 WHERE id = 5 AND quantity - reserved >= 2. If no row changes, there was not enough. Reading first and writing later lets two requests both believe they won.

Freedom

Choosing a store for each service

ServiceA store that fitsWhy
Orders, usersPostgreSQLTransactions and rich queries
Product catalogueMongoDBProducts with different fields
Sessions, cacheRedisFast access by key
SearchElasticsearchFull-text search
Event and time dataCassandraMany writes, spread by key
RecommendationsNeo4jRelations as a graph
Freedom is not a duty. Each extra database needs backups, upgrades, monitoring and someone who knows it at night. One good default for most services is wise.

Four problems

Challenges and answers

ChallengeProblemAnswers
Queries across servicesNo joinComposition, read models, event sourcing
ConsistencyNo common transactionSagas, later consistency, compensation
DuplicationThe same fact in several placesAccept it with one owner, follow events
ReportsData of many servicesWarehouse, change streams, composition

Event sourcing stores the changes themselves and builds views from them. It suits a service whose history is its business, such as accounts. It is a bigger step than publishing events.

How to

From shared to own

Seven steps

  1. 1

    Define boundaries

    Bounded contexts: which words belong together?

  2. 2

    Assign owners

    Each table gets exactly one owner, for example orders belong to the order service.

  3. 3

    Choose the store

    Same server with a schema first, another one when there is a reason.

  4. 4

    Define contracts

    APIs for what others may ask.

  5. 5

    Publish events

    Through an outbox, so that none is lost.

  6. 6

    Replace joins

    Composition, local copies or a read model.

  7. 7

    Replace transactions

    Sagas with compensations.

Cutting one table loose

Revoking before moving is the test: if nothing breaks for a week, the table is really private.

Habits

Do and avoid

Do

  • Store only ids and deliberate copies of others' data
  • Publish an event when your data changes
  • Compose through APIs
  • Accept a short delay where the business allows it
  • Design the undo for each step

Avoid

  • Foreign keys into another service
  • Reading another service's tables
  • Two-phase commit as the default
  • Copying everything everywhere
  • Not asking which data must be exact

In an interview

  1. Interviewer

    The order list must show the customer's name and allow filtering by city. Users are another service.

  2. You

    Composition works for one page of orders, but not for filtering: I would have to fetch all orders first. I keep name and city in a read model fed by order and user events, keyed by order. It is a second behind, and the detail page still asks the owner.

  3. Interviewer

    A customer asks to be forgotten.

  4. You

    The user service deletes and publishes UserDeleted. Every holder of a copy removes it and confirms, and I keep a list of who holds which personal data. Copies make this harder, so I copy as little as I can.

Summary

The whole topic in one minute.

Each service owns its data and nobody else touches it. Sharing happens through APIs when the answer must be fresh, and through events and local copies when it may be slightly old.

You give up joins, foreign keys and transactions across services. Use API composition for small questions, a read model for wide lists, a saga for work over several services, and a warehouse for reports. If two services need one transaction all the time, they may be one service.

  • One owner for each fact. Nobody else touches its tables.
  • Ownership matters, not the number of servers.
  • Joins become composition, copies or read models.
  • Transactions become sagas. Foreign keys become reference ids.
  • If two services always need one transaction, join them.

Sources