Volume 6 · Chapter 2 — Enterprise Application Architecture and Design Patterns

Domain-Driven Design Advanced Patterns

Goutham Mayaluri 9 min read .NETC#

2.1 Introduction

Domain-Driven Design (DDD) is a way of building software in which the structure and language of the code mirror the business domain. Its advanced patterns address the hardest part of enterprise software: keeping a model coherent as it grows across many teams and years. DDD splits intostrategicdesign (how you carve the system into boundaries) andtacticaldesign (how you express the model inside a boundary). Getting the strategic part right is what prevents a large system from collapsing into a tangle of shared, overloaded concepts.

2.2 Strategic DDD: Bounded Contexts and Ubiquitous Language

Abounded contextis an explicit boundary within which a particular model and its ubiquitous language are consistent. The word “account” means something different to the Payments team than to the Customer Onboarding team, and DDD makes that difference explicit instead of forcing one bloated shared model. Each context owns its language, its model, and ideally its data.

flowchart LR
  subgraph Payments["Payments Context"]
      P["Account = source of funds"]
  end
  subgraph Lending["Lending Context"]
      L["Account = credit line"]
  end
  subgraph CRM["Customer Context"]
      C["Customer = profile & KYC"]
  end
  CRM -- "Customer-Supplier" --> Payments
  CRM -- "Customer-Supplier" --> Lending
  Payments -- "Published events" --> Lending

Context Mapping

A context map documents the relationships between contexts: shared kernel, customer-supplier, conformist, anti-corruption layer, and so on. It is a strategic artefact that tells teams how they may integrate and where they must translate between models.

2.3 Tactical DDD Building Blocks

  • Entities- objects with a lifecycle and identity.
  • Value Objects- immutable, equality by value.
  • Aggregates- a cluster of objects treated as a unit for consistency, guarded by an aggregate root.
  • Domain Services- stateless operations that do not belong to a single entity.
  • Repositories- collection-like access to aggregates.
  • Factories- encapsulate complex creation.
  • Domain Events- record that something meaningful happened.

2.4 Aggregate Design

An aggregate defines aconsistency boundary. All invariants inside the boundary must hold after every transaction, and the aggregate root is the only entry point through which the outside world may change the cluster. This is what protects business rules from being bypassed.


public sealed class Order // aggregate root
{
    private readonly List<OrderLine> _lines = new();
    public OrderId Id { get; }
    public OrderStatus Status { get; private set; }
    public Money Total => _lines.Aggregate(Money.Zero, (t, l) => t + l.LineTotal);

    // External code cannot touch _lines directly - it must go through the root,
    // so the "no changes after submission" invariant can be enforced.
    public void AddLine(ProductId product, int qty, Money unitPrice)
    {
        if (Status != OrderStatus.Draft)
            throw new DomainException("Cannot modify a submitted order.");
        _lines.Add(new OrderLine(product, qty, unitPrice));
    }

    public void Submit()
    {
        if (_lines.Count == 0)
            throw new DomainException("Cannot submit an empty order.");
        Status = OrderStatus.Submitted;
        Raise(new OrderSubmitted(Id, Total));
    }
}

2.5 Aggregate Boundary Guidelines

Poor aggregate boundaries are the most expensive DDD mistake. Large aggregates cause lock contention and load huge object graphs; tiny ones fail to protect real invariants. The widely used guidelines are:

  • Keep aggregatessmall- prefer referencing other aggregates by ID rather than by object reference.
  • Enforce only the invariants that must beimmediatelyconsistent inside one aggregate.
  • Modifyone aggregate per transaction; coordinate across aggregates with domain events and eventual consistency.

2.6 Domain Services and Factories

Some operations - transferring money between two accounts, evaluating fraud risk across several signals - do not belong to any single entity. These becomedomain services: stateless, named in the ubiquitous language, and operating on domain objects.Factoriesencapsulate the creation of complex aggregates so they can never be born in an invalid state.


public sealed class FundsTransferService // domain service
{
    public void Transfer(Account from, Account to, Money amount)
    {
        from.Withdraw(amount); // each aggregate protects its own invariants
        to.Deposit(amount);
    }
}

2.7 Repositories

A repository presents aggregates as if they were an in-memory collection, hiding persistence. It is defined as an interface in the domain and implemented in infrastructure. A repository returns whole aggregates, never partial rows, so invariants stay intact.

2.8 Domain Events and the Anti-Corruption Layer

Domain events let one part of the model react to another without tight coupling. When two systems must integrate but speak different languages, anAnti-Corruption Layer(ACL) translates between them so the foreign model never bleeds into your clean one.

sequenceDiagram
  autonumber
  participant Ord as Order Aggregate
  participant Bus as In-Process Dispatcher
  participant Inv as Inventory Handler
  participant Ship as Shipping Handler
  Ord->>Ord: Submit()
  Ord->>Bus: raise OrderSubmitted
  Bus->>Inv: OrderSubmitted
  Bus->>Ship: OrderSubmitted
  Inv-->>Bus: stock reserved
  Ship-->>Bus: shipment scheduled
  Note over Bus,Ship: Handlers react independently; the Order knows none of them

2.9 Legacy Integration with an ACL


// Anti-Corruption Layer: translates a legacy contract into our domain language.
public sealed class LegacyCreditGatewayAcl : ICreditCheck
{
    private readonly LegacyScoreClient _legacy;

    public async Task<CreditDecision> EvaluateAsync(CustomerId id, CancellationToken ct)
    {
        // Legacy returns a cryptic numeric code; we translate into our terms.
        LegacyScoreResponse raw = await _legacy.GetScoreAsync(id.Value, ct);
        return raw.Code switch
        {
            0 => CreditDecision.Approved,
            1 => CreditDecision.Refer,
            _ => CreditDecision.Declined
        };
    }
}
Senior Interview Question

Why are aggregate boundaries important?

Aggregate boundaries define where strong (immediate) consistency is guaranteed and who owns each rule. Well-drawn boundaries keep transactions small, reduce lock contention, and prevent code outside the aggregate from bypassing invariants. Poorly drawn boundaries either bundle unrelated data into one giant consistency unit - hurting scalability - or split a genuine invariant across two aggregates, so the rule can no longer be enforced atomically.

Senior Interview Question

When would you use a domain service instead of putting logic on an entity?

Use a domain service when an operation naturally involves several aggregates or belongs to no single one - transferring funds between two accounts, or a pricing calculation that spans a catalogue and a customer agreement. Forcing that logic onto one entity would make it reach into another aggregate’s internals and blur ownership. The service stays stateless, is named in the ubiquitous language, and delegates each mutation to the aggregate that owns it.

Senior Interview Question

What is the difference between a domain event and an integration event?

A domain event describes something meaningful that happenedinsideone bounded context (OrderSubmitted) and is typically handled in-process, often within the same transaction or immediately after commit. An integration event is the contract you publish toothercontexts or services over a broker; it is versioned, serialisable, and deliberately decoupled from your internal model. A common pattern is to raise domain events internally, then, on commit, translate the relevant ones into integration events for the outside world.

Senior Interview Question

How do you decide between an entity and a value object?

Ask whether identity matters over time. If two instances with identical attributes are interchangeable, it is a value object - model it immutable with value equality (money, address, date range). If the object has a continuous lifecycle and must be tracked even as its attributes change, it is an entity with a stable identifier. Favour value objects: they are immutable, side-effect free, and eliminate a large category of bugs around shared mutable state.

Principal Engineer Question

How do you identify good bounded context boundaries?

Look for seams in the business, not in the technology. Strong signals are divergent language (the same word meaning different things), different rates and sources of change, distinct teams and ownership, and different consistency and data needs. Techniques like Event Storming surface these seams by mapping domain events across the business. I treat organisational boundaries (Conway’s Law) as first-class input: a context that spans two teams will constantly generate coordination cost. The aim is high cohesion inside a context and a small, explicit, translated surface between contexts.

Principal Engineer Question

Your aggregates have grown huge and transactions are contended. How do you fix it?

Oversized aggregates usually mean invariants that do not actually require immediate consistency have been bundled together. I’d identify which rules truly must hold atomically and shrink the aggregate to just those, replacing object references to other aggregates with IDs. Cross-aggregate workflows move to domain events with eventual consistency (for example, an order raises an event and inventory reserves stock in its own transaction, compensating if it fails). This trades a little consistency latency for dramatically better throughput and smaller lock footprints, which is almost always the right call at scale.

Principal Engineer Question

When is DDD the wrong choice?

DDD earns its cost in complex, evolving domains with real business rules. For a thin CRUD application, a reporting tool, or a technical utility with little domain logic, the tactical patterns add ceremony without payoff, and a simpler transaction-script or CRUD approach ships faster. The strategic ideas - clear boundaries and shared language - still help even there, but the full tactical toolkit (aggregates, domain events, repositories) should be reserved for the subdomains where the business complexity actually lives. Identifying thecoredomain and investing DDD effort there, while keeping generic subdomains simple, is itself a key strategic decision.

2.10 Banking Enterprise Scenario

A digital bank models Payments, Lending, and Customer as separate bounded contexts, each with its own database and team. The Account aggregate in Payments enforces “you cannot spend money you do not have” atomically, while Lending maintains its own notion of an account as a credit line. When a payment completes, Payments publishes an integration event; Lending consumes it through an anti-corruption layer that translates the payment contract into its own terms. No context reaches into another’s tables, so each can evolve and scale independently.

Chapter Revision Notes

  • Strategic DDD defines boundaries and language; tactical DDD models behaviour.
  • Aggregates are consistency boundaries guarded by a root.
  • Keep aggregates small; one aggregate per transaction; reference others by ID.
  • Domain events decouple reactions; ACLs translate foreign models.
  • Reserve full DDD for the complex core domain, not generic subdomains.