Shelves / Software Architecture
SA·138
Domain-Driven Design
Designing software around the business domain: why DDD exists, strategic design (domain, core, supporting and generic subdomains, bounded contexts, ubiquitous language, context mapping with its relationship patterns, the anti-corruption layer, discovery with event storming and domain storytelling), and tactical design (entities, value objects, aggregates and aggregate roots with consistency boundaries and sizing rules, repositories, domain services, application services, domain events, factories, specifications), with a worked example implemented in Java, Kotlin, C#, Go, Rust, TypeScript and Haskell, plus where DDD is overkill.
Start here: put the business rules where they can't be skipped
Domain-driven design (DDD) is an approach to software where the code is organised around the business (its language, its rules, and the boundaries between its parts) rather than around database tables or screens. Its strategic half splits a large domain into bounded contexts (ordering, kitchen, delivery, billing), each with its own model and vocabulary. Its tactical half shapes the code inside a context, and its most useful idea is the aggregate: a cluster of objects that changes together and protects its own rules.
The same order, two ways
The tiffin centre's order has rules: at most 20 items; once paid, its contents can't change; refunds can never exceed what was paid.
Anemic model: the Order is a bag of data, and separate service functions change it. Each function is supposed to remember the rules. Two of them forgot one each:
def svc_remove(o, dish): # forgot: a paid order can't change
o.lines.pop(dish, None)
def svc_refund(o, amount): # forgot: refunds can't exceed what was paid
if o.status != "paid": raise DomainError("not paid")
o.refunded += amount
Rich aggregate: the data is private, and every change goes through a method on Order that checks the rules (add, remove, pay, refund all call guards such as _require_open()).
A machine that tries every sequence
Hypothesis's stateful testing generated random sequences of add, remove, pay and refund (300 runs of up to 20 steps), checking two rules after every step: refunds never exceed payment and a paid order's lines still add up to what was paid.
anemic model: Hypothesis found 2 distinct failures
add(dal, qty 1, ₹40) → pay() → remove(dal) AssertionError: assert 0 == 40 (paid ₹40 for an empty order)
add(dal, qty 1, ₹40) → pay() → refund(₹41) AssertionError: assert 41 <= 40 (refunded more than paid)
rich aggregate: 1 passed in 2.05 s
Each failure was shrunk to the shortest sequence that breaks a rule, three steps. In the anemic model, every new piece of code that touches an order (a support tool, a batch job, a new API) must remember every rule; one forgets, and the data is wrong. In the aggregate, the rules live in one place and nothing can bypass them.
The rest of the vocabulary
- Ubiquitous language: the same words in conversation and in code ("tiffin", "slot", "kitchen ticket"), within a bounded context.
- Entity (identity that persists: an order) vs value object (defined by its values, immutable: a
Money(₹120, INR)). - Domain event: something that happened, named in the past tense (
OrderPaid), published for other contexts (Volume 12, chapter 131). - Repository: loads and saves whole aggregates; one transaction changes one aggregate.
- Context map: how bounded contexts relate (customer–supplier, anticorruption layer, shared kernel, and so on).
How deep to go in domain-driven design
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain bounded contexts, ubiquitous language, entities, value objects and aggregates |
| L2 | Model an aggregate that enforces its invariants, with value objects and a repository |
| L3 | Explain aggregate sizing, consistency boundaries, domain events and context-mapping patterns |
| L4 | Find leaked invariants and wrong boundaries in an existing model, and refactor them |
| L5 | Lead strategic design: discover subdomains and contexts (event storming) and map their relations |
| L6 | Align team and system boundaries with domains across an organisation |
Why DDD
Domain-Driven Design (Eric Evans, 2003) is an approach to building software for complex business domains by putting a rich, shared understanding of the domain at the centre of the design. Its premise: in most business software, the hard part isn't the technology, it's the domain complexity: rules, exceptions, workflows, language and their evolution. Code that doesn't reflect the domain becomes a translation layer nobody fully understands.
DDD has two halves:
- Strategic design: how to divide a large domain into parts (subdomains and bounded contexts), how those parts relate (context maps), and where to invest effort (core domain). This shapes team boundaries, service boundaries and module boundaries (chapters 140, 141).
- Tactical design: building blocks for modelling inside one bounded context (entities, value objects, aggregates, repositories, domain events, services).
Strategic design matters more and is useful even when you never use the tactical patterns.
Strategic design
Domain and subdomains
The domain is the sphere of knowledge and activity the software serves (e-commerce, insurance, logistics, healthcare). Large domains decompose into subdomains, classified by their strategic value:
| Type | Definition | Investment | Example (food delivery) |
|---|---|---|---|
| Core domain | What differentiates the business; competitive advantage | Best people, custom software, deep modelling, DDD tactical patterns | Dispatch/matching, delivery-time prediction, restaurant ranking |
| Supporting subdomain | Necessary and specific to the business, but not differentiating | Custom but simpler software; good-enough models | Restaurant onboarding, menu management, partner payouts |
| Generic subdomain | Solved problems common to many businesses | Buy or use open source/SaaS | Identity, payments processing, email/SMS, accounting, search infrastructure |
This classification answers "where should we spend our best effort?" and "what should we build vs buy?" (chapter 142). Many organisations waste effort building generic subdomains (a custom auth system) while under-investing in the core.
Ubiquitous language
The ubiquitous language is a rigorous, shared vocabulary used by domain experts and developers in conversation, documents, tests and code, within a bounded context.
- If the business says "a booking is confirmed when the hold is converted", the code has
Booking,confirm(),Hold,convert(), notReservation,setStatus(2),TempRecord,process(). - Disagreements and ambiguities in the language reveal modelling problems; resolving them ("what exactly is an 'active' customer?") improves both the model and the business's understanding.
- The language is bounded: the same word can mean different things in different contexts, which is fine if contexts are explicit.
Bounded contexts
A bounded context is an explicit boundary within which a particular model and its ubiquitous language apply consistently. Inside it, every term has one meaning; across boundaries, the same real-world thing may be modelled differently.
The classic example: "Product" means different things to different parts of a retailer:
- In Catalogue: title, description, images, categories, attributes, SEO.
- In Pricing: list price, price rules, promotions, currency.
- In Inventory: SKU, warehouse locations, stock levels, reservations.
- In Shipping: dimensions, weight, hazardous-material flags.
Forcing one universal Product model to serve all of them produces a bloated, contradictory model that every team must coordinate on. DDD instead gives each context its own model, linked by identifiers and explicit translation.
Guidelines for finding boundaries:
- Look for language shifts: where the same word changes meaning, or where experts use different vocabulary.
- Look for different rates and reasons of change and different owners (teams, departments).
- Align with business capabilities (what the business does: price products, fulfil orders) rather than technical layers or data entities.
- Keep strongly consistent invariants within one context; cross-context consistency is eventual.
- A bounded context is a model boundary, often but not necessarily a deployment boundary: a modular monolith can contain several bounded contexts as modules (chapter 140); a microservice usually implements one bounded context (chapter 141). Avoid splitting one context across many services.
- Conway's law: system structure mirrors communication structure. Aligning bounded contexts with teams (the "inverse Conway manoeuvre", Team Topologies' stream-aligned teams) reduces coordination.
Context mapping
A context map documents the bounded contexts and the relationships between them, which are as much about team politics and power as about technology:
| Pattern | Relationship | When |
|---|---|---|
| Partnership | Two teams coordinate closely, succeed or fail together | Tightly related features delivered jointly |
| Shared Kernel | Two contexts share a small, jointly owned subset of the model (code/library/schema) | Rarely; high coordination cost |
| Customer–Supplier | Upstream (supplier) serves downstream (customer); downstream's needs influence upstream's priorities | Internal teams with a negotiated relationship |
| Conformist | Downstream adopts upstream's model as-is (no influence) | Upstream is a large external provider or a dominant internal platform |
| Anti-Corruption Layer (ACL) | Downstream translates upstream's model into its own via a dedicated layer | Upstream model is messy, legacy or foreign, and you must protect your model |
| Open Host Service (OHS) | Upstream offers a well-defined protocol/API for all consumers | Many consumers; avoid bespoke integrations |
| Published Language | A documented shared exchange format (often with OHS) | Industry standards (ISO 20022, HL7 FHIR), public event schemas |
| Separate Ways | No integration; contexts solve their needs independently | Integration costs more than duplication |
| Big Ball of Mud | Acknowledged area with no clear model boundaries | Legacy you must contain, not emulate |
Anti-corruption layer
An ACL is a translation layer (adapters, translators, facades) that converts another system's model and protocol into your context's model, so foreign concepts, naming and quirks don't leak into your domain:
// ACL: translating a legacy payment gateway's model into the Ordering context's language
// Legacy model (upstream): status codes as strings, amounts as decimal strings in paise
data class LegacyTxnResponse(val txnRef: String, val respCode: String, val amt: String, val narration: String?)
// Our model (downstream, Ordering context)
sealed interface PaymentOutcome {
data class Captured(val paymentId: PaymentId, val amount: Money) : PaymentOutcome
data class Declined(val reason: DeclineReason) : PaymentOutcome
data object Pending : PaymentOutcome
}
class LegacyPaymentAcl(private val client: LegacyGatewayClient) : PaymentGateway { // our port
override fun capture(orderId: OrderId, amount: Money): PaymentOutcome {
val resp = client.doTxn(merchantRef = orderId.value, amtPaise = amount.minor.toString())
return when (resp.respCode) {
"00" -> PaymentOutcome.Captured(PaymentId(resp.txnRef), Money.inr(resp.amt.toLong()))
"05", "51" -> PaymentOutcome.Declined(DeclineReason.fromLegacy(resp.respCode, resp.narration))
"09" -> PaymentOutcome.Pending
else -> throw UnexpectedGatewayResponse(resp.respCode)
}
}
}
ACLs are also the key tool in legacy migration (the strangler fig pattern, chapter 141): new contexts talk to the legacy system only through ACLs, so the legacy model never infects the new code.
Discovering the domain
Collaborative modelling techniques bring domain experts and engineers together:
- Event Storming (Alberto Brandolini): participants place domain events (orange sticky notes, past tense: "Order Placed", "Payment Captured", "Courier Assigned") on a long timeline, then add commands (blue), actors, policies ("whenever X happens, do Y"), external systems, read models, hot spots (pink: questions, conflicts) and finally aggregates and context boundaries. Big-picture sessions explore the whole business; design-level sessions detail one context. Online whiteboards work well.
- Domain Storytelling: domain experts tell concrete stories ("the dispatcher sees a new order, picks a courier, calls the restaurant…") drawn as pictographic sequences of actors, work objects and activities.
- Example Mapping and Specification by Example: rules illustrated by concrete examples, which become acceptance tests.
- Bounded context canvas and core domain charts (DDD Crew) for documenting and classifying contexts.
Tactical design
Inside a bounded context, tactical patterns help express the model in code.
Entities
An entity is an object defined by its identity and continuity over time, not by its attributes: a Customer remains the same customer when their address changes; two customers with the same name are different customers.
- Has a stable identifier (UUID/ULID, a natural business key, or a database-generated ID).
- Equality by identity.
- Has a lifecycle and usually mutable state, changed through behaviour-revealing methods (
order.ship(tracking), notorder.setStatus("SHIPPED")) that enforce rules.
Value objects
A value object is defined entirely by its attributes, has no identity, and is immutable: Money(4999, INR), Email, Address, DateRange, GeoPoint, Percentage, Quantity. Two value objects with equal attributes are interchangeable.
Value objects are the most under-used and most valuable tactical pattern:
- They validate on construction (an
Emailis always syntactically valid; aDateRangealways hasstart ≤ end), so invalid states can't exist. - They encapsulate behaviour (
money.add(other)checks currencies match;range.overlaps(other)). - They eliminate primitive obsession (passing raw
String,long,BigDecimalaround), making signatures self-documenting and preventing argument mix-ups (transfer(from, to, amount)with threelongs vs typed IDs). - They're side-effect free and easy to test.
// Java 25 records as value objects with validation and behaviour
public record Money(long minor, Currency currency) {
public Money {
Objects.requireNonNull(currency);
}
public static Money of(String amount, String currency) {
return new Money(new BigDecimal(amount).movePointRight(2).longValueExact(), Currency.getInstance(currency));
}
public Money plus(Money other) {
requireSameCurrency(other);
return new Money(Math.addExact(minor, other.minor), currency);
}
public Money times(int qty) { return new Money(Math.multiplyExact(minor, qty), currency); }
private void requireSameCurrency(Money o) {
if (!currency.equals(o.currency)) throw new IllegalArgumentException("currency mismatch");
}
}
public record DateRange(LocalDate start, LocalDate end) {
public DateRange {
if (end.isBefore(start)) throw new IllegalArgumentException("end before start");
}
public boolean overlaps(DateRange o) { return !start.isAfter(o.end) && !o.start.isAfter(end); }
}
// Kotlin: value classes for typed IDs (zero runtime cost) and data classes for compound values
@JvmInline value class OrderId(val value: UUID)
@JvmInline value class CustomerId(val value: UUID)
data class Quantity(val value: Int) {
init { require(value in 1..999) { "quantity must be 1..999" } }
}
fun transfer(from: AccountId, to: AccountId, amount: Money) // can't swap arguments by accident
// Rust: newtypes are idiomatic and free; constructors enforce invariants
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct OrderId(uuid::Uuid);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Quantity(u16);
impl Quantity {
pub fn new(v: u16) -> Result<Self, DomainError> {
if (1..=999).contains(&v) { Ok(Self(v)) } else { Err(DomainError::InvalidQuantity(v)) }
}
pub fn get(self) -> u16 { self.0 }
}
// TypeScript: branded types prevent mixing structurally identical primitives
type Brand<T, B extends string> = T & { readonly __brand: B };
export type OrderId = Brand<string, "OrderId">;
export type CustomerId = Brand<string, "CustomerId">;
export const OrderId = (s: string): OrderId => {
if (!/^ord_[0-9A-Za-z]{20}$/.test(s)) throw new Error("invalid order id");
return s as OrderId;
};
// placeOrder(customerId, orderId) with swapped arguments is now a type error
-- Haskell: newtypes + smart constructors; the constructor isn't exported (see ch. 135)
newtype Quantity = Quantity Int deriving (Eq, Ord, Show)
mkQuantity :: Int -> Either DomainError Quantity
mkQuantity n | n >= 1 && n <= 999 = Right (Quantity n)
| otherwise = Left (InvalidQuantity n)
Aggregates and aggregate roots
An aggregate is a cluster of entities and value objects treated as one unit for data changes, with a consistency boundary: all invariants inside the aggregate are guaranteed to hold after every transaction. Each aggregate has one aggregate root, the only entity outside code may reference and call; it controls all changes to the inside.
Example: an Order aggregate contains OrderLines and value objects (Money, ShippingAddress). Invariants: an order has at least one line; total equals the sum of lines; lines can't change after the order is paid; no more than 50 lines. Only Order methods (addLine, removeLine, pay) modify lines, so the invariants are checked in one place.
Aggregate design rules (Vaughn Vernon, Effective Aggregate Design):
- Model true invariants in consistency boundaries: put objects in the same aggregate only if a business rule requires them to be consistent immediately (within a transaction).
- Design small aggregates: large aggregates (a
Customercontaining all their orders) cause contention (concurrent updates conflict), slow loading and big transactions. Most aggregates should be a root plus a few value objects. - Reference other aggregates by identity, not object references:
OrderholdsCustomerId, notCustomer. This keeps boundaries clear, enables separate storage and scaling, and avoids lazy-loading surprises. - Use eventual consistency outside the boundary: one transaction modifies one aggregate; other aggregates react to domain events (in the same process after commit, or via an outbox to other contexts).
Concurrency: aggregates are the unit of optimistic concurrency (a version per aggregate; concurrent modifications conflict and retry, Vol. 12 ch. 129).
// Java: Order aggregate root enforcing invariants; lines are internal; events recorded for publication
public final class Order {
private static final int MAX_LINES = 50;
private final OrderId id;
private final CustomerId customerId; // reference by identity
private final List<OrderLine> lines = new ArrayList<>();
private OrderStatus status = OrderStatus.DRAFT;
private long version; // optimistic concurrency
private final List<DomainEvent> events = new ArrayList<>();
public Order(OrderId id, CustomerId customerId) { this.id = id; this.customerId = customerId; }
public void addLine(ProductId product, Quantity qty, Money unitPrice) {
requireStatus(OrderStatus.DRAFT);
if (lines.size() >= MAX_LINES) throw new DomainException("too many lines");
lines.stream().filter(l -> l.product().equals(product)).findFirst().ifPresentOrElse(
l -> l.increase(qty),
() -> lines.add(new OrderLine(product, qty, unitPrice)));
}
public void place(Clock clock) {
requireStatus(OrderStatus.DRAFT);
if (lines.isEmpty()) throw new DomainException("order has no lines");
status = OrderStatus.PLACED;
events.add(new OrderPlaced(id, customerId, total(), Instant.now(clock)));
}
public Money total() {
return lines.stream().map(OrderLine::subtotal).reduce(Money.zero(Currency.getInstance("INR")), Money::plus);
}
public List<OrderLine> lines() { return List.copyOf(lines); } // no external mutation
public List<DomainEvent> pullEvents() { var e = List.copyOf(events); events.clear(); return e; }
private void requireStatus(OrderStatus s) { if (status != s) throw new DomainException("order is " + status); }
}
// C#: aggregate root with private setters, read-only collection exposure, and domain events
public sealed class Order : AggregateRoot<OrderId>
{
private readonly List<OrderLine> _lines = new();
public CustomerId CustomerId { get; }
public OrderStatus Status { get; private set; } = OrderStatus.Draft;
public IReadOnlyList<OrderLine> Lines => _lines.AsReadOnly();
public Order(OrderId id, CustomerId customerId) : base(id) => CustomerId = customerId;
public void Place(TimeProvider time)
{
if (Status != OrderStatus.Draft) throw new DomainException($"order is {Status}");
if (_lines.Count == 0) throw new DomainException("order has no lines");
Status = OrderStatus.Placed;
Raise(new OrderPlaced(Id, CustomerId, Total, time.GetUtcNow()));
}
public Money Total => _lines.Aggregate(Money.Zero("INR"), (acc, l) => acc + l.Subtotal);
}
// Go: unexported fields + methods enforce invariants; package boundary = aggregate boundary
package ordering
type Order struct {
id OrderID
customerID CustomerID
lines []line
status Status
version int64
events []Event
}
func (o *Order) AddLine(p ProductID, q Quantity, price Money) error {
if o.status != Draft { return ErrNotDraft }
if len(o.lines) >= 50 { return ErrTooManyLines }
for i := range o.lines {
if o.lines[i].product == p { o.lines[i].qty = o.lines[i].qty.Add(q); return nil }
}
o.lines = append(o.lines, line{product: p, qty: q, unitPrice: price})
return nil
}
func (o *Order) Place(now time.Time) error {
if o.status != Draft { return ErrNotDraft }
if len(o.lines) == 0 { return ErrEmptyOrder }
o.status = Placed
o.events = append(o.events, OrderPlaced{OrderID: o.id, CustomerID: o.customerID, Total: o.Total(), At: now})
return nil
}
// Rust: the aggregate owns its lines; only methods mutate; events returned for publication
pub struct Order {
id: OrderId,
customer: CustomerId,
lines: Vec<OrderLine>,
status: Status,
version: u64,
}
impl Order {
pub fn place(&mut self, now: DateTime<Utc>) -> Result<OrderPlaced, OrderError> {
if self.status != Status::Draft { return Err(OrderError::NotDraft(self.status)); }
if self.lines.is_empty() { return Err(OrderError::Empty); }
self.status = Status::Placed;
Ok(OrderPlaced { order: self.id, customer: self.customer, total: self.total(), at: now })
}
pub fn total(&self) -> Money { self.lines.iter().map(OrderLine::subtotal).sum() }
pub fn lines(&self) -> &[OrderLine] { &self.lines } // read-only borrow
}
-- Haskell / functional DDD: the aggregate is an immutable value; transitions are total functions
data Order = Order { orderId :: OrderId, customer :: CustomerId, lines :: NonEmpty OrderLine, status :: Status }
placeOrder :: UTCTime -> DraftOrder -> Either OrderError (Order, OrderPlaced)
placeOrder now draft = case draftLines draft of
[] -> Left EmptyOrder
(l : ls) -> let o = Order (draftId draft) (draftCustomer draft) (l :| ls) Placed
in Right (o, OrderPlaced (orderId o) (customer o) (orderTotal o) now)
-- Types make illegal states unrepresentable: a placed Order has a NonEmpty list of lines.
Scott Wlaschin's Domain Modeling Made Functional shows how algebraic data types express the domain precisely: workflows as functions from input types to output types, states as separate types (UnvalidatedOrder → ValidatedOrder → PricedOrder), and errors as explicit types.
Repositories
A repository provides collection-like access to aggregates: load an aggregate by ID, save it, perhaps query a few domain-meaningful ways. It hides persistence details behind a port defined in the domain (chapter 136, DIP).
- One repository per aggregate root, not per table/entity (there's no
OrderLineRepository). - Methods speak the domain language (
findPendingOlderThan(duration)) rather than exposing generic query builders. - Loads and saves whole aggregates atomically, handling optimistic concurrency.
- Read-heavy queries for screens and reports don't need to go through aggregates: use separate query services/read models (CQRS-lite, Vol. 12 ch. 127).
public interface OrderRepository { // domain port
Optional<Order> find(OrderId id);
void save(Order order); // insert or update with version check
List<Order> findPlacedBefore(Instant cutoff, int limit);
}
ORM caveat: JPA/Hibernate, Entity Framework and similar map aggregates conveniently, but encourage anemic models and leaky lazy loading; keep mappings simple, avoid bidirectional associations across aggregate boundaries, or map to separate persistence models with explicit translation when the domain model must stay clean.
Domain services
A domain service holds domain logic that doesn't naturally belong to a single entity or value object, typically an operation involving several aggregates or a domain concept that is a verb: PricingService.quote(cart, customer, promotions), FundsTransferService, RoutePlanner. Domain services are stateless and expressed in the ubiquitous language. Don't move all logic into services (that creates an anemic domain model, where entities are just data bags and services do everything: Fowler's anti-pattern).
Application services
Application services (use cases, command handlers) orchestrate a single use case: load aggregates via repositories, call domain methods/services, save, publish events, handle transactions and authorisation. They contain no business rules themselves; they coordinate.
// Application service: one use case; transaction and event publication at this layer
@Service
public class PlaceOrderHandler {
private final OrderRepository orders;
private final PricingService pricing; // domain service
private final DomainEventPublisher events;
private final Clock clock;
@Transactional
public OrderId handle(PlaceOrderCommand cmd) {
Order order = new Order(OrderId.newId(), cmd.customerId());
for (var item : cmd.items()) {
order.addLine(item.productId(), item.quantity(), pricing.unitPrice(item.productId(), cmd.customerId()));
}
order.place(clock);
orders.save(order);
events.publish(order.pullEvents()); // e.g. into an outbox in the same transaction
return order.id();
}
}
// TypeScript (NestJS-style or plain): use case as a function with injected ports
export const placeOrder = (deps: { orders: OrderRepo; pricing: Pricing; outbox: Outbox; clock: Clock; tx: Tx }) =>
async (cmd: PlaceOrderCommand): Promise<OrderId> =>
deps.tx(async () => {
const order = Order.draft(newOrderId(), cmd.customerId);
for (const item of cmd.items) {
order.addLine(item.productId, item.qty, await deps.pricing.unitPrice(item.productId, cmd.customerId));
}
const placed = order.place(deps.clock.now());
await deps.orders.save(order);
await deps.outbox.add(placed);
return order.id;
});
Domain events
A domain event records something meaningful that happened in the domain (OrderPlaced, PaymentCaptured, CourierAssigned), named in past tense in the ubiquitous language. Uses:
- Decoupling within a context: side effects (send confirmation, update loyalty points) react to events instead of being hard-coded into the aggregate or use case.
- Eventual consistency between aggregates: one transaction per aggregate; others react to events.
- Integration between contexts: published (via outbox) as integration events for other bounded contexts (Vol. 12 ch. 131).
- Audit and event sourcing.
Aggregates record events; the application layer publishes them after (or atomically with) the commit.
Factories and specifications
- Factories encapsulate complex creation of aggregates (from several inputs, or reconstitution from persistence) so constructors stay simple and invariants hold from birth (chapter 137).
- Specifications encapsulate business rules as composable predicate objects (
isEligibleForFreeShipping.and(isNotFlagged)), reusable for validation, selection and querying.
Layering inside a bounded context
DDD is commonly combined with hexagonal/clean architecture (chapter 139): the domain layer (entities, value objects, aggregates, domain services, domain events, repository interfaces) has no dependencies on frameworks; the application layer (use cases) orchestrates; adapters (web controllers, persistence, messaging) implement ports and depend inward.
When DDD is overkill
DDD's tactical patterns and modelling effort pay off for complex, evolving core domains. They're overkill for:
- CRUD applications with little business logic (admin panels, simple catalogues): use straightforward data-centric designs.
- Generic subdomains you should buy rather than build.
- Prototypes and short-lived tools.
- Teams without access to domain experts (the collaboration is the point).
Strategic DDD (subdomains, bounded contexts, ubiquitous language, context maps) remains valuable for almost any system of significant size, because it drives sensible module, service and team boundaries.
Common failure modes: applying all tactical patterns everywhere ("DDD-lite" boilerplate without modelling); giant aggregates; anemic models with all logic in services; bounded contexts drawn around data entities ("customer service", "product service") rather than capabilities; one shared "canonical data model" across contexts.
Lab: invariants under random command sequences
Hypothesis 6.170 with RuleBasedStateMachine on the lab machine (Python 3.13). The machine applies four commands in random order with random arguments, swallows DomainError (a rejected command is correct behaviour), and checks two invariants after every step. 300 sequences of up to 20 steps per run.
Experiment 1: anemic model versus aggregate
class OrderMachine(RuleBasedStateMachine):
@rule(d=dishes, q=st.integers(1, 8), p=st.integers(40, 200))
def add(self, d, q, p): ...
@rule(d=dishes)
def remove(self, d): ...
@rule()
def pay(self): ...
@rule(a=st.integers(1, 500))
def refund(self, a): ...
@invariant()
def refunds_never_exceed_payment(self): assert self.o.refunded <= self.o.paid
@invariant()
def paid_orders_keep_their_total(self): ...
| Model | Result | Shrunk counterexamples |
|---|---|---|
| anemic (data + service functions) | 2 distinct failures in 1.78 s | add(dal,1,40) → pay() → remove(dal): assert 0 == 40; add(dal,1,40) → pay() → refund(41): assert 41 <= 40 |
aggregate (Order methods with guards) |
1 passed in 2.05 s | — |
Hypothesis reports all distinct failures (as an ExceptionGroup) and shrinks each to a minimal sequence. Writing the same tests by hand means guessing the dangerous orderings; the state machine explores them. For Java, jqwik's stateful testing and for TypeScript fast-check's model-based testing do the same.
Experiment 2: what the aggregate looks like
class Order:
MAX_ITEMS = 20
def add(self, dish, qty, price):
self._require_open()
if self.item_count() + qty > self.MAX_ITEMS: raise DomainError("max 20 items")
...
def refund(self, amount):
if self.status != "paid": raise DomainError("not paid")
if self.refunded + amount > self.paid: raise DomainError("refund exceeds payment")
self.refunded += amount
Three design rules make it work: state is private (_lines), every mutation is a method named in the domain's language, and each method checks all the invariants it could affect before changing anything. In persistence, the aggregate is loaded and saved as a whole by a repository, and concurrent changes are serialised with an optimistic version column (Volume 12, chapter 129), so two clerks can't each issue a refund that is individually valid but together exceeds the payment.
Experiment 3: sizing the aggregate
Should the kitchen's daily capacity (at most 200 thalis per slot) live inside Order? No: it spans all orders, so making it an invariant of one aggregate would mean locking every order for every change. Options, in order of preference: make it its own small aggregate (SlotCapacity, reserved by a conditional update), or accept eventual consistency and compensate (over-booked orders get a polite cancellation). Rule of thumb from Vaughn Vernon: design small aggregates, reference other aggregates by ID, and use domain events for rules that cross them.
Try it yourself
- Add an invariant "item count never exceeds 20" to the state machine. Does either model break it?
- Give the anemic model a third service function,
svc_change_qty, that forgets the 20-item rule, and watch Hypothesis find it. - Add a
versionfield toOrderand a fake repository that rejects stale saves; model two concurrent refunds in the state machine. - Run a 30-minute event-storming session (sticky notes for domain events, commands, aggregates) for tiffin delivery and draw the bounded contexts that emerge.
Revision sheet: domain-driven design
Key ideas
- Strategic design: core, supporting and generic subdomains; invest design effort in the core; buy or simplify the rest.
- Bounded contexts with their own ubiquitous language; one model per context; context maps describe relationships (partnership, shared kernel, customer–supplier, conformist, anticorruption layer, open host service, published language, separate ways).
- Tactical design: entities, value objects, aggregates (root, invariants, small, reference others by ID), domain services, domain events, repositories, factories.
- One aggregate per transaction; cross-aggregate rules via events and eventual consistency.
- Discovery: event storming, domain storytelling, example mapping with domain experts.
- Architecture fit: hexagonal/clean architecture keeps the domain free of infrastructure (chapter 139); contexts map to modules (140) or services (141).
Numbers to remember
- Lab: Hypothesis found 2 invariant violations in the anemic model with 3-step counterexamples; the aggregate passed 300 sequences.
Pitfalls
- Anemic models with rules scattered across services.
- Huge aggregates that lock too much and contend.
- One "enterprise model" shared across contexts.
- DDD ceremony for CRUD-only or generic subdomains.
- Tables-first design leaking database structure into the domain.
- Contexts that share databases, making boundaries fiction.
Glossary
- Core domain: where the business differentiates.
- Aggregate root: the only entry point for changes to an aggregate.
- Anticorruption layer: translation layer protecting your model.
- Event storming: workshop technique for discovering domain events and boundaries.
- Domain service: domain logic that doesn't belong to one entity.