Domain-Driven Design
Domain-Driven Design is an approach to software development that puts the business domain at the centre, using a shared language between developers and domain experts to build models that reflect real-world rules.
Overview
Domain-Driven Design aligns software boundaries and language with a complex business domain. Strategic design distinguishes core, supporting, and generic subdomains, defines bounded contexts in which one model is consistent, and maps upstream/downstream relationships and translation between contexts. Tactical design uses entities with identity, immutable value objects, small aggregate consistency boundaries, domain services for behavior that belongs to no one entity, repositories for aggregate access, and factories for valid creation. Aggregates protect immediate invariants but should not grow into object graphs; workflows across roots or contexts normally use application coordination and eventual consistency. Domain events record internal facts, while integration events are deliberately mapped, versioned, and delivered through an outbox after state commits. DDD is a continuous collaboration and learning process, not a mandatory folder structure or a reason to add patterns to straightforward CRUD subdomains.
What you will learn
- Discover ubiquitous language and distinguish core, supporting, and generic subdomains.
- Define bounded contexts and map their upstream and downstream relationships.
- Model entities, value objects, aggregates, invariants, services, and repositories deliberately.
- Keep aggregate consistency boundaries small and enforce behavior through roots.
- Separate domain events from durable integration events and publish safely.
- Test domain models directly and persist them with optimistic concurrency.
Prerequisites
- Object-oriented C#, testing, persistence, and transaction fundamentals.
- Familiarity with business workflows, messaging, consistency, and architecture boundaries.
- Access to domain experts or representative business knowledge.
When to use Domain-Driven Design
Good fit
- Business rules, terminology, exceptions, and workflows are complex and changing.
- Multiple areas use the same words with different meanings.
- Correctness and shared understanding justify sustained modeling collaboration.
Choose another approach when
- The capability is straightforward CRUD with little differentiated policy.
- The team applies tactical patterns without domain discovery.
- One enterprise model would erase necessary contextual meanings.
Key concepts
A shared vocabulary used by both developers and domain experts in code, tests, and conversations, so the model and the business stay aligned.
An explicit boundary within which a particular domain model and its language are consistent; different contexts can have different models for the same concept.
An aggregate is a cluster of objects treated as one unit for data changes; the root entity controls access and enforces all invariants.
Value objects model concepts by their attributes rather than identity; domain events record meaningful state changes that other parts of the system can react to.
Core, supporting, and generic subdomains guide where deep modeling and investment create competitive value.
Upstream and downstream relationships, translation, and ownership make dependencies between bounded contexts explicit.
Repositories retrieve aggregate roots and factories create valid complex objects without exposing persistence or assembly details.
Domain events coordinate inside a boundary; integration events are stable external contracts published reliably after commit.
Architecture
Bounded contexts own their models and communicate through well-defined contracts or domain events, keeping each context independently evolvable.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
The subscription sample models one aggregate root, validated CustomerId and Plan value objects, explicit invariants, and past-tense events without any framework or persistence dependency.
- 01Explore the domain
Use event storming, examples, and expert conversations to find language, rules, decisions, and exceptions.
- 02Separate contexts
Identify model boundaries, ownership, upstream dependencies, and translation needs.
- 03Choose aggregates
Group only state that must remain immediately consistent and select one root.
- 04Model behavior
Create entities and value objects that reject invalid state and expose business operations.
- 05Record events
Capture meaningful past-tense facts and distinguish internal domain events from external contracts.
- 06Persist safely
Load and save roots through focused repositories with optimistic concurrency and atomic outbox records.
- 07Evolve language
Refactor code, tests, documentation, and contracts as expert understanding improves.
Code example
An aggregate root enforces its own invariants and raises domain events instead of letting callers mutate state directly.
public sealed class Order : AggregateRoot
{
private readonly List<OrderLine> _lines = [];
public IReadOnlyList<OrderLine> Lines => _lines;
public OrderStatus Status { get; private set; }
public Money Total { get; private set; }
private Order() { }
public static Order Place(CustomerId customerId, IEnumerable<OrderLine> lines)
{
var order = new Order
{
Status = OrderStatus.Pending,
Total = Money.Zero
};
foreach (var line in lines)
order.AddLine(line);
order.Raise(new OrderPlaced(order.Id, customerId));
return order;
}
public void AddLine(OrderLine line)
{
if (Status != OrderStatus.Pending)
throw new DomainException("Cannot modify a non-pending order.");
_lines.Add(line);
Total = Total.Add(line.Subtotal);
}
}
public sealed record Money(decimal Amount, string Currency)
{
public static readonly Money Zero = new(0, "GBP");
public Money Add(Money other) =>
Currency == other.Currency
? this with { Amount = Amount + other.Amount }
: throw new DomainException("Currency mismatch.");
}Testing strategy
Domain tests should read like executable business examples and run without infrastructure.
- Test aggregate creation, transitions, invariants, and illegal operations.
- Test value equality, normalization, and invalid construction.
- Assert domain events and ensure failed operations emit none.
- Use property-based tests for broad invariant spaces where valuable.
- Integration-test repository rehydration and optimistic concurrency.
- Test integration-event mapping and outbox delivery separately.
Security considerations
Domain models enforce business validity, but trusted identity and authorization still enter from application boundaries.
- Pass verified actor and tenant context to authorized use cases.
- Prevent direct mutation that bypasses aggregate rules.
- Avoid sensitive values in events, exceptions, and logs.
- Validate identifiers and context ownership before loading aggregates.
- Authorize cross-context commands at both caller and owner boundaries.
Performance and scalability
Aggregate size and consistency choices determine load cost, contention, and throughput.
- Keep aggregates small and reference others by identity.
- Use projections for reads instead of loading graphs.
- Measure transaction duration, conflicts, event volume, and rehydration cost.
- Avoid synchronous cross-context cascades.
- Partition hot aggregates or revisit boundaries when contention is structural.
Deployment and operations
Contexts and integration contracts must evolve without requiring a synchronized enterprise release.
- Use backward-compatible event and API contracts.
- Deploy schema changes with expand-contract migration.
- Persist outbox messages atomically with aggregate state.
- Monitor concurrency conflicts and event delivery per context.
- Provide replay, reconciliation, and poison-message runbooks.
Common problems and fixes
The model is mostly getters and setters.
Likely cause: Rules live in services.
Fix: Move invariants and transitions into domain behavior.
Aggregates load huge graphs.
Likely cause: Consistency boundaries follow navigation convenience.
Fix: Keep only immediately consistent state and reference other roots by ID.
The same term causes arguments.
Likely cause: Bounded contexts are implicit.
Fix: Define context-specific language and translation.
Events leak persistence entities.
Likely cause: Internal state was treated as a contract.
Fix: Map to minimal versioned integration events.
Concurrent changes overwrite each other.
Likely cause: Aggregate versioning is missing.
Fix: Use optimistic concurrency and retry only safe commands.
Every area uses elaborate DDD patterns.
Likely cause: Core and generic subdomains were not distinguished.
Fix: Invest modeling depth according to business differentiation.
Best practices
- Involve domain experts when naming concepts; code that uses business language is easier to validate and maintain.
- Keep aggregates small—an aggregate that owns too much becomes a bottleneck and a source of contention.
- Model domain events in past tense to describe what happened, not what should happen.
- Map bounded context relationships explicitly using context maps so cross-boundary dependencies are visible and intentional.
- Reference other aggregates by identity and coordinate workflows outside one transaction.
- Keep domain types free of transport, ORM, and vendor concerns.
- Separate internal domain events from stable integration contracts.
- Apply tactical DDD depth according to subdomain complexity and value.
Production checklist
- Domain experts and developers share a maintained ubiquitous language.
- Bounded contexts and ownership are documented.
- Aggregates are small consistency boundaries with one root.
- Invalid state is unrepresentable or rejected by behavior.
- Repositories load and save roots with concurrency protection.
- Domain and integration events are distinct.
- Outbox and idempotency protect delivery.
- Domain, persistence, contract, and reconciliation tests cover separate risks.
Common interview questions
What is the difference between an entity and a value object?
An entity has a unique identity that persists over time regardless of attribute changes; a value object is defined entirely by its attributes and has no meaningful identity of its own, so two value objects with the same attributes are interchangeable.
Why should an aggregate be kept small?
Aggregates are loaded and saved as a unit and act as a consistency boundary. A large aggregate increases lock contention, load time, and the risk of unrelated operations blocking each other.
What is a bounded context and why does it matter?
A bounded context is an explicit boundary within which a domain model is internally consistent. It matters because the same word—like 'customer'—can mean different things in different parts of a business, and mixing those meanings in one model creates confusion and fragile code.
What is an aggregate consistency boundary?
It is the smallest cluster of state that must satisfy invariants atomically through one root; other aggregates are referenced by identity.
Domain event or integration event?
A domain event is an internal model fact. An integration event is a stable external contract mapped and published reliably after commit.
When should a domain service be used?
When domain behavior spans concepts but naturally belongs to no single entity or value object.
When is DDD unnecessary?
When rules are simple, terminology is stable, and CRUD plus basic validation clearly solves the capability.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
DDD Subscriptions
A .NET 10 subscription domain demonstrating an aggregate consistency boundary, behavior-rich entities, validated value objects, ubiquitous language, invariants, and domain events.
- Run
dotnet run --project src/DddSubscriptions- Test
dotnet test DddSubscriptions.slnx