Domain-Driven Design
Model complex business domains with a shared language, bounded contexts and aggregates that protect invariants.
Advanced · about 6 hours · difficulty 4/5
Learn first: Design Patterns for Backend Code
Domain-Driven Design (DDD) is an approach for software where the hard part is the business logic, not the technology: insurance, logistics, banking, marketplaces. It gives you tools to model that logic together with domain experts.
Strategic design
- Ubiquitous language: developers and domain experts use the same terms, and those terms appear in the code. If the business says "policy" and "claim", your classes do too.
- Bounded contexts: a large domain is split into areas where each term has one precise meaning. "Customer" in billing (payment details) differs from "customer" in support (tickets). Each context has its own model, and often maps to a module or service.
- Context maps describe how contexts relate, including anti-corruption layers that translate another system's model so it does not leak into yours.
Tactical design
- Entities have identity (an order with an id); value objects are defined by their values and are immutable (
Money(100, "INR"), an address). - Aggregates group entities that must stay consistent together, with one aggregate root as the only entry point. Invariants ("an order total cannot be negative") are enforced inside the aggregate, and one transaction changes one aggregate.
- Domain events record things that happened ("OrderPlaced") and let other parts react.
- Repositories load and save whole aggregates; domain services hold logic that fits no single entity.
When DDD pays off
Rich, changing business rules and long-lived systems. For CRUD apps it is heavy ceremony; borrow the ubiquitous language and bounded contexts and skip the rest.
You are ready to move on when you can identify the bounded contexts of a familiar business, name one aggregate with its invariants, and explain why it should be modified in a single transaction.
Key concepts
- Ubiquitous language
- Bounded contexts and context maps
- Entities and value objects
- Aggregates and invariants
- Domain events
- Anti-corruption layer
- Event storming workshops
Mini project
Model an order-fulfilment domain: define two bounded contexts, an Order aggregate with invariants enforced in code, a Money value object and an OrderPlaced domain event, all covered by unit tests.
Check yourself
Why should a single transaction typically modify only one aggregate?
Free resources
- Domain Driven Design (Martin Fowler)
- Bounded Context (Martin Fowler)
- Using domain analysis to model microservices (Microsoft Learn)