Database per service
medium 28 minEach service owns its data, and only that service may touch it.
Video lesson · Chapter 1 of 5
Three departments scribble in the same ledger
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
1998
Amazon's Distributed Computing Manifesto, dated 24 May, names applications that access the database directly as a problem and proposes services.
2002
PostgreSQL 7.3, released on 27 November, adds schemas, which let one server keep objects in separate namespaces.
2011
On 16 November Martin Fowler writes Polyglot Persistence: using different kinds of data store for different needs.
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.
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?
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
How private?
| Form | Separation | Cost |
|---|---|---|
| Private tables | Own login, rights only on own tables | Lowest |
| Own schema | Clear names and rights, same server | Low |
| Own server | Also own CPU, memory, version and backup | Highest |
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 usersWhat 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
| Problem | What happens | Example |
|---|---|---|
| Tight coupling | All services depend on the schema | A change to users breaks four services |
| Release lock | Schema and services must move together | A migration needs a common evening |
| Shared load | One service takes the capacity of all | A report slows down checkout |
| One technology | All must use the same database | Search in tables not made for search |
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
-- 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);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
What a composed page waits for
A local copy from events
| Way | Good for | Price |
|---|---|---|
| API composition | One order with details | Waits for all, fails with any, poor for filters over many rows |
| Local copy | Names and prices in lists | Slightly old, a consumer to run, storage |
| Read model (CQRS) | Search and filters over several services | A separate view to build: see CQRS |
| Warehouse | Reports and analytics | Minutes or hours behind: see OLAP |
Which way?
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))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
| Step | Service | Undo |
|---|---|---|
| 1. Create order | Order | Cancel the order |
| 2. Reserve stock | Stock | Release the stock |
| 3. Take payment | Payment | Refund |
| 4. Confirm order | Order | None: the end |
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
The short time in between
| Time | Event | State |
|---|---|---|
| T0 | Order saved | Order database has it |
| T1 | Event published | Broker has it |
| T2 | Stock reserved | Stock database has it |
| T3 | Confirmation read | All agree |
How many orders are in between?
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
| Service | A store that fits | Why |
|---|---|---|
| Orders, users | PostgreSQL | Transactions and rich queries |
| Product catalogue | MongoDB | Products with different fields |
| Sessions, cache | Redis | Fast access by key |
| Search | Elasticsearch | Full-text search |
| Event and time data | Cassandra | Many writes, spread by key |
| Recommendations | Neo4j | Relations as a graph |
Four problems
Challenges and answers
| Challenge | Problem | Answers |
|---|---|---|
| Queries across services | No join | Composition, read models, event sourcing |
| Consistency | No common transaction | Sagas, later consistency, compensation |
| Duplication | The same fact in several places | Accept it with one owner, follow events |
| Reports | Data of many services | Warehouse, 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
Define boundaries
Bounded contexts: which words belong together?
- 2
Assign owners
Each table gets exactly one owner, for example orders belong to the order service.
- 3
Choose the store
Same server with a schema first, another one when there is a reason.
- 4
Define contracts
APIs for what others may ask.
- 5
Publish events
Through an outbox, so that none is lost.
- 6
Replace joins
Composition, local copies or a read model.
- 7
Replace transactions
Sagas with compensations.
Cutting one table loose
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
Interviewer
The order list must show the customer's name and allow filtering by city. Users are another service.
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.
Interviewer
A customer asks to be forgotten.
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.