📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

Two of your services read and write the same SQL Server tables. Explain what goes wrong with this shared database setup compared with database per service, and walk me through how you would move to database per service step by step without downtime.

The shared database anti-pattern versus database per service: schema coupling, hidden invariants, locking and scaling problems, and a step-by-step, zero-downtime migration to separate data ownership.

Mid-Level Theory Intermediate data-migration database-per-service distributed-systems microservices shared-database sql-server

🎯 Key points

  • Shared tables couple services at the schema: a column change needs coordinated releases
  • Invariants are enforced in two codebases, so they drift and data goes wrong
  • Contention: one service's long transaction or missing index blocks the other (locks, tempdb, DTU/vCore limits)
  • No independent scaling, failover or technology choice; one noisy neighbour hurts all
  • Database per service: each service writes only its own tables; data it needs from others comes through their API, events or a local read model
  • Cross-service consistency becomes eventual: outbox for reliable publishing, sagas with compensations instead of one transaction, idempotent consumers, reconciliation jobs
  • Middle steps: schema per service with separate logins and permissions in one server or elastic pool
  • Migration: pick an owner, make others read-only, replace reads with API/events, run old and new side by side and compare, switch, revoke access (expand and contract)

⏱ 30-second answer

Sharing tables couples services through the schema: renaming a column needs both teams to release together, business rules are enforced in two codebases and drift apart, and one service's long transaction or bad query blocks the other. You also lose independent scaling and failover. With database per service, each service is the only writer of its data and others use its API, events or a local read model. To migrate: choose an owner, make the other service read-only with its own login, replace its reads with an API or events, then move and separate the data with expand-and-contract steps. The trade-off: you give up cross-service joins and atomic transactions in exchange for independent change.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"When two services share tables, they're still one system at the most rigid layer: the schema. If the Orders team wants to split CustomerName into two columns, Billing's queries break, so both teams have to release together. Business rules get enforced twice, once in each codebase, and they drift: one service allows an order status the other doesn't know about. And they share capacity: a reporting query from one service holding locks on Orders makes the other time out, and on Azure SQL they compete for the same DTUs or vCores.

Database per service means each service is the only writer of its data, and others get it through an API, through events they store in their own read model, or through a reporting copy. It doesn't have to mean a separate server on day one: separate schemas with separate logins in the same server or elastic pool already give you ownership and enforce it with permissions.

To move there safely I go in small steps. First, pick the owner of each table. Second, give the other service its own login with read-only access, so no new writes sneak in. Third, replace its writes with calls to the owner's API, and its reads with events into a local read model or an API. Fourth, once nothing else touches the tables, move them into the owner's schema or database. Each step is deployable on its own and reversible.

The mistake I see is splitting the code into services and leaving the database shared, which gives you a distributed monolith: network calls plus lockstep releases. Data ownership, not code ownership, is what makes services independent."


What goes wrong with a shared database

Problem How it shows up
Schema coupling Coordinated releases; fear of changing columns
Duplicated invariants Rules in two codebases drift; invalid states appear
Contention Blocking chains and deadlocks across services; one service's missing index slows both
Shared capacity One noisy service exhausts DTUs/vCores or connection limits
No independent operations Can't scale, fail over, patch or restore one service alone
Unclear ownership Nobody knows who may change a table or who to page
Security Every service has wide access; harder least privilege (relevant for APP 11 security of personal information)

Options from coupled to independent

Option Isolation Cost
Shared tables None Lowest, until it hurts
Schema per service, same database, separate logins Ownership enforced by permissions Low
Database per service, same server or elastic pool Separate backups, restore and scaling knobs Moderate
Database per service, separate servers or engines Full Highest

Replacing what the shared tables gave you

You used to… Now you…
JOIN across services' tables Call an API, or keep a local read model fed by events
Update two services' rows in one transaction Saga or outbox with eventual consistency
Run reports across everything Replicate into a reporting store (CDC, events, Fabric or Synapse)

Production example

A [billing] service and an [orders] service shared dbo.Orders. A nightly billing job held locks for ~6 minutes and caused ~3% of checkout requests to time out each night. Moving Orders to its own schema with Billing reading an OrderCompleted-fed read model removed the cross-service blocking, and schema changes to Orders no longer needed a joint release.

πŸ” What the interviewer is checking

Checks that the candidate understands why shared databases couple services and can plan a safe, incremental way out.

Green flags

  • Names schema coupling, duplicated invariants and contention
  • Knows schema per service with separate logins is a valid first step
  • Gives an incremental, reversible migration plan
  • Replaces joins with read models and reporting copies

Red flags

  • "Just give each service its own server" with no migration plan
  • Replaces every join with a synchronous call
  • Ignores eventual consistency and idempotency

πŸ“š Learn in depth

1. Why sharing is so tempting

One database gives you joins, transactions, a single backup and referential integrity for free. Those are real benefits. The cost is that every consumer of a table depends on its exact shape and behaviour, and that dependency is invisible: no compiler or contract test tells you Billing reads Orders.Status.

2. The coupling, drawn

 Orders service        Billing service
      |  INSERT/UPDATE        |  SELECT ... JOIN, UPDATE Status='Billed'
      v                       v
   +-------------- dbo.Orders --------------+
   | Id | CustomerId | Status | Total | ... |
   +----------------------------------------+
        ^ schema, locks, indexes, rules: shared by both

Three kinds of coupling hide here:

  1. Structural: column names, types and meaning.
  2. Behavioural: valid status transitions, which only one service should own.
  3. Operational: locks, log growth, tempdb, CPU and connection limits.

3. What database per service means

 Orders service --writes--> [orders schema/db]
       | publishes OrderCompleted (via outbox)
       v
 Billing service --writes--> [billing schema/db]  (keeps its own copy: OrderId, Total, CustomerId)

Rules:

  • One writer per table.
  • Other services never connect to it; enforce with separate logins or managed identities and GRANT only on their own schema.
  • Data others need is published as events or exposed through an API.

4. Step-by-step migration (expand and contract)

  1. Inventory: query sys.dm_exec_sessions and Query Store by login or Application Name in the connection string to see which service touches which table.
  2. Assign owners and record them in an ADR.
  3. Separate identities: each service gets its own login or managed identity, so access is visible and controllable.
  4. Freeze foreign writes: grant the non-owner SELECT only. Move its writes to the owner's API.
  5. Replace reads: the owner publishes events through an outbox; the consumer builds a local read model. Run both in parallel and compare.
  6. Revoke access to the owner's tables.
  7. Move tables into the owner's schema or database when convenient.

Each step is backwards compatible and can be rolled back, which is the zero-downtime part.

5. What you lose and how to cope

  • Joins: replaced by read models; accept that they are eventually consistent (usually seconds).
  • Foreign keys across services: replaced by validation at the boundary and reconciliation jobs.
  • Atomic multi-service updates: replaced by sagas and the outbox.
  • Reporting: a separate analytical store, fed by CDC or events.

Try it yourself

  1. Add Application Name=orders-api to each service's connection string and query sys.dm_exec_sessions to see who connects.
  2. Create two schemas and two users; prove that the billing user can't update orders.Orders.
  3. Build an outbox in the Orders service and a consumer in Billing that maintains a read model; compare results with the old join.
  4. Reproduce cross-service blocking with a long transaction in one session and observe sys.dm_exec_requests.blocking_session_id.

πŸ’» Code

Enforcing ownership in SQL Server with schemas and least-privilege users, then the consumer's local read model.

-- Each service gets its own schema and its own user (contained user or managed identity on Azure SQL).
CREATE SCHEMA orders AUTHORIZATION dbo;
CREATE SCHEMA billing AUTHORIZATION dbo;

CREATE USER [orders-api] FROM EXTERNAL PROVIDER;   -- managed identity
CREATE USER [billing-api] FROM EXTERNAL PROVIDER;

GRANT SELECT, INSERT, UPDATE, DELETE ON SCHEMA::orders  TO [orders-api];
GRANT SELECT, INSERT, UPDATE, DELETE ON SCHEMA::billing TO [billing-api];

-- Transitional step: billing may still read orders, but can no longer write it.
GRANT SELECT ON orders.Orders TO [billing-api];
-- Final step, once billing uses its read model:
-- REVOKE SELECT ON orders.Orders FROM [billing-api];
namespace Billing.ReadModel;

// Billing's own copy of what it needs from Orders. Fed by OrderCompleted events.
public sealed class BilledOrder
{
    public Guid OrderId { get; init; }
    public Guid CustomerId { get; init; }
    public decimal Total { get; init; }
    public DateTimeOffset CompletedAt { get; init; }
}

public sealed record OrderCompleted(Guid OrderId, Guid CustomerId, decimal Total, DateTimeOffset CompletedAt);

public sealed class OrderCompletedHandler(BillingDbContext db)
{
    public async Task HandleAsync(OrderCompleted e, CancellationToken ct)
    {
        // At-least-once delivery: make the handler idempotent on OrderId.
        if (await db.BilledOrders.AnyAsync(o => o.OrderId == e.OrderId, ct)) return;

        db.BilledOrders.Add(new BilledOrder
        {
            OrderId = e.OrderId, CustomerId = e.CustomerId, Total = e.Total, CompletedAt = e.CompletedAt
        });
        await db.SaveChangesAsync(ct); // a unique index on OrderId backs up the check under concurrency
    }
}

⚠ Common mistakes

  • Mistake: Splitting code into services but keeping one shared schema. Why it is wrong: you get network costs and still need lockstep releases. Instead: split data ownership along with the code.
  • Mistake: All services connecting with the same SQL login. Why it is wrong: you can't see or limit who touches what. Instead: one login or managed identity per service, least privilege.
  • Mistake: Thinking database per service requires a server per service. Why it is wrong: it scares teams off and wastes money. Instead: start with schema per service and separate users, in one server or an elastic pool.
  • Mistake: Replacing joins with synchronous calls on every request. Why it is wrong: chatty, slow and couples availability. Instead: local read models fed by events for frequent reads.
  • Mistake: Big-bang data migration over a weekend. Why it is wrong: risky and hard to roll back. Instead: expand and contract, one reversible step at a time.
  • Mistake: Querying other services' databases for reporting. Why it is wrong: recreates the coupling through the back door. Instead: a reporting copy via CDC or events.
  • Mistake: Forgetting idempotency in the read-model consumer. Why it is wrong: at-least-once delivery duplicates rows. Instead: dedupe on the business key with a unique index.

πŸ› Senior insight: trade-offs

Database per service is about ownership, not infrastructure. The cheapest first step, separate schemas and identities in the same database, gets most of the benefit: visible dependencies, enforced permissions and a single team allowed to change each table. Separate databases come later when scaling, restore or compliance needs differ.

Option When it fits Cost When not to
Shared tables One team, one deployable Coupling grows with every consumer Several teams or services
Schema per service + separate logins First step, small estate Discipline; shared capacity Very different load or compliance needs
Database per service (same pool) Independent restore/scaling More databases to manage Lots of tiny services with no ops support
Separate engines Genuinely different data shapes Polyglot operations "Because we can"

Measure progress by the number of cross-service logins on each table and the number of coordinated releases per quarter.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions reporting or cross-service queries Why: Checks how they meet reporting and query needs once data is split.
    How to answer

    Data ownership means each piece of data has one owner, a module or service, that is the only one allowed to write it and enforce its invariants. Everyone else either asks the owner (API), subscribes to its events, or keeps a read-only local copy.

    In microservices that usually means database per service; in a modular monolith it means schema per module with its own DbContext, and no cross-module joins.

    Shared writes are the thing to avoid: two services updating the same table means nobody owns the rules and every schema change is a coordinated release. For reporting, I ship data to a separate analytical store instead of joining live databases.

    The trade-off is duplication and eventual consistency: copies lag the owner, so you design for staleness and synchronise with an outbox.

  2. When: Candidate mentions expand and contract Why: Checks they can run schema changes while old and new versions run together.
    How to answer

    Never use RenameColumn while old and new app versions overlap: the old version would query a column that no longer exists. Use expand and contract over several releases. 1. Expand: add the new column (nullable). 2. Dual write: release an app version that writes both columns in the same SaveChanges (same transaction), or add a trigger that copies writes made by the old version, and still reads the old column. 3. Backfill existing rows in small batches (UPDATE TOP (5000) ... WHERE New IS NULL) to avoid long locks and log growth, then verify with a count of mismatches. 4. Switch reads to the new column; keep writing both so a rollback to the previous version still works. 5. Contract: once no running version uses the old column, stop writing it and drop it in a later migration. Each step is backward compatible with the version before it.

  3. When: Candidate talks about extracting a service from a monolith Why: Checks how they choose and extract the first module safely.
    How to answer

    I keep a modular monolith until a module has a measured reason to become its own deployable: it needs to scale independently, it has a different release cadence or owning team, it needs fault or security isolation, or it needs a different runtime. "Microservices are modern" isn't a reason.

    The first candidate should have few inbound dependencies, a clean contract and its own schema already. Extraction is incremental: make the module talk only through its contract, stop cross-module joins and transactions, move its data, deploy it as a service, and switch traffic behind a feature flag with a rollback path.

    The trade-off: every extracted module turns method calls into network calls, so you gain autonomy and isolation but pay with latency, partial failures and eventual consistency.

πŸ›  Real-world problems: how you handle them

Nightly billing job blocked checkout through a shared Orders table
Situation
An [orders] API and a [billing] service shared `dbo.Orders` in one Azure SQL database. Checkout handled [~150] orders a minute at night for [overseas customers].
Signals
About 3% of checkout requests timed out between [01:00 and 01:10] each night; SQL timeout exceptions in Application Insights; DTU spikes to 100%; on-call alerts for checkout error rate.
Investigation
Queried `sys.dm_exec_requests` and the blocked process report during the window; the head blocker was the billing job's `UPDATE ... SET Status = 'Billed'` holding locks for ~6 minutes; Query Store showed the job's plan scanning `dbo.Orders`.
Resolution
Immediate: batched the billing update into chunks of 1,000 rows and moved the job outside peak. Real fix: separate schemas and managed identities, Billing made read-only on Orders, an `OrderCompleted` event via outbox feeding a Billing read model, then revoked Billing's access to Orders.
Prevention
Per-service identities with `Application Name` in connection strings; an alert on blocking longer than 30 seconds; an ADR recording table owners; a check in code review that no service references another's schema.

How to tell it (STAR)

**S:** At [company], our [orders] and [billing] services shared the same Orders table, and checkout failed for a few percent of customers every night. **T:** I had to stop the timeouts and make sure the two services couldn't hurt each other again. **A:** Using the blocked process report and Query Store, I found the billing job holding locks for six minutes on a scan. I batched the update as a quick fix, then led the split: separate schemas and managed identities, billing made read-only, and an OrderCompleted event via an outbox feeding billing's own read model. **R:** Night-time checkout timeouts went from [~3%] to [zero], and the Orders team shipped [two] schema changes the next quarter without a joint release.

↩ Usually asked after

More in Microservices

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me