Skip to main content

Domain-Driven Design

Learning objectives
  • Classify subdomains as core, supporting or generic and decide where to invest, build or buy
  • Draw bounded contexts and a context map using ACL, OHS, published language, customer/supplier and conformist relationships
  • Design aggregates around true invariants and keep them small
  • Use entities, value objects, domain events, repositories and domain services correctly in Go
  • Run an event storming session and turn its output into contexts and aggregates
  • Model an e-commerce platform and a bank with DDD and defend the boundaries

TL;DR​

  • Strategic DDD decides where the boundaries are; tactical DDD decides how to model inside a boundary. Strategic matters more — a perfect aggregate in the wrong context is still wrong.
  • Core subdomains differentiate the business (invest, build in-house, best people); supporting are necessary but specific (build simply); generic are solved problems (buy or use open source).
  • A bounded context is the boundary inside which one model and one ubiquitous language are consistent. "Account" in the ledger and "account" in customer login are different concepts, and that is fine.
  • Context maps describe how contexts relate: customer/supplier, conformist, anti-corruption layer (ACL), open host service (OHS), published language, shared kernel, partnership, separate ways.
  • Aggregates are consistency boundaries: one transaction modifies one aggregate; reference other aggregates by ID; use domain events and eventual consistency between them.
  • Event storming is the fastest way to discover the domain with the business in the room: orange domain events on a timeline, then commands, policies, aggregates and boundaries.

Why it matters​

Bank and e-commerce systems are mostly domain complexity, not algorithmic complexity. A transfer touches limits, fees, FX, holds, ledger postings, sanctions screening and notifications; a checkout touches pricing, promotions, stock, payment, fraud and shipping. When the code does not reflect the domain, every change becomes archaeology, and the business and engineers talk past each other ("is a pending transaction posted or not?").

DDD is also how you justify service boundaries in an interview. "I split by bounded context: Ordering owns order lifecycle and its invariants; Payment owns money movement; they integrate through published events with an ACL on the payment provider" is a far stronger answer than "I made an order service and a payment service because that seemed natural".

Core concepts​

Subdomains: core, supporting, generic​

TypeDefinitionStrategyE-commerce exampleBank example
CoreWhere the business competes and winsBuild in-house, best engineers, rich domain modelPricing and promotions, search ranking, recommendations, seller logisticsCredit decisioning, product/pricing engine, fraud models, real-time payments experience
SupportingNecessary, specific to the business, not differentiatingBuild simply (CRUD, transaction scripts) or customizeSeller onboarding, returns handlingBranch operations tools, collateral management
GenericSolved problems, same for everyoneBuy / SaaS / open sourceEmail delivery, identity provider, tax calculation serviceGeneral ledger for corporate accounting, HR, document storage

Classification is a business decision and can change: for a payments startup, the ledger may be core; for a retailer, payments are generic (use a PSP). Interviewers like hearing that you spend complexity budget on the core and keep the rest boring.

Bounded contexts and ubiquitous language​

A bounded context is an explicit boundary — often one team, one codebase, one database — within which every term has exactly one meaning. The ubiquitous language is that shared vocabulary, used identically in conversations, docs, code and tests.

The same word means different things in different contexts, and trying to unify them produces a bloated "god model":

TermIn context AIn context B
AccountLedger: a balance-holding entity with postings and a normal balance sideIdentity: a login with credentials and MFA devices
OrderOrdering: a customer's purchase with lines, prices and lifecycleShipping: a consignment with parcels, weight and carrier
ProductCatalog: title, attributes, imagesInventory: a SKU with on-hand and reserved quantities
TransactionPayments: a payment instruction with status (initiated, accepted, settled)Ledger: a balanced set of journal entries

Each context has its own model of the overlapping concept, linked by identifiers and translated at the boundary.

Context maps​

A context map shows bounded contexts and the relationships between the teams that own them. Upstream (U) contexts affect downstream (D) ones.

PatternMeaningWhen you see it
PartnershipTwo teams succeed or fail together, coordinate closelyTwo new contexts co-developed for a launch
Shared kernelSmall shared model/code both teams own jointlyShared money/currency types; use sparingly
Customer/supplierDownstream's needs influence upstream's planningOrdering (customer) and Inventory (supplier) inside one company
ConformistDownstream adopts upstream's model as-is, no influenceIntegrating with a large vendor or the national switch's message format
Anti-corruption layer (ACL)Downstream translates upstream's model into its ownWrapping a core banking system or a payment provider's API
Open host service (OHS)Upstream offers a well-defined protocol for many consumersCatalog's public read API; Payments' integration API
Published languageA documented shared exchange formatISO 20022, ISO 8583, a company event schema catalog
Separate waysNo integration; duplicate if neededMarketing's own simple product list

Read it as: Payment protects its model from the PSP's model via an ACL; Ordering and Payment have a customer/supplier relationship (Ordering's needs drive Payment's API roadmap); Catalog publishes an open host service used by Search and Cart.

Anti-corruption layer in detail​

An ACL is a translation layer — adapters, facades and translators — that keeps an external or legacy model from leaking in. For a bank wrapping a vendor core:

The ACL maps vendor transaction codes to your PaymentType, vendor error codes to domain errors, and vendor account structures to your AccountRef. When you migrate off the core, you replace the ACL, not the Payments model. See Legacy Modernization & Migration.

Tactical building blocks​

Building blockIdentity?Mutable?PurposeExample
EntityYes, stable over timeYesSomething tracked through its lifecycleOrder, Account, Card
Value objectNo, defined by attributesNo (replace, don't modify)Describe and validate a conceptMoney, IBAN, Address, DateRange
AggregateRoot entity's identityYes, via the root onlyConsistency boundary for invariantsOrder with its OrderLines
Domain eventEvent IDNoA fact that happened in the domainOrderPlaced, FundsReserved
Repository——Load and save whole aggregates; collection-like interfaceOrderRepository
Domain service—StatelessDomain logic that does not belong to one entityFxConversionService, TransferPolicy
Application service—StatelessOrchestrates a use case: load, call domain, save, publishPlaceOrderHandler
Factory——Complex creation logicLoanApplicationFactory

Value objects are the most under-used building block. Money as a value object (amount in minor units + currency, arithmetic refuses mixed currencies) eliminates a whole class of bugs that float64 amounts cause.

Aggregates and invariants​

An invariant is a rule that must be true after every transaction ("an order's total equals the sum of its lines minus discounts"; "available balance never drops below the overdraft limit"). The aggregate is the smallest cluster of objects that must be consistent together to protect such invariants.

Vaughn Vernon's guidelines (from Implementing Domain-Driven Design):

  1. Model true invariants in consistency boundaries. Only group what must be consistent in the same transaction.
  2. Design small aggregates. Large aggregates cause lock contention and slow loads.
  3. Reference other aggregates by identity (CustomerID), not by object pointers.
  4. Use eventual consistency outside the boundary, via domain events.

Design questions that reveal aggregate boundaries:

  • Is "customer has at most 3 pending orders" an invariant of Order or of Customer? It spans many orders — either a policy checked with eventual consistency (accept, then flag) or a small dedicated aggregate (CustomerOrderQuota). Do not make Customer contain all its orders.
  • Must stock reservation and order placement be atomic? In a monolith maybe; across contexts, use a saga: OrderPlaced → reserve stock → StockReserved / StockReservationFailed → confirm or cancel.
  • Must a transfer debit and credit atomically? Within one ledger, yes — model a JournalEntry aggregate whose invariant is "sum of debits = sum of credits", posted in one transaction. Across banks, no — it is a process with clearing and settlement.

Domain events​

A domain event records something meaningful that happened, named in past tense in the ubiquitous language: OrderPlaced, PaymentAuthorized, CardBlocked, LimitExceeded. Aggregates record events as part of state changes; the application service persists the aggregate and the events together (outbox) and publishes them. See Event-Driven Architecture.

Event storming​

A workshop technique created by Alberto Brandolini. You need a long wall, sticky notes in fixed colours and the people who know the business.

Typical colour convention: orange domain events, blue commands, small yellow actors, large pale yellow aggregates, lilac policies ("whenever X, then Y"), pink external systems, green read models, red/magenta hot spots (questions, conflicts).

Levels:

  1. Big picture: everyone writes domain events on a timeline for the whole business flow (e.g. from "customer browsed" to "refund paid"). Find hot spots and pivotal events where responsibility changes — these suggest context boundaries.
  2. Process modelling: add commands, actors, policies, read models and external systems for one process.
  3. Software design: group commands and events around aggregates; draw bounded context lines.

Output: candidate bounded contexts, aggregates with their commands and events, a list of open questions, and a shared language.

Worked example: e-commerce​

ContextCore responsibilityKey aggregatesKey invariantsPublishes
CatalogProduct informationProduct, CategorySKU unique; required attributes per categoryProductPublished, ProductUpdated
CartPre-purchase intentCartQuantity ≥ 1; max lines; prices are snapshots marked as indicativeCartCheckedOut
OrderingOrder lifecycleOrderLines immutable after placement; total = lines − discounts + shipping; state transitions validOrderPlaced, OrderCancelled, OrderCompleted
PaymentMoney movement with PSPsPayment, RefundCaptured ≤ authorized; refunds ≤ captured; idempotent per keyPaymentAuthorized, PaymentCaptured, RefundIssued
ShippingFulfilment and deliveryShipment, ParcelA parcel has one active tracking number; cannot ship a cancelled orderShipmentDispatched, ShipmentDelivered

Note that Cart is not Ordering: a cart is a mutable, cheap, abandonable draft with indicative prices; an order is a commitment with final prices, legal and tax implications. Splitting them lets cart scale independently during a sale and lets ordering stay strict. Deeper dives: Cart & Checkout, Order Management.

Worked example: banking​

ContextResponsibilityAggregatesInvariants
AccountsProduct, ownership, status, limits of customer accountsAccount (status, product, holders, limits)Closed accounts cannot receive postings; limit changes need maker-checker
LedgerBalances and immutable postingsJournalEntry, LedgerAccountEvery entry balances (Σ debits = Σ credits); entries are never edited, only reversed; available balance respects overdraft limit
PaymentsPayment instructions and their lifecyclePayment (state machine), BeneficiaryState transitions valid (initiated → accepted → settled / rejected); idempotent per client request ID; daily limit respected
CardsCard lifecycle and authorizationsCard, AuthorizationBlocked card cannot authorize; authorization amount ≤ available + tolerance; clearing matches an authorization or is flagged

Key modelling decisions:

  • Accounts ≠ Ledger. Account metadata (product, owners, status) changes for business reasons; balances change through postings with strict accounting rules. Separating them keeps the ledger small, strict and fast. See Double-Entry Ledger Design.
  • Payments owns the process, Ledger owns the money. Payments never updates a balance directly; it asks Ledger to post a balanced journal entry.
  • Conformist to schemes and switches — you cannot negotiate ISO 8583 field semantics with Visa or the national switch, so model the boundary as conformist plus an internal translation to your own model.
  • ACL over the legacy core during modernization, so new contexts never speak the vendor's language.

Trade-offs​

ChoiceStrengthsWeaknessesChoose when
Rich domain model (aggregates, VOs)Invariants enforced in one place, expressive, testableMore design effort, learning curveCore subdomains with complex rules (pricing, ledger, credit)
Transaction script / CRUDFast, simpleRules scatter as complexity growsSupporting and generic subdomains
Small aggregates + eventual consistencyLow contention, scalableSagas, compensations, temporary inconsistencyMost cross-entity rules
Large aggregateStrong consistency across many objectsContention, slow loads, lock conflictsRarely; only when the invariant truly demands it
ACLProtects your model, eases migrationExtra code and latencyLegacy cores, vendor and third-party APIs
ConformistNo translation costUpstream model leaks everywhereUpstream is a standard you cannot change and fits well enough
Shared kernelNo duplication of key typesTight coupling between teamsTiny, stable concepts (Money, Currency)

In practice​

Value object and aggregate in Go:

package ordering

import (
"errors"
"fmt"
)

var (
ErrCurrencyMismatch = errors.New("currency mismatch")
ErrOrderNotDraft = errors.New("order is not in draft state")
ErrEmptyOrder = errors.New("order has no lines")
ErrInvalidQuantity = errors.New("quantity must be positive")
)

// Money is a value object: immutable, compared by value, minor units.
type Money struct {
amount int64
currency string
}

func NewMoney(amount int64, currency string) Money {
return Money{amount: amount, currency: currency}
}

func (m Money) Add(o Money) (Money, error) {
if m.currency != o.currency {
return Money{}, fmt.Errorf("%w: %s vs %s", ErrCurrencyMismatch, m.currency, o.currency)
}
return Money{amount: m.amount + o.amount, currency: m.currency}, nil
}

func (m Money) Times(n int) Money {
return Money{amount: m.amount * int64(n), currency: m.currency}
}

type Status string

const (
StatusDraft Status = "DRAFT"
StatusPlaced Status = "PLACED"
)

type OrderLine struct {
SKU string
Quantity int
UnitPrice Money
}

type OrderPlaced struct {
OrderID string
CustomerID string
Total Money
}

// Order is the aggregate root. All changes go through its methods,
// which protect the invariants and record domain events.
type Order struct {
id string
customerID string
status Status
lines []OrderLine
total Money
events []any
}

func NewOrder(id, customerID, currency string) *Order {
return &Order{id: id, customerID: customerID, status: StatusDraft, total: NewMoney(0, currency)}
}

func (o *Order) AddLine(sku string, qty int, price Money) error {
if o.status != StatusDraft {
return ErrOrderNotDraft
}
if qty <= 0 {
return ErrInvalidQuantity
}
total, err := o.total.Add(price.Times(qty))
if err != nil {
return err
}
o.lines = append(o.lines, OrderLine{SKU: sku, Quantity: qty, UnitPrice: price})
o.total = total
return nil
}

func (o *Order) Place() error {
if o.status != StatusDraft {
return ErrOrderNotDraft
}
if len(o.lines) == 0 {
return ErrEmptyOrder
}
o.status = StatusPlaced
o.events = append(o.events, OrderPlaced{OrderID: o.id, CustomerID: o.customerID, Total: o.total})
return nil
}

// PullEvents returns and clears recorded events; the application service
// saves them to the outbox in the same transaction as the order.
func (o *Order) PullEvents() []any {
ev := o.events
o.events = nil
return ev
}

// Repository loads and saves whole aggregates; implemented by an adapter.
type Repository interface {
Get(id string) (*Order, error)
Save(o *Order) error
}

Practical advice:

  • Start strategic. One afternoon of big-picture event storming with business people is worth weeks of tactical modelling.
  • Make the language visible in code: package names, type names and method names match the glossary (Place, not UpdateStatus(2)).
  • One aggregate per transaction is a guideline, not a law; inside a modular monolith you may update two aggregates atomically when the business truly needs it — but record that decision.
  • Bounded context ≠ microservice. A context can be a module in a monolith; a large context may be several services. Contexts are about models; services are about deployment.

Common pitfalls​

  • Anaemic domain model. Entities are data bags; all logic lives in "services". Symptom: the same invariant is checked (differently) in five handlers.
  • One model to rule them all. A single Customer class with 80 fields used by every team. Symptom: every change needs sign-off from five teams.
  • Giant aggregates. Customer containing all orders and payments. Symptom: lock contention and loading 10,000 rows to add one line.
  • Tactical DDD without strategic DDD. Perfect aggregates in a system with no clear contexts. Symptom: lots of patterns, same coupling.
  • Leaking external models. PSP status codes and vendor transaction codes appear in domain logic. Symptom: switching provider requires changes in core business code.
  • DDD everywhere. Rich models for a CRUD admin screen. Symptom: slow delivery on simple features, team fatigue.

Interview angle​

  • When designing any system, name the bounded contexts first and say which are core. Interviewers listen for "this is a generic subdomain, I'd use a vendor".
  • Be ready to define aggregate precisely — a consistency boundary for invariants, loaded and saved as a unit, referenced by ID — and to give an invariant from banking or e-commerce.
  • Expect: "Where would you put the rule that a customer can't exceed their daily transfer limit?" Good answer: identify it as an invariant across many payments, discuss a DailyLimit aggregate per customer-day with optimistic concurrency, or a reservation in the Accounts/Limits context, and the trade-off with eventual consistency.
  • Expect: "How do you integrate with the core banking system?" — ACL, plus the strangler fig if migrating.
  • Red flags: treating DDD as "entities and repositories"; one microservice per entity; no mention of ubiquitous language; using the vendor's model directly in new services.

Self-check​

1. How do you decide whether a subdomain is core, supporting or generic? Classify "payment processing" for a retailer and for a payments fintech.

Ask whether it differentiates the business (core), is specific but not differentiating (supporting), or is a solved problem shared across industries (generic). For a retailer, payment processing is generic or supporting — integrate a PSP. For a payments fintech, it is core — routing, authorization rates and settlement speed are their competitive advantage, so they build and invest.

2. Why is it acceptable for "Account" to mean different things in Identity and Ledger contexts?

Each bounded context has its own model and language; forcing one meaning produces a god model that serves no context well and couples teams. Within each context the term is unambiguous. The contexts link by identifiers (customer ID) and translate at their boundaries.

3. Explain the difference between an anti-corruption layer and a conformist relationship, with a bank example of each.

Conformist: the downstream adopts the upstream model as-is because it cannot influence it and translation is not worth it — e.g. a card authorization adapter that uses ISO 8583 field semantics directly at the scheme boundary. ACL: the downstream translates the upstream model into its own to avoid contamination — e.g. a Payments context wrapping a vendor core banking API so vendor transaction codes and account structures never enter the domain.

4. State Vernon's four aggregate design rules.
  • Model true invariants in consistency boundaries.
  • Design small aggregates.
  • Reference other aggregates by identity only.
  • Use eventual consistency (domain events) outside the boundary.
5. Scenario: the business says "a customer can have at most 3 unpaid orders". Where does this rule live?

It spans multiple Order aggregates, so it cannot be enforced inside one Order. Options: a small CustomerOrderQuota aggregate updated with optimistic concurrency when an order is placed or paid (strong consistency, contention per customer is low); or a policy check at placement against a read model, accepting a rare race and flagging/cancelling the extra order (eventual consistency). Ask the business how bad a 4th order is; that decides.

6. Why should Cart and Ordering usually be separate contexts?

They have different language, invariants and load profiles. A cart is a cheap, mutable, frequently abandoned draft with indicative prices and very high write volume during sales; an order is a commitment with final prices, tax and legal implications and a strict lifecycle. Separation lets cart scale and change freely while ordering stays strict and auditable.

7. What are the outputs of a big-picture event storming session, and how do they lead to bounded contexts?

A timeline of domain events across the business flow, hot spots (questions, conflicts), pivotal events where responsibility changes, actors and external systems, and a growing shared vocabulary. Clusters of events owned by the same people and language, separated by pivotal events (e.g. "Order placed", "Payment settled"), suggest bounded context boundaries.

🧠 Flashcards0/9 learned · 0 retries

Exercise​

Run a solo (or team) event storming for "customer transfers money to another bank via instant payment":

  1. On a timeline, write at least 15 domain events from "customer opens transfer screen" to "beneficiary bank confirms credit" and "statement updated", including failure paths (timeout, rejection, reversal).
  2. Add commands, actors, policies and external systems (national switch, fraud provider, core banking).
  3. Draw bounded contexts and a context map in Mermaid, labelling each relationship (ACL, conformist, customer/supplier, OHS).
  4. For the Payments and Ledger contexts, define aggregates with their invariants and the domain events they publish.
  5. Implement the JournalEntry aggregate in Go with a test proving unbalanced entries are rejected.

Done when: every invariant has exactly one aggregate that enforces it, and every external system sits behind an ACL or an explicit conformist boundary.

Further reading​

  • Domain-Driven Design: Tackling Complexity in the Heart of Software — Eric Evans (2003).
  • Implementing Domain-Driven Design — Vaughn Vernon (2013); Domain-Driven Design Distilled — Vaughn Vernon (2016).
  • Learning Domain-Driven Design — Vlad Khononov (O'Reilly, 2021). Very practical on subdomain classification.
  • Introducing EventStorming — Alberto Brandolini (Leanpub).
  • Vaughn Vernon, "Effective Aggregate Design" (three-part essay, dddcommunity.org).
  • Domain Modeling Made Functional — Scott Wlaschin (2018). Value objects and state machines as types.
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).