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.
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.
DbContext in handlers and projections for reads. No repositories, CQRS levels, mediator or domain services.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.
"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
DbContextas the unit of work, DTOs at every boundary, input validation, typedHttpClients 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, useDbContextdirectly 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 modelClaimas 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."
| 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 |
| 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 |
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.
Checks staff-level judgement: deriving patterns from forces, contrasting simple and complex contexts, avoiding overuse, and making decisions explicit, enforceable and revisitable.
Green flags
Red flags
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 ________/
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.
| 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.
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.
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.
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.
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.
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.
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.
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.
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.
DbContext with Select and AsNoTracking. Never return IQueryable from a repository.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.
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.
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.
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].
Last updated 18 Nov 2026.