Course contents

10. Software Architecture Lesson 6 of 10

Domain-Driven Design

See why one shared model breaks down, how bounded contexts and a ubiquitous language fix it, why aggregates should be small, and how a context map works.

18 minIntermediate10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A bounded context is the boundary inside which one model and one language apply.
  • The same real-world thing can be modelled differently in different contexts, linked by a shared id.
  • An aggregate is a consistency boundary and a unit of locking: one transaction changes one aggregate.
  • Big aggregates serialise unrelated work; keep them as small as the true invariants allow.
  • Contexts talk through domain events and published contracts, and are eventually consistent with each other.
  • Spend tactical modelling effort on the core domain; buy or CRUD the generic parts.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Domain-Driven Design (DDD) is an approach to software for complex business domains, introduced by Eric Evans in 2003. It has two halves:

  • Strategic design decides where the boundaries go: which parts of the business get their own model (bounded contexts), what each part calls things (ubiquitous language) and how the parts relate (context map).
  • Tactical design gives building blocks for the model inside one context: entities, value objects, aggregates, domain events, repositories and domain services.

Why it exists

As a system grows, the business vocabulary splits without anyone noticing. "Product", "Customer" or "Order" mean different things to sales, the warehouse and finance. A single model that tries to serve all of them grows dozens of fields and conditionals, and every change needs every team's agreement. DDD makes those different meanings explicit and gives each its own model, so teams can change their part without negotiating with everyone else.

How it works

Ubiquitous language. Within a context, developers and domain experts use the same terms in conversation, documentation and code. If the experts say "an order is placed", the method is Place(), not SetStatus(2). When the language gets awkward, that is a modelling signal.

Bounded contexts. A bounded context is the boundary inside which one model and one language are consistent. Sales can have a Product with a name and price, Shipping a StockItem with weight and bin locations, Billing an InvoiceLine with a VAT code. They refer to the same thing by a shared identifier (here the SKU) and share nothing else. A context owns its data; others reach it through its API or its events. A context is a model boundary, not necessarily a deployable: a module of a modular monolith works as well as a separate service.

Aggregates. An aggregate is a cluster of objects (an Order with its OrderLines) treated as one unit for changes. All changes go through the aggregate root, which enforces the invariants ("at most 50 lines", "total within the credit limit"). The rules of thumb, from Vaughn Vernon's Effective Aggregate Design:

  • protect true invariants inside the aggregate boundary;
  • design small aggregates;
  • reference other aggregates by identity only;
  • change one aggregate per transaction, and use eventual consistency (domain events) outside it.

In .NET this usually means an entity with private setters and behaviour methods, persisted with EF Core: one SaveChangesAsync() per command, with a concurrency token ([Timestamp]/RowVersion on SQL Server, xmin on PostgreSQL via Npgsql) so two concurrent edits of the same aggregate cannot both win.

public sealed class Order
{
    private readonly List<OrderLine> _lines = new();
    public OrderId Id { get; private set; }
    public CustomerId CustomerId { get; private set; }   // reference by id
    public Money Total => _lines.Aggregate(Money.Zero, (sum, l) => sum + l.Amount);

    public Result AddLine(Sku sku, int quantity, Money price, Money creditLimit)
    {
        if (_lines.Count >= 50) return Result.Fail("An order has at most 50 lines.");
        var amount = price * quantity;
        if (Total + amount > creditLimit) return Result.Fail("Credit limit exceeded.");
        _lines.Add(new OrderLine(sku, quantity, amount));
        return Result.Ok();
    }
}

Domain events. When something meaningful happens (OrderPlaced), the aggregate records an event. After the transaction commits, the event is published (reliably, with a transactional outbox) and other aggregates or contexts react in their own transactions.

Context map. The map names how contexts relate. Upstream/downstream: the downstream depends on the upstream's model or events. Patterns on the map include customer/supplier (the upstream takes the downstream's needs into account), conformist (the downstream adopts the upstream model as is), anti-corruption layer (the downstream translates the upstream model into its own), open host service and published language (a stable, documented protocol for many consumers), shared kernel (a small shared model both sides must agree on) and separate ways (no integration at all).

Subdomains. The core domain is what differentiates the business; supporting subdomains are specific but not differentiating; generic subdomains are solved problems (identity, invoicing, email). Rich modelling belongs in the core.

When to use it

  • The domain logic is genuinely complex: many rules, exceptions, workflows, and they change often.
  • Several teams work on one system and keep stepping on each other's models.
  • You are planning service boundaries: bounded contexts are the best-known heuristic for where to split.
  • Domain experts are available to talk to; the language comes from them.

When not to

  • CRUD over a few tables with little behaviour: a rich domain model adds layers with nothing to protect.
  • A small team on a small system where one model is still understood by everyone.
  • Generic subdomains: buy them or keep them simple.
  • Without access to domain experts, the "ubiquitous language" becomes developers' guesses with extra ceremony.

Trade-offs

Choice You gain You pay
Separate models per context Teams change independently; each model stays small Translation at the boundaries, duplicated data (by SKU/id)
Small aggregates Parallel commits, less contention, simpler loading Cross-aggregate rules become eventually consistent policies
Large aggregates One transaction can enforce more rules Lock contention, concurrency conflicts, slow loads
Domain events between contexts Temporal decoupling, no distributed transactions Eventual consistency, harder debugging, event versioning
Anti-corruption layer Your model survives upstream changes One more component to build and maintain

Alternatives

  • Transaction script / CRUD: procedures over tables. Fast to build, fine while rules are few.
  • Data-centric "canonical model": one enterprise-wide schema. Looks consistent, couples everyone.
  • Layered or clean architecture without DDD: organises code technically; does not by itself find business boundaries.
  • Team Topologies / Conway-driven boundaries: complementary; aligns teams with the contexts DDD identifies.

Failure modes

  • The god aggregate. Making Customer contain all orders turns every command into contention for one lock or version. The lesson's simulation shows it: ~40 commands/s ceiling, queues, timeouts.
  • Anaemic model. Entities with only getters/setters and all rules in services: the vocabulary of DDD without the encapsulation.
  • Shared database between contexts. Contexts that read each other's tables are one model again, just harder to see.
  • Context per entity. Splitting too fine ("Address service") creates chatty dependencies; contexts follow business capabilities, not nouns.
  • Leaky upstream models. Using an external provider's types in your domain makes every provider change your change.
  • Distributed transactions across contexts. Two-phase commit between services reintroduces tight coupling and availability risk.

In production

Start with event storming or domain-expert interviews to find language and boundaries; draw the context map and keep it in the repo next to the code. In .NET, a context is often a project or a set of projects in a modular monolith with its own DbContext and schema, exposing a small public contract (commands, queries, integration events). Use concurrency tokens on aggregates, publish integration events through an outbox, and version event contracts (OrderPlaced v1, v2) like public APIs. Revisit boundaries as the business changes; a wrong boundary is cheaper to move inside a monolith than across services.

Common misconceptions

  • "DDD means microservices." Bounded contexts are model boundaries. They map well to services, but a modular monolith with one module per context is often the better start.
  • "DDD is the tactical patterns." Repositories and value objects are the smaller part. The big wins come from boundaries and language.
  • "An aggregate is any object graph you load together." It is the unit of consistency and concurrency, sized by the invariants it must protect.
  • "Every context needs the full toolkit." Generic and supporting subdomains usually don't.

Interview angle

When splitting a system, name the bounded contexts and justify them by business capability and language ("in Shipping a product is a stock item with weight and bins"). Show you know aggregates are consistency boundaries: one per transaction, referenced by id, kept small, with cross-aggregate rules handled by events and eventual consistency. Mention optimistic concurrency, the outbox for publishing events, and an anti-corruption layer for third parties. Saying when you would not use tactical DDD scores points.

Model assumptions

Most of this lesson is a scripted illustration: the departments, contexts, event bus, anti-corruption layer and payment provider are scenery, and their packets follow a fixed script rather than a simulation. Two steps (Too big, Keep small) and the challenge run on the simulation engine: Sales receives Poisson-distributed commands (all writes); the Sales service has 32 workers and 5 ms of work per command; the aggregate lock is modelled as a store that runs one command at a time (1 connection, 25 ms mean, lognormal cv 0.3), while small Order aggregates commit in parallel (12 connections, 15 ms). Commands that wait more than 500 ms fail. Real lock and optimistic-concurrency behaviour differs in detail (conflicts and retries instead of a queue); the numbers are illustrative, not benchmarks.

The lesson as textEvery step of the simulation, written out.
  1. 1. One model for the whole business

    Three departments use one shop application. All three talk about a Product, and the code has exactly one Product class and one products table.

    But they do not mean the same thing. Sales means something you can sell: a name, a price, a description. The warehouse means a physical box: weight, dimensions, a bin location. Finance means a line on an invoice: a VAT code and an amount. The one class carries all of it, about sixty fields, and every team edits it.

    This step is a scripted illustration: the packets show who uses the shared model, not simulated traffic.

    Scene: Sales, Warehouse and Finance all use one Shop app with one shared database. Each department means something different by "Product", but the code has a single Product model with about sixty fields.

    Key idea: The same word means different things in different parts of a business. One model for all of them grows into a tangle nobody fully understands.

  2. 2. A change for one team breaks another

    The warehouse starts stocking one product in several bins, so a developer changes the shared table: the single bin column becomes a list of stock locations. It is a sensible change for the warehouse.

    That night the invoicing job, which reads the same table, fails. Nobody in Finance asked for anything, and nobody in the warehouse knew Finance depended on that column. Every change to the shared model needs every team in the room, so changes slow down or break things.

    Scripted illustration: the migration (blue), then Finance’s request failing (red).

    Scene: The warehouse changes the shared products table. Afterwards Finance’s invoicing request to the same table fails, because it relied on the column that changed.

    Key idea: A shared model couples every team that touches it. Coordination cost grows with every team and every field.

  3. 3. Bounded contexts, each with its own model

    DDD splits the problem along the lines of the business. Each bounded context has its own model, its own data and, ideally, one team. Inside it, every term has exactly one meaning, and developers and domain experts use the same words in conversation and in code: the ubiquitous language.

    Sales now has a Product with a name and a price. Shipping has a StockItem with weight and bins. Billing has an InvoiceLine with a VAT code. They share a SKU to refer to the same thing, and nothing else. The warehouse can change StockItem without asking Finance.

    A bounded context is a model boundary, not necessarily a deployment boundary: it can be a module in a monolith or its own service. Still scripted: packets show each team using only its own context.

    Scene: Three bounded contexts: Sales, Shipping and Billing, each with its own service, its own database and its own model of a product (Product, StockItem, InvoiceLine). Each team works only inside its own context.

    Key idea: A bounded context is the boundary inside which one model and one language apply. Different contexts may model the same real thing differently.

  4. 4. An aggregate guards its own rules

    Zoom into Sales. An Order with its order lines is an aggregate: a cluster of objects changed together through one entry point, the *aggregate root*. Its rules (at most 50 lines, total within the customer’s credit limit) are checked inside it, and each change is saved in one transaction.

    First command: add a line worth 40. The total stays within the limit, the order is saved as version 8. Second command: add a line worth 200. The aggregate rejects it before anything reaches the database: the rule is enforced in one place, not scattered over controllers.

    In .NET this is typically an Order class with private setters and methods like AddLine(...) that throw or return an error when a rule would break, saved through one DbContext.SaveChangesAsync() call. Scripted illustration.

    Scene: The first AddLine command passes the Order aggregate’s credit-limit rule and is saved in one transaction. The second would exceed the limit and is rejected by the aggregate without reaching the database.

    Key idea: An aggregate is a consistency boundary: its invariants hold after every transaction, and one transaction changes one aggregate.

  5. 5. One huge aggregate serialises everything

    Suppose the model makes Customer the aggregate and puts every order inside it, so the credit-limit rule can see all orders at once. A big B2B customer has many buyers placing orders at the same time, about 50 commands per second.

    Every command now loads and locks the same aggregate, so commands on unrelated orders wait for each other. Here that lock is modelled as a store that commits one command at a time, about 25 ms each: at most 40 per second. The queue grows, P95 latency climbs to hundreds of milliseconds and commands that wait longer than 500 ms fail.

    This step runs on the simulation engine.

    Scene: Sales receives 50 commands per second for one customer. Because the Customer aggregate contains all orders, commands commit one at a time; they queue, P95 latency rises to hundreds of milliseconds and some fail after waiting 500 ms.

    Key idea: An aggregate is also a unit of locking. The bigger it is, the more unrelated work contends for it.

  6. 6. Small aggregates, referenced by id

    Make each Order its own aggregate that refers to the customer by CustomerId, not by holding the Customer object. Commands on different orders no longer touch the same aggregate, so they commit in parallel, and each loads less data (about 15 ms).

    The queue drains, errors stop and P95 drops to well under 100 ms. Two buyers editing the *same* order still conflict, and that is caught by an optimistic version check (RowVersion / concurrency token in EF Core): the second save fails and is retried.

    The price: the credit limit across *all* orders is no longer one transaction. It becomes a policy checked when the order is placed, or a reservation in a separate Credit aggregate, and it is eventually consistent. That is the classic trade: smaller aggregates, more throughput, weaker cross-aggregate guarantees. Simulated.

    Scene: Each order is its own aggregate. Commands on different orders commit in parallel; the queue is gone, nothing fails and P95 latency is well under 100 ms.

    Key idea: Design aggregates as small as the true invariants allow; reference other aggregates by id.

  7. 7. Domain events cross the boundaries

    When an order is placed, Shipping must prepare a parcel and Billing must raise an invoice. Sales does not call into their models. It commits its own transaction and then publishes a domain event, OrderPlaced { orderId, sku, qty }, in its own language.

    Shipping and Billing each react in their own transaction, a moment later. Each context stays consistent internally; *between* contexts the system is eventually consistent. To publish reliably after the commit, use the transactional outbox (see that lesson).

    Scripted illustration: the commit (blue and green), then the event (teal) fanned out by the event bus. The simulated Sales traffic keeps running underneath at a lower rate.

    Scene: Sales commits an order and publishes an OrderPlaced event to the event bus. The bus delivers it to Shipping and Billing, which each update their own database in their own transaction.

    Key idea: Aggregates and contexts change in their own transactions and tell each other what happened through domain events.

  8. 8. The context map: who depends on whom

    A context map names the relationships between contexts. Sales is upstream of Shipping and Billing: they consume its events, so Sales owes them a stable, versioned contract (a *published language*, here OrderPlaced v1).

    Billing depends on an external payment provider whose model it cannot change. Instead of letting the provider’s terms (payment intents, charge objects, status codes) leak into its own code, Billing puts an anti-corruption layer in between: an adapter that translates Charge(invoiceId, amount) into the provider’s API and the provider’s reply back into PaymentCaptured. If the provider changes, only the adapter changes.

    Other relationships you will meet: *shared kernel* (two contexts share a small model and must agree on changes), *conformist* (a downstream simply adopts the upstream model), *open host service* (an upstream API designed for many consumers). Scripted illustration.

    Scene: The context map: Sales is upstream of Shipping and Billing through its OrderPlaced v1 events. Billing calls an external payment provider only through an anti-corruption layer that translates between the two models.

    Key idea: Map upstream/downstream relationships explicitly, and protect your model from models you do not control with an anti-corruption layer.

  9. 9. Spend the modelling effort where it pays

    Not every context deserves rich modelling. DDD distinguishes the core domain (what makes this business different, here pricing and ordering rules in Sales), supporting subdomains (needed, specific, but not a differentiator, like Shipping) and generic subdomains (solved problems such as invoicing or identity, best bought or kept as simple CRUD).

    Aggregates, domain events and a carefully grown language cost time. Use them where the rules are complex and change often. For a settings screen or a reporting table, a plain CRUD model over EF Core is the right amount of design.

    Scripted illustration: the annotations rank the three contexts.

    Scene: Sales is labelled as the core domain with a rich model, Shipping as a supporting subdomain with a simpler model, and Billing as a generic subdomain best bought or kept as CRUD.

    Key idea: Strategic DDD (contexts, language, map) helps almost everywhere; tactical patterns (aggregates, events) belong in the complex core.

  10. 10. What to remember about DDD

    Strategic design first: find the bounded contexts where one model and one ubiquitous language hold, give each its own data and, ideally, one team, and draw the context map between them.

    Tactical design inside the complex ones: aggregates as small consistency boundaries saved one per transaction, references by id, domain events for everything that crosses a boundary, and an anti-corruption layer in front of models you do not control. Consistency inside an aggregate is immediate; between aggregates and contexts it is eventual, by design.

    Scene: The full map: Sales, Shipping and Billing contexts with their own services and databases, the event bus between them, and Billing’s anti-corruption layer in front of the external payment provider.

    Key idea: DDD is mostly about boundaries: of language, of models and of transactions.