Architecture patterns: layered, DDD, CQRS, events
Architecture patterns answer a few recurring questions: where do business rules live, which code may depend on which, how do reads and writes relate, and how do parts of a system tell each other that something happened. This page covers the four patterns most .NET teams meet first. They are not competitors; a typical OrdersPortal service might be layered on the inside, use domain-driven design for its ordering rules, separate its read model with CQRS, and publish events for other services.
Each section has one runnable sample built around the same order-placing use case. They are C# file-based programs: save the code as a .cs file and run dotnet run file.cs with the .NET 10 SDK. All were run with .NET SDK 10.0.115. They use in-memory stores so the pattern is visible without a database.
Topics on this page
Section titled “Topics on this page”| Pattern | Solves | Main cost |
|---|---|---|
| Layered architecture | Separating UI, use cases, business rules and infrastructure. | Ceremony for very simple apps; rules drift into services. |
| Domain-driven design | Modeling complex business rules in code the business recognizes. | Learning curve; overkill for CRUD. |
| CQRS | Reads and writes with different shapes, loads or models. | Two models to maintain; eventual consistency if stores differ. |
| Event-driven architecture | Decoupling the thing that happened from everything that reacts to it. | Brokers, retries, duplicates, ordering and tracing. |
Layered architecture
Section titled “Layered architecture”Layered (n-tier) architecture splits an application into horizontal layers with one job each: presentation (controllers, endpoints, UI), application (one class per use case, orchestration, transactions), domain (entities and business rules) and infrastructure (databases, HTTP clients, queues, files). The classic rule is that each layer only calls the one below it.
The modern variant, known as clean, onion or hexagonal architecture, adds the dependency rule: source code dependencies point inward, toward the domain. The domain and application layers declare the interfaces they need (ports such as IOrderRepository), and infrastructure implements them (adapters). The database then becomes a detail you can swap or fake in tests, and business rules never reference Entity Framework or HttpClient. In .NET this usually means separate projects (OrdersPortal.Domain, .Application, .Infrastructure, .Api) so the compiler enforces the direction, with the API project wiring implementations in the DI container.
// Presentation: the only layer that knows about input and output formats.var repository = new InMemoryOrderRepository(); // Infrastructurevar catalog = new InMemoryProductCatalog(); // Infrastructurevar placeOrder = new PlaceOrderHandler(repository, catalog); // Application
var id = await placeOrder.HandleAsync(new PlaceOrder("dana@example.test", [new("KB-101", 2), new("CBL-USB-C", 3)]));Console.WriteLine($"Placed order {id}, total {(await repository.GetAsync(id))!.Total:0.00}");
try{ await placeOrder.HandleAsync(new PlaceOrder("dana@example.test", [new("KB-101", 0)]));}catch (ArgumentOutOfRangeException ex){ Console.WriteLine($"Rejected: {ex.ParamName} must be positive");}
// ---------- Domain: business rules, no dependencies ----------public sealed class Order(int id, string customerEmail){ private readonly List<OrderLine> _lines = []; public int Id { get; } = id; public string CustomerEmail { get; } = customerEmail; public IReadOnlyList<OrderLine> Lines => _lines; public decimal Total => _lines.Sum(l => l.UnitPrice * l.Quantity);
public void AddLine(string sku, decimal unitPrice, int quantity) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(quantity); _lines.Add(new OrderLine(sku, unitPrice, quantity)); }}public sealed record OrderLine(string Sku, decimal UnitPrice, int Quantity);
// Ports owned by the inner layers; implemented by Infrastructure.public interface IOrderRepository { Task<int> NextIdAsync(); Task SaveAsync(Order order); Task<Order?> GetAsync(int id); }public interface IProductCatalog { Task<decimal> PriceOfAsync(string sku); }
// ---------- Application: one class per use case ----------public sealed record PlaceOrder(string CustomerEmail, List<PlaceOrderLine> Lines);public sealed record PlaceOrderLine(string Sku, int Quantity);
public sealed class PlaceOrderHandler(IOrderRepository orders, IProductCatalog catalog){ public async Task<int> HandleAsync(PlaceOrder command) { var order = new Order(await orders.NextIdAsync(), command.CustomerEmail); foreach (var line in command.Lines) order.AddLine(line.Sku, await catalog.PriceOfAsync(line.Sku), line.Quantity); await orders.SaveAsync(order); return order.Id; }}
// ---------- Infrastructure: database, HTTP clients, files ----------public sealed class InMemoryOrderRepository : IOrderRepository{ private readonly Dictionary<int, Order> _store = []; private int _next = 1000; public Task<int> NextIdAsync() => Task.FromResult(++_next); public Task SaveAsync(Order order) { _store[order.Id] = order; return Task.CompletedTask; } public Task<Order?> GetAsync(int id) => Task.FromResult(_store.GetValueOrDefault(id));}
public sealed class InMemoryProductCatalog : IProductCatalog{ private readonly Dictionary<string, decimal> _prices = new() { ["KB-101"] = 49.99m, ["CBL-USB-C"] = 9.50m }; public Task<decimal> PriceOfAsync(string sku) => Task.FromResult(_prices[sku]);}Output:
Placed order 1001, total 128.48Rejected: quantity must be positivePitfalls:
- Anemic domain model. Entities become property bags and every rule moves into “services”, so rules are duplicated across use cases. Put behavior such as
AddLineand its validation on the entity. - Layer skipping and leaking types. A controller that queries
DbContextdirectly, or a domain class that takes an EF Core type, quietly reverses the dependency rule. Enforce it with project references and an architecture test library such as NetArchTest or ArchUnitNET in CI. - Pass-through layers. If most application services only forward calls to a repository, the app may be CRUD; fewer layers (or vertical slices per feature) can be the better design.
Domain-driven design
Section titled “Domain-driven design”Domain-driven design (DDD), introduced by Eric Evans in Domain-Driven Design (2003), is an approach for software whose difficulty lies in its business rules rather than its technology. It has two halves. Strategic design splits a large domain into bounded contexts, each with its own model and ubiquitous language: “customer” means buyer in Ordering and recipient in Shipping, and that is fine because each context owns its own definition. Contexts integrate through explicit contracts (APIs, events, an anti-corruption layer), not a shared database.
Tactical design gives building blocks inside a context. Entities have identity that survives changes. Value objects (Money, Address) have no identity, are immutable and compare by value; C# records fit them well. An aggregate is a cluster of objects changed as one unit through its root, which enforces every invariant, so outside code never edits an order line directly. Aggregates raise domain events (OrderSubmitted) to tell the rest of the system what happened. Repositories load and save whole aggregates, and domain services hold rules that belong to no single entity.
var price = new Money(49.99m, "USD");Console.WriteLine($"Value objects equal by value: {price == new Money(49.99m, "USD")}");
var order = Order.Draft(customerId: 7);order.AddLine("KB-101", price, 1);order.AddLine("KB-101", price, 1); // same product: quantity mergesorder.AddLine("CBL-USB-C", new Money(9.50m, "USD"), 3);Console.WriteLine($"Lines: {order.LineCount}, total: {order.Total}");
order.Submit();Console.WriteLine($"Status: {order.Status}, events: {string.Join(", ", order.DomainEvents)}");
try { order.AddLine("MS-220", new Money(25m, "USD"), 1); }catch (InvalidOperationException ex) { Console.WriteLine($"Invariant: {ex.Message}"); }
try { _ = price.Add(new Money(10m, "EUR")); }catch (InvalidOperationException ex) { Console.WriteLine($"Invariant: {ex.Message}"); }
// ---------- Value object: immutable, compared by value ----------public sealed record Money(decimal Amount, string Currency){ public static Money Zero(string currency) => new(0m, currency); public Money Add(Money other) => other.Currency == Currency ? this with { Amount = Amount + other.Amount } : throw new InvalidOperationException($"Cannot add {other.Currency} to {Currency}"); public Money Times(int factor) => this with { Amount = Amount * factor }; public override string ToString() => $"{Amount:0.00} {Currency}";}
public enum OrderStatus { Draft, Submitted }public sealed record OrderSubmitted(Guid OrderId, int CustomerId, Money Total){ public override string ToString() => $"OrderSubmitted({Total})";}
// ---------- Aggregate root: the only way in, guards every invariant ----------public sealed class Order{ private readonly List<OrderLine> _lines = []; private readonly List<object> _events = [];
private Order(Guid id, int customerId) { Id = id; CustomerId = customerId; }
public Guid Id { get; } public int CustomerId { get; } public OrderStatus Status { get; private set; } = OrderStatus.Draft; public int LineCount => _lines.Count; public Money Total => _lines.Aggregate(Money.Zero("USD"), (sum, l) => sum.Add(l.LineTotal)); public IReadOnlyList<object> DomainEvents => _events;
public static Order Draft(int customerId) => new(Guid.NewGuid(), customerId);
public void AddLine(string sku, Money unitPrice, int quantity) { if (Status != OrderStatus.Draft) throw new InvalidOperationException("A submitted order cannot change"); var existing = _lines.FirstOrDefault(l => l.Sku == sku); if (existing is not null) existing.Increase(quantity); else _lines.Add(new OrderLine(sku, unitPrice, quantity)); }
public void Submit() { if (_lines.Count == 0) throw new InvalidOperationException("An empty order cannot be submitted"); Status = OrderStatus.Submitted; _events.Add(new OrderSubmitted(Id, CustomerId, Total)); }
// Inner entity: only the aggregate can create or change it. private sealed class OrderLine(string sku, Money unitPrice, int quantity) { public string Sku { get; } = sku; public int Quantity { get; private set; } = quantity; public Money LineTotal => unitPrice.Times(Quantity); public void Increase(int by) => Quantity += by; }}Output:
Value objects equal by value: TrueLines: 2, total: 128.48 USDStatus: Submitted, events: OrderSubmitted(128.48 USD)Invariant: A submitted order cannot changeInvariant: Cannot add EUR to USDPitfalls:
- Aggregates that are too big. An aggregate is a consistency boundary; loading a customer with every order ever placed causes locking and slow saves. Reference other aggregates by ID and keep each one small.
- Tactical patterns without the language. Classes named
AggregateandValueObjectadd nothing if the code still speaks in table and status-code terms. Start with the conversations, names and boundaries. - DDD everywhere. Supporting subdomains such as reference-data admin screens are often fine as simple CRUD.
Command Query Responsibility Segregation, named by Greg Young and building on Bertrand Meyer’s command-query separation, uses one model to change state and a different model to read it. Commands express intent (PlaceOrder, CancelOrder), are validated by the write model and return at most an ID. Queries (GetCustomerOrders) never change state and read from a model shaped for the screen or API that needs it: flat rows with exactly the columns required, no joins through the domain model.
CQRS has levels. The simplest is separate command and query handlers over the same database, where queries use lightweight projections (Dapper, AsNoTracking EF Core queries or views) instead of loading aggregates. The next level keeps a separate read store that projectors update from the write side’s events; reads then scale independently, but the read side is eventually consistent and can lag behind a write by milliseconds or more. Event sourcing, where the write side stores events instead of current state, pairs naturally with CQRS but is a separate decision. Libraries such as MediatR are optional; note that from version 13 MediatR is no longer Apache 2.0 but dual-licensed (the reciprocal RPL 1.5 or a commercial license), so a few lines of your own dispatching, as below, is often enough.
var writeStore = new OrderWriteStore();var readStore = new CustomerOrderSummaries();var projector = new OrderSummaryProjector(readStore);var commands = new OrderCommandHandlers(writeStore, projector.Apply);var queries = new OrderQueries(readStore);
var a = commands.Handle(new PlaceOrder(CustomerId: 7, Sku: "KB-101", Quantity: 2, UnitPrice: 49.99m));var b = commands.Handle(new PlaceOrder(CustomerId: 7, Sku: "MS-220", Quantity: 1, UnitPrice: 25.00m));commands.Handle(new CancelOrder(b));
foreach (var row in queries.Handle(new GetCustomerOrders(CustomerId: 7))) Console.WriteLine($"{row.OrderId} {row.Status,-9} {row.Total,7:0.00}");Console.WriteLine($"Open value for customer 7: {queries.Handle(new GetOpenOrderValue(7)):0.00}");
// ---------- Commands: intent to change state; return at most an ID ----------public sealed record PlaceOrder(int CustomerId, string Sku, int Quantity, decimal UnitPrice);public sealed record CancelOrder(int OrderId);
// ---------- Queries: ask for data; never change state ----------public sealed record GetCustomerOrders(int CustomerId);public sealed record GetOpenOrderValue(int CustomerId);
// ---------- Write side: rich model, validates, emits events ----------public abstract record OrderEvent(int OrderId);public sealed record OrderPlaced(int OrderId, int CustomerId, decimal Total) : OrderEvent(OrderId);public sealed record OrderCancelled(int OrderId) : OrderEvent(OrderId);
public sealed class OrderWriteStore{ public Dictionary<int, (int CustomerId, bool Cancelled)> Orders { get; } = []; public int NextId = 5000;}
public sealed class OrderCommandHandlers(OrderWriteStore store, Action<OrderEvent> publish){ public int Handle(PlaceOrder cmd) { if (cmd.Quantity <= 0) throw new ArgumentException("Quantity must be positive"); var id = ++store.NextId; store.Orders[id] = (cmd.CustomerId, false); publish(new OrderPlaced(id, cmd.CustomerId, cmd.Quantity * cmd.UnitPrice)); return id; }
public void Handle(CancelOrder cmd) { var order = store.Orders[cmd.OrderId]; if (order.Cancelled) return; // idempotent store.Orders[cmd.OrderId] = order with { Cancelled = true }; publish(new OrderCancelled(cmd.OrderId)); }}
// ---------- Read side: flat rows shaped for one screen ----------public sealed record OrderSummaryRow(int OrderId, int CustomerId, string Status, decimal Total);
public sealed class CustomerOrderSummaries{ public Dictionary<int, OrderSummaryRow> Rows { get; } = [];}
public sealed class OrderSummaryProjector(CustomerOrderSummaries read){ public void Apply(OrderEvent e) { switch (e) { case OrderPlaced p: read.Rows[p.OrderId] = new(p.OrderId, p.CustomerId, "Placed", p.Total); break; case OrderCancelled c: read.Rows[c.OrderId] = read.Rows[c.OrderId] with { Status = "Cancelled" }; break; } }}
public sealed class OrderQueries(CustomerOrderSummaries read){ public IEnumerable<OrderSummaryRow> Handle(GetCustomerOrders q) => read.Rows.Values.Where(r => r.CustomerId == q.CustomerId).OrderBy(r => r.OrderId);
public decimal Handle(GetOpenOrderValue q) => read.Rows.Values.Where(r => r.CustomerId == q.CustomerId && r.Status == "Placed").Sum(r => r.Total);}Output:
5001 Placed 99.985002 Cancelled 25.00Open value for customer 7: 99.98Pitfalls:
- CQRS for CRUD. Two models for a screen that reads and writes the same fields doubles the code for no gain. Apply it per bounded context, where read and write needs really differ.
- Ignoring eventual consistency. With a separate read store, a user who just placed an order may not see it on the next page. Return the new data from the command, or read your own writes from the write side for that request.
- Queries that modify state. A “query” that updates a last-viewed timestamp breaks caching and replicas; make it a command.
Event-driven architecture
Section titled “Event-driven architecture”In event-driven architecture (EDA), components communicate by publishing events, immutable records of something that already happened (OrderPlaced), instead of calling each other. A producer does not know who consumes its events; consumers (email, inventory, analytics) subscribe and react independently, so new reactions need no change to the producer. Domain events stay inside one service and are often dispatched in-process; integration events cross service boundaries through a broker such as Azure Service Bus, RabbitMQ or Apache Kafka.
Two problems appear as soon as a broker is involved. First, dual writes: saving the order and publishing the event are two operations, and a crash between them loses the event or publishes one for an order that was rolled back. The transactional outbox fixes this by writing the event to an outbox table in the same database transaction as the order; a relay publishes pending rows afterwards. Second, the relay or broker can deliver a message more than once (at-least-once delivery), so consumers must be idempotent, typically by recording processed message IDs. The sample simulates a relay crash to show both pieces working.
#:property PublishAot=falseusing System.Text.Json;
var db = new FakeDatabase();var broker = new InMemoryBroker();broker.Subscribe("order-placed", new EmailConsumer().Handle);broker.Subscribe("order-placed", new InventoryConsumer().Handle);
// 1. The use case writes the order and the outgoing event in ONE transaction.db.Transaction(tx =>{ tx.Orders.Add(new Order(1001, "dana@example.test", 128.48m)); tx.Outbox.Add(OutboxMessage.For("order-placed", new OrderPlaced(1001, "dana@example.test", 128.48m)));});
// 2. A background relay publishes pending outbox rows. Simulate a crash after// publishing but before marking the row sent: the message goes out twice.var relay = new OutboxRelay(db, broker);relay.PublishPending(crashBeforeMarkingSent: true);relay.PublishPending(crashBeforeMarkingSent: false);Console.WriteLine($"Outbox rows still pending: {db.Outbox.Count(m => m.SentAt is null)}");
// ---------- Events: past tense facts ----------public sealed record OrderPlaced(int OrderId, string CustomerEmail, decimal Total);public sealed record Order(int Id, string CustomerEmail, decimal Total);
public sealed class OutboxMessage{ public Guid Id { get; } = Guid.NewGuid(); // also the message ID consumers dedupe on public required string Topic { get; init; } public required string Payload { get; init; } public DateTimeOffset? SentAt { get; set; } public static OutboxMessage For<T>(string topic, T message) => new() { Topic = topic, Payload = JsonSerializer.Serialize(message) };}
public sealed class FakeDatabase{ public List<Order> Orders { get; } = []; public List<OutboxMessage> Outbox { get; } = []; public void Transaction(Action<FakeDatabase> work) => work(this); // stands in for a real DB transaction}
public sealed class InMemoryBroker{ private readonly Dictionary<string, List<Action<Guid, string>>> _subscribers = []; public void Subscribe(string topic, Action<Guid, string> handler) => (_subscribers.TryGetValue(topic, out var list) ? list : _subscribers[topic] = []).Add(handler); public void Publish(string topic, Guid messageId, string payload) { foreach (var handler in _subscribers.GetValueOrDefault(topic, [])) handler(messageId, payload); }}
public sealed class OutboxRelay(FakeDatabase db, InMemoryBroker broker){ public void PublishPending(bool crashBeforeMarkingSent) { foreach (var message in db.Outbox.Where(m => m.SentAt is null)) { broker.Publish(message.Topic, message.Id, message.Payload); if (crashBeforeMarkingSent) { Console.WriteLine("relay: crashed before marking sent"); return; } message.SentAt = DateTimeOffset.UtcNow; } }}
// ---------- Consumers: independent, idempotent ----------public sealed class EmailConsumer{ private readonly HashSet<Guid> _processed = []; // in production: a table keyed by message ID public void Handle(Guid messageId, string payload) { if (!_processed.Add(messageId)) { Console.WriteLine("email: duplicate ignored"); return; } var e = JsonSerializer.Deserialize<OrderPlaced>(payload)!; Console.WriteLine($"email: confirmation for order {e.OrderId} sent to {e.CustomerEmail}"); }}
public sealed class InventoryConsumer{ private readonly HashSet<Guid> _processed = []; public void Handle(Guid messageId, string payload) { if (!_processed.Add(messageId)) { Console.WriteLine("inventory: duplicate ignored"); return; } Console.WriteLine($"inventory: stock reserved for order {JsonSerializer.Deserialize<OrderPlaced>(payload)!.OrderId}"); }}Output:
email: confirmation for order 1001 sent to dana@example.testinventory: stock reserved for order 1001relay: crashed before marking sentemail: duplicate ignoredinventory: duplicate ignoredOutbox rows still pending: 0The sample sets PublishAot=false because file-based apps default to Native AOT, which disables the reflection-based JsonSerializer calls used here for brevity.
Pitfalls:
- Events as remote procedure calls. An event named
SendEmailthat the producer expects one specific consumer to handle is a command in disguise; you keep the coupling and lose the error handling of a direct call. - Assuming order and exactly-once. Most brokers guarantee order only within a partition or session, and deliver at least once. Design consumers to tolerate duplicates and out-of-order events (version numbers, idempotency keys).
- Invisible flows. Nobody can see the whole process any more. Propagate a correlation ID in message headers, use distributed tracing (OpenTelemetry), and monitor dead-letter queues.
For broker-level patterns (queues versus topics, sagas, dead-letter queues), see Microservices messaging patterns.
Choosing between them
Section titled “Choosing between them”- Start layered with the dependency rule for almost any service that will live longer than a prototype. It is cheap and keeps infrastructure replaceable.
- Add DDD tactical patterns where business rules are complex and change often (pricing, ordering, claims), and use bounded contexts to decide service and team boundaries.
- Add CQRS when read and write shapes or loads diverge: dashboards over large data, search, or read traffic far above write traffic. Begin with separate handlers on one database before adding a read store.
- Add events when one action triggers several independent reactions, when other services must learn about changes without being called, or when work can finish later. Use the outbox as soon as events leave the process.
- Avoid all four extras for simple CRUD, reporting tools and short-lived prototypes, where a single project with EF Core and a few endpoints is the right architecture.
Interview questions
Section titled “Interview questions”What is the dependency rule in clean or onion architecture? Source code dependencies point inward: infrastructure and presentation depend on application and domain, never the reverse. Inner layers define interfaces for what they need, and outer layers implement them, so business rules do not change when the database or web framework does.
What is the difference between an entity and a value object?
An entity has an identity that persists while its attributes change (order 1001 is the same order after a new line is added). A value object is defined only by its values, is immutable and is compared by value (two Money(49.99, "USD") instances are equal).
Why should an aggregate be small? It is the unit of consistency and of locking: every change loads and saves the whole aggregate in one transaction. Large aggregates cause contention and slow writes, so keep only what must be consistent together, and reference other aggregates by ID.
Does CQRS require two databases? No. The core idea is separate models and handlers for commands and queries. A separate read store is an optional later step for scaling or very different read shapes, and it introduces eventual consistency.
What is the transactional outbox and why is it needed? It stores outgoing messages in the same database transaction as the state change, then a relay publishes them. Without it, a crash between “save” and “publish” either loses an event or publishes one for data that was never committed. Because the relay can publish twice, consumers must be idempotent.
Senior scenario: OrdersPortal is a layered monolith whose order page is slow and whose order placement must now notify inventory, billing and email. How do you evolve it?
Keep the monolith but find the bounded contexts first. For the slow page, add query handlers with read-optimized projections (and indexes or a view) before considering a separate read store. For notifications, raise an OrderPlaced domain event in the order aggregate, write it to an outbox in the same transaction, and publish it through a broker; inventory, billing and email become idempotent subscribers, at first as modules in the same process, later as separate services if team or scaling needs justify it. Add correlation IDs and tracing before the first consumer goes live, and only split out services once the context boundaries have proven stable.
Related pages
Section titled “Related pages”- Software architecture introduction
- Design patterns: structural and behavioral: repository, observer and strategy at class level.
- Microservices messaging patterns
- Microservices communication
- .NET core features: dependency injection