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

πŸ“š Interview question

What does data ownership mean in a modular or service-based .NET architecture? Explain database per service (or schema per module), why shared writes are dangerous, how you meet reporting and cross-cutting query needs, and how you duplicate and synchronise data safely.

Data ownership: one owner per piece of data, database per service vs schema per module, no shared writes, reporting via read models or a warehouse, and synchronising copies with events and the outbox.

Senior Theory Advanced architecture data-ownership database-per-service eventual-consistency outbox reporting

🎯 Key points

  • Each piece of data has exactly one owner that enforces its invariants; others ask or subscribe
  • Database per service for microservices; inside a modular monolith, schema per module with separate DbContexts is how you enforce ownership and stop accidental coupling
  • Shared writes break invariants, hide accountability and traceability (who changed what), and couple schema changes
  • Other services get data via the owner's API, events with the needed fields, or a local read-only copy
  • Synchronise copies with the transactional outbox and idempotent, version-aware consumers
  • Reporting goes to a separate store (Fabric/warehouse, read replica, CDC pipeline), not by joining live service databases
  • Database per service multiplies backups, HA, scaling and cost; schema per module keeps one database to operate
  • Privacy: knowing the owner and copies of personal data makes APP access/correction requests and NDB assessments tractable

⏱ 30-second 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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"Data ownership is the rule that every piece of data has exactly one owner that writes it and protects its invariants. In a microservices system that's a database per service, or at least a schema per service with no other service granted access. Inside a modular monolith I do the same thing with a schema per module and a separate DbContext, so the Orders module can't accidentally join into the Customers tables. Other parts of the system get data in one of three ways: call the owner's API, subscribe to its events, or keep a local read-only copy built from those events.

For example, at [company] we had [four] services all writing to a shared Customer table in one Azure SQL database. Billing changed the email format, Marketing had a trigger that assumed the old one, and a release broke [newsletter sign-ups] for [two] days. Nobody knew who owned the rules. I proposed making the Customer service the sole writer, exposing a CustomerChanged event with the fields others actually needed, and giving Billing and Marketing their own projections. We moved writes over one consumer at a time, and schema changes in Customer went from needing [four] team sign-offs to one.

The mistake I see is treating 'database per service' as the goal and then rebuilding joins with chatty synchronous calls, or the opposite, keeping one shared database 'for reporting' and letting writes leak back in. My senior line is: share data by contract, never by table, and decide up front which copies are allowed to be stale and by how much."


Ways to share data

Approach How Consistency When it fits Cost
Query the owner's API HTTP/gRPC call Fresh Low volume, need current data Runtime coupling, latency
Event-carried state transfer Owner publishes events with needed fields; consumer stores a copy Eventual High read volume, tolerates lag Storage, sync logic, versioning
Shared database, separate schemas, read-only views Owner exposes a view; others read only Fresh Transitional step inside a monolith Schema coupling; discipline needed
Shared tables, shared writes Everyone writes β€” Never as a target state Broken invariants, coordinated releases

Schema per module vs database per service

Schema per module Database per service
Isolation Logical (permissions, separate DbContexts) Physical
Cross-module transaction Technically possible (avoid it) Not possible without sagas
Ops cost One database One per service; backups, scaling, cost
Fits Modular monolith Independently deployed services

Reporting

Need Approach
Operational dashboards on one service That service's read model or a read replica
Cross-domain analytics CDC or events into Microsoft Fabric / a warehouse
Near-real-time cross-domain view Dedicated projection service fed by events

Production example

Making Customer the single writer and moving [three] consumers to event-fed projections removed the coordinated schema releases, cut customer-related incidents from [six] a quarter to [one], and kept projection lag under [5 seconds] at p99.

πŸ” What the interviewer is checking

Checks whether the candidate understands single-writer ownership, how to share data without coupling, and the consistency, reporting and privacy consequences.

Green flags

  • States the single-writer rule and how it is enforced (schemas, permissions, tests)
  • Chooses between API, events and local copies based on freshness and volume
  • Uses an outbox and version-aware idempotent consumers
  • Moves reporting to a separate analytical store

Red flags

  • Accepts shared writes "just for now" with no plan
  • Thinks database per service means no data duplication at all
  • Ignores out-of-order or duplicate events

πŸ“š Learn in depth

1. Why one owner

An invariant ("a customer's email is unique and verified before marketing can use it") can only be enforced where the data is written. If three services write the same rows, each needs a copy of the rule, and they drift.

Shared writes (bad)                     Single owner (good)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  CustomerChanged  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Billing β”‚ β”‚Marketingβ”‚ β”‚ Support β”‚          β”‚ Customer β”‚ ────────────────► β”‚ Billing β”‚ (copy)
β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜          β”‚ service  β”‚ ────────────────► β”‚Marketingβ”‚ (copy)
     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜               β”‚  writes  β”‚ ◄── API calls ───── β”‚ Support β”‚
                 β–Ό                           β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜                   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
          dbo.Customer                        β–Ό
                                       customer DB

2. Enforcing ownership in .NET

  • Separate DbContext per module with HasDefaultSchema("customers"), internal entity types, and migrations per context.
  • Database permissions: each module or service connects with its own managed identity, granted only its schema (GRANT ... ON SCHEMA::customers).
  • Architecture tests: no module references another module's DbContext or entity types.

3. Synchronising copies safely

The dual-write problem: writing to your database and publishing to a broker are two operations; either can fail. The transactional outbox writes the event to an outbox table in the same transaction as the change; a relay publishes it later.

Consumers must be:

  • Idempotent: record processed message ids (inbox) or use upserts.
  • Version-aware: carry a version or sequence number per entity and ignore older updates, because brokers can deliver out of order.
  • Tolerant of missing data: a consumer may see OrderPlaced before it has the CustomerCreated copy; design a fallback (call the owner, park and retry).

4. How much to copy

Copy only what the consumer needs, ideally in its own language (Billing stores BillingContact, not the whole Customer). Copying everything recreates coupling to the owner's schema and spreads personal data, which increases your Privacy Act and NDB surface.

5. Reporting

Operational databases are tuned for the owner's writes and reads. Cross-domain reporting joins should happen in an analytical store:

service DBs ──CDC / events──► landing zone ──► warehouse / Fabric lakehouse ──► Power BI

Azure SQL change tracking/CDC or event streams feed it. Reporting latency of minutes is usually acceptable, and the services stay free to change their schemas as long as the published feed is versioned.

6. Personal data and ownership

Under the APPs, people can request access to and correction of their personal information, and an eligible data breach must be assessed and notified. If you know which service owns each personal field and which copies exist, these become tractable. A map of owners and copies is a privacy control, not just an architecture diagram.

Try it yourself

  1. List the tables in a shared database and mark which module writes each; find tables with more than one writer.
  2. Create two DbContexts with different default schemas and an architecture test forbidding cross-references.
  3. Implement an outbox table and a background relay with BackgroundService.
  4. Write a consumer that ignores events with a lower version than the stored copy, and test it with out-of-order messages.
  5. Grant a managed identity access to a single schema in Azure SQL and confirm cross-schema reads fail.

πŸ’» Code

A consumer keeping a minimal, version-aware local copy of data owned by another service.

namespace Billing.Infrastructure;

using Microsoft.EntityFrameworkCore;

// Published by the Customer service (the owner). Carries only what consumers need plus a version.
public sealed record CustomerChanged(Guid CustomerId, string BillingEmail, string LegalName, long Version);

// Billing's own, minimal copy in its own schema and language.
public sealed class BillingContact
{
    public Guid CustomerId { get; init; }
    public string Email { get; set; } = "";
    public string LegalName { get; set; } = "";
    public long SourceVersion { get; set; }
}

public sealed class BillingDbContext(DbContextOptions<BillingDbContext> options) : DbContext(options)
{
    public DbSet<BillingContact> Contacts => Set<BillingContact>();
    protected override void OnModelCreating(ModelBuilder b)
    {
        b.HasDefaultSchema("billing");
        b.Entity<BillingContact>().HasKey(c => c.CustomerId);
    }
}

public sealed class CustomerChangedHandler(BillingDbContext db)
{
    public async Task HandleAsync(CustomerChanged e, CancellationToken ct)
    {
        var contact = await db.Contacts.FindAsync([e.CustomerId], ct);
        if (contact is null)
        {
            db.Contacts.Add(new BillingContact
            {
                CustomerId = e.CustomerId, Email = e.BillingEmail, LegalName = e.LegalName, SourceVersion = e.Version
            });
        }
        else if (e.Version > contact.SourceVersion) // ignore stale or duplicate deliveries
        {
            contact.Email = e.BillingEmail;
            contact.LegalName = e.LegalName;
            contact.SourceVersion = e.Version;
        }
        await db.SaveChangesAsync(ct);
    }
}
-- Each service's managed identity can only touch its own schema.
CREATE USER [billing-api] FROM EXTERNAL PROVIDER;
GRANT SELECT, INSERT, UPDATE, DELETE ON SCHEMA::billing TO [billing-api];

⚠ Common mistakes

  • Mistake: Several services writing the same tables. Why it is wrong: Invariants are enforced in several places and drift, nobody is accountable for the data, it's hard to trace which service made a bad change, and every schema change needs coordinated releases. Instead: Choose one owner; others call it or subscribe to its events.
  • Mistake: Database per service, then rebuilding joins with chatty synchronous calls. Why it is wrong: Latency adds up and one slow service takes others down. Instead: Keep local read models fed by events for high-volume reads.
  • Mistake: Publishing events after SaveChanges without an outbox. Why it is wrong: A crash between the two loses the event and copies silently drift. Instead: Use a transactional outbox and an idempotent relay.
  • Mistake: Consumers that apply events blindly. Why it is wrong: Duplicates and out-of-order delivery overwrite newer data with older. Instead: Track a version per entity and ignore stale updates; record processed message ids.
  • Mistake: Copying the owner's whole entity. Why it is wrong: It couples you to their schema and spreads personal data. Instead: Copy only the fields you need, in your own model.
  • Mistake: Running cross-domain reports directly against live service databases. Why it is wrong: It couples reporting to internal schemas and adds load to production. Instead: Feed an analytical store via CDC or events.
  • Mistake: Forgetting deletion and correction of personal data in copies. Why it is wrong: APP requests and retention rules aren't met, and breaches are larger. Instead: Publish deletion/correction events and keep a map of where personal data is copied.

πŸ› Senior insight: trade-offs

Ownership is mostly a governance decision with a technical enforcement. I make the owner explicit in the architecture docs (a data ownership table per context), enforce it with per-identity database permissions and architecture tests, and keep traceability by having the owner record who changed what (audit columns or temporal tables) and by propagating trace ids into events.

I also define a staleness budget for every copy ("Billing's contact copy may lag up to 1 minute"). If the budget is seconds-to-minutes, an event-fed copy is right. A synchronous call to the owner is justified when the decision must use the current value and a wrong answer is costly, for example checking available credit before approving a payment, and the call volume is modest. If many hot-path operations in one service need another service's data to be exactly current, that usually means the two belong in the same boundary.

Operationally, database per service means separate backups, HA configuration, scaling and cost for each database; an Azure SQL elastic pool can soften the cost. In a modular monolith I start with schema per module in one database: cheap, clear ownership, and later extraction becomes a data move rather than a redesign.

Option When it fits Cost When not to
Schema per module, one DB Modular monolith, one deployable Low Modules deployed independently
Database per service Independent services and teams Higher ops and consistency cost Small team, one deployable
Event-fed local copy High read volume, lag acceptable Sync and versioning logic Strong consistency required
Synchronous API lookup Low volume, must be fresh Runtime coupling Hot paths, long call chains

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions publishing events with the fields consumers need Why: Checks they can version and own integration event contracts
    How to answer

    An integration event is a public API owned by the publisher. Within a version I only make backward-compatible changes: add optional (nullable or defaulted) fields. I never add a required field mid-version (messages already in queues won't have it), and never rename, remove or retype. Consumers are tolerant readers: they ignore unknown fields and default missing optional ones. A breaking change becomes a new event type (orders.order-placed.v2), published alongside v1 until consumers move, then deprecated with a date.

    I wrap events in a CloudEvents envelope (id, source, type, time, dataschema). Each publisher ships its own contracts package or JSON Schema; one shared events library for every service forces lockstep upgrades.

    The trade-off: discipline and some duplication in exchange for independent deployments.

  2. When: Candidate mentions out-of-order or duplicate events Why: Checks they can diagnose and fix copies that drift in production
    How to answer

    I'd first confirm the mechanics: Azure Service Bus delivers at least once and only orders messages within a session, so after a release that raised consumer concurrency or scaled out, events for the same order can be processed out of order and redelivered. Traces with event ids, aggregate versions and delivery counts prove it.

    The fixes: every event carries the aggregate version and the consumer applies it only if newer (or I use sessions keyed by order id); an inbox with a unique key dedups by message id in the same transaction; increments like loyalty credits use a natural idempotency key (order id plus reason). Unknown event versions dead-letter. Then I rebuild the corrupted state from the source of truth.

    The trade-off: sessions give ordering but limit parallelism per key; version checks keep parallelism but require versioned events.

  3. When: Candidate mentions schema per module Why: Checks how a modular monolith enforces data boundaries
    How to answer

    A modular monolith is one deployable split into modules aligned to business capabilities β€” Orders, Billing, Catalogue β€” each with hard boundaries.

    • Each module owns its data: its own schema and DbContext, no cross-module joins or foreign keys.
    • Modules talk only through a public contract (an interface and DTOs) or integration events; everything else is internal.
    • Boundaries are enforced: separate projects, internal types, architecture tests, even per-schema database permissions.

    You get microservice-style boundaries with monolith-style operations: one pipeline, in-process calls, easy refactoring. The trade-off: one runtime, one release and one scaling unit, and it only works if the boundaries are enforced β€” otherwise it decays into a big ball of mud.

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

Four services writing one Customer table
Situation
A [retail platform] had [four] services (Customer, Billing, Marketing, Support) all writing a shared `dbo.Customer` table in one Azure SQL database, serving about [150k] customers.
Signals
A Billing release changed email normalisation and broke a Marketing trigger; [newsletter sign-ups] failed for [two] days. Every Customer schema change needed sign-off from [four] teams, and there were [six] customer-data incidents a quarter.
Investigation
I used Query Store and the SQL audit log to find which identities wrote which columns, mapped readers and writers in a C4 container diagram, and reviewed the incident history to quantify the cost.
Resolution
Immediate: reverted the trigger and froze schema changes. Long-term: an ADR making the Customer service the sole writer, a `CustomerChanged` event published through an outbox, Billing and Marketing moved to minimal local copies one at a time, and write permissions on `dbo.Customer` revoked from the other identities.
Prevention
Per-schema permissions for each managed identity; an architecture test forbidding references to another service's DbContext; a data ownership table in the architecture docs; a dashboard for projection lag with an alert above [1 minute].

How to tell it (STAR)

**S:** At [company] four services wrote the same Customer table, and a Billing change broke Marketing sign-ups for [two] days. **T:** As the senior engineer on Customer, I had to stop these cross-team breakages. **A:** I showed who wrote what using Query Store and audit logs, wrote an ADR making Customer the only writer, and introduced a `CustomerChanged` event through an outbox. I moved Billing and Marketing to small local copies one at a time, then revoked their write permissions. **R:** Customer schema changes went from [four] team sign-offs to one, customer-data incidents dropped from [six] to [one] a quarter, and projection lag stayed under [5 seconds] at p99.

↩ Usually asked after

More in Senior-Level Architecture

Last updated 23 Nov 2026.

🌐 Sangam's Webring

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