SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
  • Service Discovery
  • API Gateway Pattern
  • Backend for Frontend (BFF)
  • Sidecar Pattern
  • Circuit Breaker
  • Bulkhead
  • Strangler Fig
  • Service Mesh
  • Database per Service
  • Timeouts and Deadlines
  • API Composition
  • Anti-Corruption Layer
  • Ambassador Pattern
  • Idempotent Consumer and Inbox Pattern
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Architecture/Microservices Patterns

Database per Service

Each service owns its data and nobody else touches it, so services can change and scale on their own.

⏱ 13 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Database per service means each microservice has its own private data store. No other service reads or writes its tables directly. They can only ask the owner, through its API or its events.

  • Each team can change its schema, pick its own database type and scale it, without asking anyone.
  • The price: no joins and no simple transactions across services, and some data is copied and can be slightly behind.
  • The opposite is the shared database, where many services use the same tables. It looks easy but hides tight coupling.

02Concept: What is it?

In a microservices system we want each service to change and be released on its own. That is hard if two services read the same table. The moment Customers renames a column, Orders and Billing break. The database became a secret shared contract, and nobody wrote it down.

The fix is a rule: a service owns its data. The Orders service has an orders database. The Customers service has a customers database. If Orders needs a customer name, it must ask Customers (an API call), or listen to events from Customers and keep a small copy of what it needs.

Shared database and database per service
Shared database
πŸ›’Orders
πŸ‘€Customers
🧾Billing
↓same tables
πŸ—„οΈOne databasehidden coupling
Database per service
πŸ›’Orders
πŸ—„οΈOrders DB
πŸ‘€Customers
πŸ—„οΈCustomers DB
🧾Billing
πŸ—„οΈBilling DB
↔only through APIs and events
On the left, three services share tables. On the right, each service guards its own data and offers an API.
🧠Private data, public contract
The tables are private. The API and the events are the public contract. As long as the contract stays the same, the owner is free to change everything behind it.

03Real-Life Example

🍡The Shared Kitchen Fridge vs Each Cook's Own Pantry
In a shared house, everyone keeps food in one big fridge. One day a person reorganises the shelves, and now nobody can find their lunch. Another person eats something that was not theirs. Everyone must agree before any change. Now give each cook a private pantry with a locked door. If you need an egg from another cook, you ask them at the window. Or, if you always need eggs, the cook leaves a few eggs in your pantry every morning (a copy). Each cook can now rearrange their pantry freely. The cost is that asking takes a moment, and the eggs in your pantry may be a day old.
Kitchen
Database per service
One shared fridge
A shared database
A private pantry
A service's own database
Locked door
Nobody else reads the tables directly
Asking at the window
An API call to the owner
Eggs left every morning
A local copy kept up to date by events
Eggs may be a day old
Eventual consistency
Reorganising your pantry
Changing the schema without asking anyone
Two ways to get data you do not own
πŸ›’Orders
→↓ask (API)
πŸ‘€Customersowner of the data
←or: events keep a copy
πŸ—„οΈOrders keeps a small copy

04Why Do We Need It?

πŸ”“Loose coupling
Change a table without a meeting. The API is the only thing others depend on.
πŸš€Release alone
A schema change in one service does not force other teams to release on the same day.
πŸ“Scale on its own
Give a busy service a bigger database without paying for the others.
🧩Best tool for each job
Search in a search engine, orders in SQL, sessions in a key-value store (polyglot persistence).
🧯Fault isolation
One overloaded database slows only its own service, not the whole company.
πŸ”Clear ownership
One team is responsible for the data, its quality and its access rules.
If two services share tables, they are not really independent. Give every service its own data and a clear way to ask for it.

05Where Do We Use It?

🧱Microservices
It is the usual rule: each service owns its data. Without it, microservices keep the pain of a monolith.
πŸ›οΈShops
Catalog, orders, payments and shipping each keep their own store.
πŸš•Ride apps
Trips, drivers, payments and ratings are different services with different data needs.
🏦Banks
Accounts, cards and fraud checks are separated for safety and for clear ownership.
πŸ”„Breaking up a monolith
Splitting the code is half the job. Splitting the database is the harder, important half.
🧠Teams that own a domain
It matches Domain-Driven Design: one team, one area, one set of data.

06Types / Parts / How It Works

How separate is separate?

LevelWhat is separateGoodCareful
Private tablesSame database, but each service has its own tables and a rule not to touch othersCheap and simple to startOnly a rule. Someone will break it.
Schema per serviceSame server, separate schemas with separate loginsRules are enforced by permissionsShared server resources: a heavy service slows the others
Database per serviceSeparate database instance per serviceReal isolation and independent scalingMore databases to run, back up and pay for
Server per serviceA different server (or type of database) per serviceFull freedom and fault isolationHighest cost and most to operate

How to read data you do not own

WayHow it worksGood forWatch out
API callAsk the owning service each timeData that must be freshAdds a network call and depends on the other service being up
API compositionOne place calls several services and combines the answersPages and reports built from many servicesSlow if it makes many calls in a row. See API Composition.
Local copy from eventsThe owner publishes changes. You store only what you need.Reads that must be fast and survive the other service being downThe copy can lag. See Outbox Pattern and Change Data Capture.
CQRS read modelA separate store built from events, shaped for queriesComplex queries across servicesMore moving parts. See CQRS.
Analytics storeCopy everything into a warehouse for reportsCompany-wide reportsNot for live user requests. See ETL Pipelines.
Keeping a local copy with events
πŸ‘€Customerschanges a name
→↓event
πŸ“¬Message broker
→↓event
πŸ›’Ordersupdates its copy
The owner writes its change and an event together. Other services update their small copies when they see the event.
VisualizerShared database vs database per serviceRename a column in Customers under each setup and see what breaks. Then build the orders page with customer names: try one call per customer, one batched call, and a local copy.
How is the data stored?
What happens?
πŸ›’OrdersBROKEN: its query fails
πŸ‘€Customersrenames name to full_name
🧾BillingBROKEN: its query fails
↓all three read and write the same tables
πŸ—„οΈOne shared databasecustomers table changed
Services broken
2
Teams that must coordinate
3
Can release alone?
No
Customers renamed a column in the shared database. Orders and Billing read that column directly, so both break at once. Three teams must change and release together.

Illustrative numbers: a database query takes 5 ms and a call between services takes 20 ms. The page has 12 different customers for 20 orders.

07How to Use It / Steps / Implementation

Moving to a database per service

  1. 1
    Find who owns what
    For each table, decide which service is the owner. If you cannot decide, the services are probably cut in the wrong place.
  2. 2
    Forbid direct access
    Give each service its own login that can only reach its own data. A rule that is not enforced will be broken.
  3. 3
    Expose an API for what others need
    Offer clear, small read endpoints. Do not offer your table layout.
  4. 4
    Replace joins
    Use API composition for pages, a local copy for fast reads, or a read model for complex queries.
  5. 5
    Replace cross-service transactions
    Use a Saga: a chain of local transactions, with undo steps if one fails. See SAGA Pattern.
  6. 6
    Publish events safely
    Write the change and its event in one local transaction, then send it. See Outbox Pattern.
  7. 7
    Move step by step
    First stop new code from touching other tables. Then split the data. Then remove the old shared access.
⚠️Do not copy everything
A local copy should hold only the fields you really need (for example a customer id and a display name). Copying a whole table brings back the coupling you wanted to remove.
πŸ’‘Start with the boundary, not the database
Splitting the database is easy when the service boundary is right and painful when it is wrong. If two services always change together, they may be one service.

08Key Terms to Know

TermMeaning in easy words
Database per serviceA pattern where each microservice owns a private data store
Shared databaseSeveral services using the same tables, which hides tight coupling
Polyglot persistenceUsing different kinds of database for different services, each the best fit
Service APIThe only public way to read or change another service's data
Data ownershipOne service is the single source of truth for a piece of data
API compositionBuilding one answer by calling several services and combining the results
Local copy (replica)A small, read-only copy of another service's data, kept up to date by events
Eventual consistencyCopies agree after a short delay, not at the same instant
SagaA chain of local transactions with undo steps, used instead of one big transaction
SchemaThe layout of a database: tables, columns and their types
CouplingHow much one part must change when another part changes

09Pros, Cons and Trade-offs

βœ… Pros
  • Services can change their schema freely
  • Independent release and scaling
  • Choose the best database for each job
  • Failures stay inside one service
  • Clear data ownership
⚠️ Cons
  • No joins across services
  • No simple ACID transaction across services
  • Data is copied and can lag
  • Reports across services are harder
  • More databases to operate and pay for

Trade-offs

ChoiceWe gainWe lose
Shared databaseEasy joins, simple transactions, fast startHidden coupling, forced coordinated releases, shared failures
Database per serviceIndependence and fault isolationCross-service queries and transactions get harder
Read through an APIAlways fresh dataExtra network calls, and a dependency on the owner being up
Keep a local copyFast reads that survive an outageLag, storage, and an event pipeline to maintain
Many database typesThe right tool for each serviceMore skills to learn and more systems to run
Saga instead of a transactionWorks across servicesTemporary inconsistency and undo logic to write

10Common Problems and Mistakes

Common mistakes

  1. A shared database in disguise. Separate services, but one database that all of them read. It is a distributed monolith.
  2. Letting a team "just read" another table. One shortcut becomes a hidden dependency that breaks later.
  3. Making one API call per row. A page with 50 orders makes 50 calls. Batch the calls or keep a copy.
  4. Copying too much. A big local copy means two sources of truth, and they will disagree.
  5. Pretending there is a transaction. Writing to two services in a row, with no undo, leaves half-finished data after a crash.
  6. Splitting too small. Tiny services that must always be changed together give the cost without the benefit.
  7. Forgetting reports. The business still needs company-wide numbers. Plan an analytics store.

Things to watch

🐒Chatty calls
Many small calls in a row make pages slow. Batch them or cache.
πŸͺžStale copies
A copy can be behind. Decide which screens can accept that.
πŸ’₯Half-done work
A crash between two services leaves a mess. Use a saga and idempotent steps.
🧾Cost and care
Each database needs backups, patches, monitoring and a person who knows it.

11Real-World Examples

πŸ›’Large online shops
Catalog, cart, orders and payments are usually separate services with their own data stores.
πŸ“ΊStreaming companies
Microservices each own their data, often in different kinds of database chosen for the job.
🚚Logistics
Orders, routes and tracking each keep their own records, and share through events.
🏒Monolith migrations
Many teams first split the code, and then spend most of the effort splitting the database.
πŸ“¬Event-driven setups
Services publish events, and others keep the small copies they need.
πŸ“ŠAnalytics
Changes from all services flow into a warehouse for company-wide reports.
πŸ“Note
There is no single right level of separation. Many teams start with schemas per service and move to separate databases for the services that need it.
Mini case: show my orders with the customer name
πŸ‘€Customers serviceowns names
→↓NameChanged
πŸ“¬Broker
→↓update
πŸ›’Orders serviceorders + name copy
→↓one local query
πŸ“±Orders page
Owner Events Reader
Orders keeps only the display name it needs and updates it from events.

12Related Topics to Read Next

Microservices→

The style that makes data ownership matter.

API Composition→

The simple way to answer a question that spans services.

SAGA Pattern→

Replaces a cross-service transaction with undo steps.

CQRS→

A separate read model built from other services' data.

Outbox Pattern→

Publishes events safely together with the local change.

Change Data Capture (CDC)β†’

Streams database changes to other services or a warehouse.

Event-Driven Architecture→

How services share changes without sharing tables.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”Rule: each service owns its data. Others use its API or events.
  • βœ”Why: change schemas, release and scale without asking other teams.
  • βœ”Anti-pattern: a shared database. It hides coupling.
  • βœ”Joins: use API composition, a small local copy, or a read model.
  • βœ”Transactions: use a saga with undo steps, not one big transaction.
  • βœ”Events: publish with an outbox so the change and the event never get out of step.
  • βœ”Cost: copied data can lag, and there are more databases to run.
  • βœ”One line: β€œPrivate tables, public contract: share data through APIs and events, never through the database.”
← Previous
Service Mesh
Next β†’
Timeouts and Deadlines