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

📚 Interview question

You're setting the architecture for a new .NET 10 service. How do you decide which enterprise patterns (repository, unit of work, CQRS, mediator, domain services, outbox, sagas, resilience patterns) to use? Contrast a CRUD-heavy admin service with a complex domain such as insurance claims, explain how you avoid pattern overuse, and how you record and revisit those decisions.

Staff-level pattern selection: starting from forces (domain complexity, invariants, consistency, integration, scale, team) rather than a template, a minimal baseline every service gets (DbContext, DTOs, validation, HttpClient resilience, observability), a CRUD admin service (vertical slices, DbContext in handlers, no repositories/CQRS/mediator) vs an insurance-claims domain (aggregates, repositories, domain services, light CQRS, outbox/inbox, saga for long-running claims), triggers for adding patterns, cost of each pattern, ADRs with reversal conditions, architecture fitness functions (NetArchTest), and periodic review.

Staff / Architect Architecture Expert adr architecture cqrs design-patterns domain-driven-design over-engineering

🎯 Key points

  • Choose patterns from forces (domain complexity, invariants, consistency needs, integrations, scale, team experience) and weigh each option's maintainability, performance, operational load and learning cost, not from a reference template
  • Every service gets a cheap baseline: DbContext as the unit of work, DTOs at boundaries, input validation, typed HttpClients with resilience, outbox for any integration event, observability
  • CRUD admin service: vertical slices, DbContext directly in handlers, projections for reads; no repositories, CQRS levels, mediator or domain services
  • Complex domain (claims): aggregates with invariants, repositories per aggregate root, domain services for cross-aggregate rules, level-1 CQRS, outbox/inbox, and a saga for long-running claim workflows
  • Each pattern has a cost (files, indirection, onboarding, licences such as MediatR v13+/MassTransit v9); add it when a named trigger appears, not in advance
  • Different parts of one system can use different styles (per bounded context or even per feature)
  • Record decisions as ADRs with context, consequences and reversal conditions; enforce with architecture tests (NetArchTest/ArchUnitNET) and review them periodically
  • Measure the outcome: lead time per change, files touched per feature, escaped defects, incident causes, onboarding time

⏱ 30-second answer

I choose patterns from the forces, not from a template: domain complexity and invariants, consistency needs, integrations, scale and the team.

Every service gets a cheap baseline: DbContext as the unit of work, DTOs at boundaries, validation, typed HttpClients with resilience, an outbox for integration events, and observability.

  • CRUD admin service: vertical slices with DbContext in handlers and projections for reads. No repositories, CQRS levels, mediator or domain services.
  • Insurance claims: aggregates and repositories, domain services for cross-aggregate rules, light CQRS, outbox/inbox, and a saga for long-running claim workflows.

Each extra pattern needs a named trigger. I record decisions as ADRs with reversal conditions and enforce them with architecture tests. The trade-off is fitting the design to today's problem against preparing for change that may never come.

🗣 Full answer (senior)

How I would answer this in an interview

"I don't start from a pattern list; I start from the forces. How complex are the rules, and do they have invariants that must hold? What consistency does the business need, and where can it accept eventual consistency? What does the service integrate with, and what happens when those integrations fail? What's the load and the read/write ratio? And who's on the team: a pattern nobody understands becomes a liability. Then I separate a baseline that every service gets, because it's cheap and prevents known failures, from patterns that have to be earned.

The baseline is small: EF Core with DbContext as the unit of work, DTOs at every boundary, input validation, typed HttpClients with the standard resilience handler tuned per dependency, an outbox for any integration event so we never dual-write, structured logging and OpenTelemetry. For a CRUD-heavy admin service, say managing product reference data, that's nearly all. I'd organise by vertical slice, use DbContext directly in handlers with projections for reads, and skip repositories, mediators, CQRS levels and domain services, because there are no invariants for them to protect. For an insurance-claims service it's different. A claim has real invariants: you can't approve above the policy limit or pay before assessment, and the lifecycle runs for weeks with assessors, fraud checks and payments. There I'd model Claim as an aggregate with a repository, put the excess-and-limit calculation across policy and claim in a domain service, separate command and query handlers on one database, add inboxes on consumers, and run the long workflow as an orchestrated saga with timeouts. Even inside claims, the reference-data screens stay CRUD. For example, at [company] [a team had applied full DDD, CQRS and event sourcing to a reference-data service], and [a one-field change took [n] files and [n] days]. I [led a simplification to vertical slices, with an ADR], and [lead time dropped to [n] hours].

To avoid overuse, every non-baseline pattern needs a named trigger: 'repositories when an aggregate has invariants', 'a separate read store when listing p95 can't meet the target from the primary', 'a mediator only if we need cross-cutting pipeline behaviour across many handlers', and I check licences, since MediatR and MassTransit v9 are now commercial. I write each decision as an ADR with the conditions that would reverse it, enforce structural rules with NetArchTest, and revisit the ADRs every quarter or after a major incident. The goal is the simplest design that protects what actually matters, with a written record of what would make us change it."


Forces to patterns

Force Pattern it justifies Trigger
Invariants across an object graph Aggregates + repository Rules that must hold on every change
Rules spanning aggregates Domain service Logic with no single owner
Read and write shapes diverge CQRS level 1, then 2/3 Slow reads, aggregate loaded just to display
Integration events Outbox (+ inbox on consumers) Any event another service depends on
Multi-service workflow Saga Steps owned by different services with compensation
Unreliable dependencies Timeout, retry, breaker, bulkhead Any external call
Cross-cutting behaviour across many handlers Pipeline/decorators (mediator optional) Same concern repeated in 10+ handlers

Two services compared

CRUD admin service Insurance claims
Domain model Entities as data Aggregates with invariants
Data access DbContext in handlers Repositories for aggregates; projections for reads
Business rules Validation only Entities + domain services
CQRS No (or trivially) Level 1 handlers, read models if needed
Messaging Outbox if events are published Outbox + inbox, orchestrated saga
Resilience Standard handler Standard handler + tuned breakers/bulkheads + fallbacks
Mediator No Optional; direct handler injection is fine

Production example

Simplifying an over-engineered reference-data service (MediatR, generic repositories, CQRS with a separate read database, AutoMapper profiles) to vertical slices with DbContext cut a typical field change from about 11 files to 3 and lead time from roughly 3 days to half a day, removed two licensed dependencies, and halved build time. The claims service kept its aggregates and saga, and its escaped-defect rate stayed below one per month.

🔍 What the interviewer is checking

Checks staff-level judgement: deriving patterns from forces, contrasting simple and complex contexts, avoiding overuse, and making decisions explicit, enforceable and revisitable.

Green flags

  • Starts from forces and a minimal baseline.
  • Gives concrete, contrasting designs for CRUD and complex domains.
  • Names triggers and costs (including licences) for each pattern.
  • Uses ADRs with reversal conditions and architecture tests.
  • Measures whether the design fits.

Red flags

  • One template for every service.
  • Patterns justified by "best practice" or future flexibility.
  • No way to record or enforce decisions.
  • Can't say when they'd remove a pattern.

📚 Learn in depth

1. Forces before patterns

Patterns are solutions to recurring problems in a context. Applying one without its problem adds cost with no benefit. A useful framing:

          Forces                         Decisions                   Fitness checks
  domain complexity, invariants  -->  aggregates? repositories?  -->  architecture tests
  consistency, integrations      -->  outbox/inbox? saga?        -->  reconciliation, metrics
  read/write shape, scale        -->  CQRS level?                -->  p95, DB load
  dependency reliability         -->  resilience pipeline        -->  chaos tests
  team, licences, operations     -->  libraries vs hand-rolled   -->  lead time, onboarding
                 \________________ recorded in ADRs with reversal conditions ________/

2. The baseline

Things so cheap and so often needed that every service gets them: DbContext as unit of work, DTOs, validation, typed clients with resilience, outbox for integration events, health checks, OpenTelemetry. They prevent known failure modes (over-posting, dual writes, cascades) for little code.

3. Earned patterns and their costs

Pattern Cost
Repositories Interfaces + implementations per aggregate; risk of leaky IQueryable
Domain services More types; needs DDD literacy
CQRS level 2/3 Projections, eventual consistency, replay, monitoring
Mediator Indirection, navigation cost; MediatR now RPL-1.5/commercial
Sagas State machines, timeouts, compensations; MassTransit v9/NServiceBus licences
Event sourcing Event versioning, projections, tooling; rarely justified

Patterns also cost onboarding time and cognitive load, which rarely show up in design discussions.

4. Per bounded context, not per system

DDD's bounded contexts let one system have different designs: claims assessment rich and event-driven, reference data CRUD, reporting a read model. The mistake is a uniform template imposed everywhere.

5. Evolution and triggers

Write triggers into the ADR: "introduce repositories for Claim when invariants span more than the root", "move listing to a read model when p95 exceeds 300 ms at 500 rps". This makes adding a pattern a planned response to evidence, and removing one equally legitimate.

6. ADRs and fitness functions

An ADR (Nygard's format) records context, decision, status and consequences; add reversal conditions. Fitness functions (Ford, Parsons and Kua, Building Evolutionary Architectures) make decisions executable: architecture tests that fail the build when the domain references EF Core, or when a handler references another slice. Review ADRs quarterly and after incidents.

7. Measuring whether the architecture fits

  • Lead time and files touched per typical change.
  • Escaped defects by cause (invariant violations suggest a model too weak; ceremony complaints suggest one too heavy).
  • Incident causes (dual writes, cascades).
  • Onboarding time to first meaningful PR.

Try it yourself

  1. List the forces for a service you know and map each to a pattern or "not needed".
  2. Write an ADR for one decision, including two reversal conditions.
  3. Add a NetArchTest rule for a structural decision and make it fail on purpose.
  4. Count the files touched by the last five features in a service; compare with what a vertical-slice design would need.
  5. Pick one pattern in your codebase and write down its trigger; if you can't, consider removing it.

💻 Code

Two project layouts, an architecture fitness test, and an ADR with reversal conditions.

# CRUD admin service: vertical slices, DbContext in handlers
ReferenceData.Api/
  Features/
    Products/
      CreateProduct.cs        # request DTO + validator + endpoint + handler using DbContext
      ListProducts.cs         # AsNoTracking projection to ProductListItem
      UpdateProduct.cs
  Infrastructure/
    ReferenceDataDbContext.cs
    Outbox/                   # only because ProductChanged events are published
  Program.cs

# Insurance claims: domain model where it matters
Claims.Domain/                # no EF Core, no HTTP
  Claims/Claim.cs             # aggregate: Lodge, Assess, Approve (invariants), raises events
  Claims/IClaimRepository.cs
  Policies/PolicyCoverageService.cs   # domain service: excess and limit across policy + claim
Claims.Application/
  Commands/ApproveClaimHandler.cs     # load, authorise, call domain, save
  Queries/ClaimSummaryQuery.cs        # projection, no aggregate
Claims.Infrastructure/
  EfClaimRepository.cs, ClaimsDbContext.cs, Outbox/, Inbox/
  Sagas/ClaimSettlementSaga.cs        # assessment -> fraud check -> payment, with timeouts
Claims.Api/
namespace Claims.ArchitectureTests;

using NetArchTest.Rules;

// Fitness functions: the ADR's structural decisions fail the build when broken
public class ArchitectureTests
{
    private static readonly System.Reflection.Assembly Domain = typeof(Claims.Domain.Claims.Claim).Assembly;
    private static readonly System.Reflection.Assembly Application = typeof(Claims.Application.Commands.ApproveClaimHandler).Assembly;

    [Fact]
    public void Domain_does_not_depend_on_infrastructure()
    {
        var result = Types.InAssembly(Domain)
            .ShouldNot().HaveDependencyOnAny("Microsoft.EntityFrameworkCore", "Microsoft.AspNetCore", "Azure.Messaging.ServiceBus")
            .GetResult();

        Assert.True(result.IsSuccessful, string.Join(", ", result.FailingTypeNames ?? []));
    }

    [Fact]
    public void Query_handlers_do_not_use_repositories()
    {
        var result = Types.InAssembly(Application)
            .That().ResideInNamespace("Claims.Application.Queries")
            .ShouldNot().HaveDependencyOn("Claims.Domain.Claims.IClaimRepository")
            .GetResult();

        Assert.True(result.IsSuccessful, string.Join(", ", result.FailingTypeNames ?? []));
    }
}
# ADR-007: Repositories only for aggregates with invariants

**Status:** Accepted (2026-11)

## Context
Claims has aggregates with invariants (approval limits, assessment before payment). Reference-data screens are CRUD.
A generic repository in a previous service caused partial writes and leaky IQueryable usage.

## Decision
- `Claim` and `Policy` get aggregate repositories; command handlers use them and commit once.
- Queries and CRUD features use `ClaimsDbContext` directly with projections.
- No mediator library; handlers are injected directly (MediatR licence and indirection not justified).

## Consequences
- Two styles in one codebase, documented in the README.
- Architecture tests enforce: Domain has no EF Core reference; queries don't use repositories.

## Reversal conditions
- If more than three aggregates need repositories with the same shape, revisit a shared base.
- If cross-cutting behaviour is copied into more than 10 handlers, consider pipeline decorators.
- Review: quarterly, or after any incident involving claims data integrity.

⚠ Common mistakes

  • Mistake: Starting a new service from a "clean architecture" template with every pattern pre-installed. Why it is wrong: It adds repositories, mediators and CQRS layers before there's a problem for them to solve. Instead: Start from the forces and a minimal baseline; add patterns on named triggers.
  • Mistake: One architectural style for the whole system. Why it is wrong: CRUD areas get heavy ceremony and complex areas may get too little structure. Instead: Decide per bounded context or feature area.
  • Mistake: Skipping the baseline to "keep it simple". Why it is wrong: Dual writes, over-posting and cascading failures are cheap to prevent and expensive to fix. Instead: Always use DTOs, an outbox for integration events and resilient typed clients.
  • Mistake: Adopting libraries without checking licences. Why it is wrong: MediatR, AutoMapper and MassTransit v9 moved to commercial licensing, creating cost or compliance surprises. Instead: Check licences and include them in the ADR.
  • Mistake: Decisions that live only in people's heads. Why it is wrong: New team members undo or overextend them. Instead: ADRs with consequences and reversal conditions.
  • Mistake: ADRs with no enforcement. Why it is wrong: Structure erodes one PR at a time. Instead: Architecture tests (NetArchTest/ArchUnitNET) in CI.
  • Mistake: Never removing a pattern. Why it is wrong: Patterns that no longer earn their keep slow every change. Instead: Review ADRs periodically and simplify when triggers no longer hold.
  • Mistake: Justifying patterns by future flexibility ("we might swap the database"). Why it is wrong: The cost is paid now; the benefit rarely arrives. Instead: Design for today's known forces and keep the code easy to change.

🏛 Senior insight: trade-offs

At staff level the job is less about knowing patterns than about making their costs and triggers explicit, so teams can apply them consistently without me in the room. The baseline protects against failures we've all seen; everything else is a bet that should be written down with the evidence that would make us change it.

Option When it fits Cost When not to
Minimal baseline only CRUD services, prototypes that will live Few abstractions to grow into Rich domains with invariants
Baseline + DDD tactical patterns Complex domains (claims, payments, scheduling) Learning curve, more types Reference data, admin screens
Baseline + messaging patterns (outbox/inbox/saga) Multi-service workflows Operational load, licences Single-service workflows
Company-wide template with everything Rarely Ceremony everywhere Default choice
Per-context decisions + ADRs + fitness functions Most organisations Discipline, review time Never really wrong

I judge the architecture by lead time, files touched per change, escaped defects by cause, incident causes and onboarding time, and I review those numbers with the team when we revisit the ADRs.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate describes simplifying an over-engineered service Why: Checks detecting and reversing over-engineering without a rewrite
    How to answer

    Over-engineering is complexity that today's requirements do not justify. I detect it through symptoms with numbers behind them: a one-field change touching many files, interfaces with one implementation, configuration options nobody sets, patterns like CQRS or event sourcing without the problems they solve, and microservices that always deploy together. I reverse it incrementally rather than with a rewrite: inline single-use abstractions, merge layers that only pass data through, consolidate services that share a release cycle, and delete unused options, each step behind tests. I also address why it happened, because otherwise it grows back.

  2. When: Candidate says patterns must be earned by a trigger Why: Checks judgement about premature abstraction
    How to answer

    I do not abstract when there is no second variant, no boundary to protect and no testing need, because an abstraction costs indirection, a name, a contract and cognitive load. Typical examples are an IOrderService with one implementation used by one controller, a generic repository over EF Core, or a wrapper around HttpClient or ILogger<T>, which are already abstractions. I do abstract at architecture boundaries (ports for payment vendors, email, storage) and where tests need a seam for something slow or non-deterministic. If an abstraction has had one implementation and one caller for a long time and is not at a boundary, I inline it.

  3. When: Candidate says repositories only for aggregates with invariants Why: Checks the repository decision as a worked example of pattern selection
    How to answer

    I decide by what the abstraction protects, not by habit. DbContext is already a repository and unit of work, so a wrapper has to earn its place.

    • Testability alone isn't a reason. Mocking repositories tests the mocks, and the EF in-memory provider ignores SQL semantics. I test persistence against SQL Server in Testcontainers either way.
    • Write side: repositories per aggregate root pay off when aggregates have invariants and must be loaded whole.
    • Read side: project straight from DbContext with Select and AsNoTracking. Never return IQueryable from a repository.
    • EF Core 10 ExecuteUpdateAsync/ExecuteDeleteAsync bypass the change tracker and run at once, so they belong behind an intention-revealing method and need an explicit transaction to be atomic with SaveChanges.

    My answer flips for pure CRUD (skip repositories) or for Dapper, stored procedures or a second store (repositories hide them). The trade-off is domain protection against a layer that only renames EF Core.

  4. When: Candidate mentions level-1 CQRS for the claims service Why: Checks CQRS levels and when each is justified
    How to answer

    CQRS splits the model that changes state (commands) from the model that reads it (queries). It grows out of Meyer's CQS (a method either changes state or returns data), applied to whole models.

    • Write side: aggregates with invariants, loaded through repositories, committed by the unit of work.
    • Read side: flat DTOs shaped per screen, projected with Select/AsNoTracking or Dapper.

    There are levels. Separate handlers on one database is cheap and often enough. Denormalised read tables updated in the same transaction stay consistent. A separate read store fed by events scales reads but is eventually consistent, so the UI needs read-your-writes or "processing" states.

    CQRS doesn't need MediatR or event sourcing. It's overkill for CRUD where reads and writes have the same shape. The trade-off is optimised, simple models on each side against more moving parts and, at the top level, stale reads.

🛠 Real-world problems: how you handle them

Full DDD and CQRS on a reference-data service slowed every change
Situation
Product reference-data service at [company] (about [40] tables, [~20] requests a second, mostly CRUD from internal admin screens), built from a company template with MediatR, generic repositories, AutoMapper profiles, CQRS with a separate read database and domain events for every change.
Signals
Lead time for a one-field change averaged [~3 days] and touched [~11] files; read-model lag caused 'I saved it but it's not there' tickets; two licence reviews flagged MediatR and AutoMapper upgrades; new joiners took [~3 weeks] to make a first change.
Investigation
Mapped the last [20] changes and counted files and hours per change; reviewed incident and ticket history (stale reads, mapping bugs); listed each pattern with its original justification and checked whether its trigger existed: no invariants beyond validation, read/write ratio low, read database unnecessary at [20] rps.
Resolution
Wrote an ADR proposing vertical slices with `DbContext` in handlers and projections for reads, removing the separate read database, MediatR and AutoMapper (hand-written mapping), and keeping the outbox only for the `ProductChanged` event other services consume. Migrated feature by feature behind the same API contract over [six] sprints.
Prevention
ADR with reversal conditions (e.g. introduce aggregates if pricing rules arrive); NetArchTest rules for slice independence; quarterly architecture review of lead time and files touched; a lightweight service template with only the baseline, plus documented triggers for adding patterns.

How to tell it (STAR)

**S:** At [company], our reference-data service had a full DDD/CQRS template for what was essentially CRUD, and a one-field change took about [3 days] across [11] files. **T:** As the staff engineer for the area, I had to decide whether the patterns were earning their keep and lead the change if not. **A:** I measured the last [20] changes, checked each pattern against a real trigger, and wrote an ADR to move to vertical slices with `DbContext`, drop the read database, MediatR and AutoMapper, and keep only the outbox for the one event others consumed. We migrated slice by slice behind the same API. **R:** Lead time fell to about [half a day], files per change to [3], stale-read tickets disappeared, and onboarding dropped from [3 weeks] to [1].

↩ Usually asked after

More in Enterprise Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me