Database per service
medium 28 minEach service owns its data, and only that service may touch it.
See it run
Who owns which data, how others get it, and what replaces joins, foreign keys and transactions.
Operations
The shared database
Three services on the same tables. It is simple until somebody changes something.
Step 1 of 4
Everything in one place
All services read and write one database. Joins and transactions just work.
Step 1: Everything in one place
-- user teamALTER TABLE users RENAME COLUMN name TO full_name;-- order service: ERROR: column "name" does not exist- Delay
- None
- Price
- Everybody is coupled
- Fine for
- one service, one team
A table that others read is a public contract, whether you wrote it down or not.
In the real world
The same database per service doing real jobs. Pick one and step through it.
Two orders want the same item at the same time.
Step 1 of 4
Two pending orders
Both were accepted as pending, because the order service does not know the stock.
Step 1: Two pending orders
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Just one direct read
criticalIt starts with one report. After a year nobody can change the table.
Wrongreport_db.query("SELECT * FROM user_service.users")Rightwarehouse.query("SELECT * FROM users_daily")# fed by the owner's published changesRead, then write
criticalTwo requests read the same free stock and both reserve it.
Wrongfree = product.quantity - product.reservedif free >= n: product.reserved += n save(product)Rightrows = execute("""UPDATE stock SET reserved = reserved + :n WHERE id = :id AND quantity - reserved >= :n""")ok = rows == 1One call per row
majorA list of 100 orders becomes 100 network calls.
Wrongfor o in orders: o.user = users.get(o.user_id)Rightfound = users.get_many({o.user_id for o in orders})for o in orders: o.user = found.get(o.user_id, UNKNOWN)Publishing without an outbox
majorIf the process stops after the commit, the other databases never hear of the change.
Wrongdb.commit()broker.publish(event)Rightwith db.transaction(): save(order); save_outbox(event)# relay publishes, consumers ignore repeats
Interview tips
How to explain it
- One owner per fact, nobody else inside.
- APIs when it must be fresh, events when it may lag.
- Ownership, not the number of servers.
Memory trick: OWNED
- Own your data. Write changes out as events.
- No direct access. Eventual consistency.
- Different databases are fine.
Replace what you lost
- Join: composition, copy, read model.
- Foreign key: reference id.
- Transaction: saga.
Stop and think when
- Two services always need one transaction.
- Every request calls five owners.
- Each service has another kind of database.