Tutorials Microservices with .NET
Database Per Service Pattern — Complete Guide
Database Per Service Pattern — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of Microservices with .NET on Toolliyo Academy.
On this page
Microservices with .NET · Lesson 9 of 131
Database Per Service Pattern
Beginner → Intermediate → Advanced → Professional
Beginner · 1 — Foundations · ~6 min · Module 1: Foundations and Fundamentals
What is this?
Database per service means Order.Api talks only to OrderDb. Payment.Api talks only to PaymentDb. No shared tables between services.
Why should you care?
Shared databases create hidden coupling — change a column and two teams break. Separate databases let each team evolve schema on their schedule.
See it live — copy this example
Create a Web API project (dotnet new webapi), paste the code, then run dotnet run.
// Order.Api/appsettings.json
{
"ConnectionStrings": {
"OrderDb": "Server=localhost;Database=ShopNest_Orders;Trusted_Connection=True;"
}
}
// Program.cs
builder.Services.AddDbContext<OrderDbContext>(o =>
o.UseSqlServer(builder.Configuration.GetConnectionString("OrderDb")));
Run Example »
Edit the code and click Run — like W3Schools Try it Yourself.
What happened?
- OrderDbContext maps to ShopNest_Orders database.
- Payment has its own connection string in Payment.Api — never copy Order connection into Payment.
Try it yourself
- Install SQL Server Express or use LocalDB on Windows.
- Add EF Core packages to Order.Api.
- Create OrderDbContext with Orders table.
- Change a string or route in the example and save — watch Swagger or the RabbitMQ Management UI update.
- Break the code on purpose (remove a semicolon), read the error message, then fix it.
Remember
One service → one database (logical ownership). No cross-service foreign keys. Duplicate read data when needed — consistency via events later.
Real-world: Payment PCI scope
Card tokens live only in PaymentDb. OrderDb stores paymentId reference — not PAN numbers.
Outcome: Security audits draw a circle around PaymentDb only.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!