Domain-Driven Design
- 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
| Type | Definition | Strategy | E-commerce example | Bank example |
|---|---|---|---|---|
| Core | Where the business competes and wins | Build in-house, best engineers, rich domain model | Pricing and promotions, search ranking, recommendations, seller logistics | Credit decisioning, product/pricing engine, fraud models, real-time payments experience |
| Supporting | Necessary, specific to the business, not differentiating | Build simply (CRUD, transaction scripts) or customize | Seller onboarding, returns handling | Branch operations tools, collateral management |
| Generic | Solved problems, same for everyone | Buy / SaaS / open source | Email delivery, identity provider, tax calculation service | General 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":
| Term | In context A | In context B |
|---|---|---|
| Account | Ledger: a balance-holding entity with postings and a normal balance side | Identity: a login with credentials and MFA devices |
| Order | Ordering: a customer's purchase with lines, prices and lifecycle | Shipping: a consignment with parcels, weight and carrier |
| Product | Catalog: title, attributes, images | Inventory: a SKU with on-hand and reserved quantities |
| Transaction | Payments: 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.
| Pattern | Meaning | When you see it |
|---|---|---|
| Partnership | Two teams succeed or fail together, coordinate closely | Two new contexts co-developed for a launch |
| Shared kernel | Small shared model/code both teams own jointly | Shared money/currency types; use sparingly |
| Customer/supplier | Downstream's needs influence upstream's planning | Ordering (customer) and Inventory (supplier) inside one company |
| Conformist | Downstream adopts upstream's model as-is, no influence | Integrating with a large vendor or the national switch's message format |
| Anti-corruption layer (ACL) | Downstream translates upstream's model into its own | Wrapping a core banking system or a payment provider's API |
| Open host service (OHS) | Upstream offers a well-defined protocol for many consumers | Catalog's public read API; Payments' integration API |
| Published language | A documented shared exchange format | ISO 20022, ISO 8583, a company event schema catalog |
| Separate ways | No integration; duplicate if needed | Marketing'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 block | Identity? | Mutable? | Purpose | Example |
|---|---|---|---|---|
| Entity | Yes, stable over time | Yes | Something tracked through its lifecycle | Order, Account, Card |
| Value object | No, defined by attributes | No (replace, don't modify) | Describe and validate a concept | Money, IBAN, Address, DateRange |
| Aggregate | Root entity's identity | Yes, via the root only | Consistency boundary for invariants | Order with its OrderLines |
| Domain event | Event ID | No | A fact that happened in the domain | OrderPlaced, FundsReserved |
| Repository | — | — | Load and save whole aggregates; collection-like interface | OrderRepository |
| Domain service | — | Stateless | Domain logic that does not belong to one entity | FxConversionService, TransferPolicy |
| Application service | — | Stateless | Orchestrates a use case: load, call domain, save, publish | PlaceOrderHandler |
| Factory | — | — | Complex creation logic | LoanApplicationFactory |
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):
- Model true invariants in consistency boundaries. Only group what must be consistent in the same transaction.
- Design small aggregates. Large aggregates cause lock contention and slow loads.
- Reference other aggregates by identity (
CustomerID), not by object pointers. - 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 makeCustomercontain 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
JournalEntryaggregate 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:
- 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.
- Process modelling: add commands, actors, policies, read models and external systems for one process.
- 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
| Context | Core responsibility | Key aggregates | Key invariants | Publishes |
|---|---|---|---|---|
| Catalog | Product information | Product, Category | SKU unique; required attributes per category | ProductPublished, ProductUpdated |
| Cart | Pre-purchase intent | Cart | Quantity ≥ 1; max lines; prices are snapshots marked as indicative | CartCheckedOut |
| Ordering | Order lifecycle | Order | Lines immutable after placement; total = lines − discounts + shipping; state transitions valid | OrderPlaced, OrderCancelled, OrderCompleted |
| Payment | Money movement with PSPs | Payment, Refund | Captured ≤ authorized; refunds ≤ captured; idempotent per key | PaymentAuthorized, PaymentCaptured, RefundIssued |
| Shipping | Fulfilment and delivery | Shipment, Parcel | A parcel has one active tracking number; cannot ship a cancelled order | ShipmentDispatched, 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
| Context | Responsibility | Aggregates | Invariants |
|---|---|---|---|
| Accounts | Product, ownership, status, limits of customer accounts | Account (status, product, holders, limits) | Closed accounts cannot receive postings; limit changes need maker-checker |
| Ledger | Balances and immutable postings | JournalEntry, LedgerAccount | Every entry balances (Σ debits = Σ credits); entries are never edited, only reversed; available balance respects overdraft limit |
| Payments | Payment instructions and their lifecycle | Payment (state machine), Beneficiary | State transitions valid (initiated → accepted → settled / rejected); idempotent per client request ID; daily limit respected |
| Cards | Card lifecycle and authorizations | Card, Authorization | Blocked 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
| Choice | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Rich domain model (aggregates, VOs) | Invariants enforced in one place, expressive, testable | More design effort, learning curve | Core subdomains with complex rules (pricing, ledger, credit) |
| Transaction script / CRUD | Fast, simple | Rules scatter as complexity grows | Supporting and generic subdomains |
| Small aggregates + eventual consistency | Low contention, scalable | Sagas, compensations, temporary inconsistency | Most cross-entity rules |
| Large aggregate | Strong consistency across many objects | Contention, slow loads, lock conflicts | Rarely; only when the invariant truly demands it |
| ACL | Protects your model, eases migration | Extra code and latency | Legacy cores, vendor and third-party APIs |
| Conformist | No translation cost | Upstream model leaks everywhere | Upstream is a standard you cannot change and fits well enough |
| Shared kernel | No duplication of key types | Tight coupling between teams | Tiny, 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, notUpdateStatus(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
Customerclass with 80 fields used by every team. Symptom: every change needs sign-off from five teams. - Giant aggregates.
Customercontaining 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
DailyLimitaggregate 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.
Exercise
Run a solo (or team) event storming for "customer transfers money to another bank via instant payment":
- 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).
- Add commands, actors, policies and external systems (national switch, fraud provider, core banking).
- Draw bounded contexts and a context map in Mermaid, labelling each relationship (ACL, conformist, customer/supplier, OHS).
- For the Payments and Ledger contexts, define aggregates with their invariants and the domain events they publish.
- Implement the
JournalEntryaggregate 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.
Related
- Microservices Patterns — turning contexts into services.
- Clean & Hexagonal Architecture — structuring code inside a context.
- Event-Driven Architecture, CQRS & Event Sourcing — domain events between aggregates and contexts.
- Double-Entry Ledger Design — the Ledger context in depth.
- Core Banking Concepts — vocabulary for the banking example.
- E-commerce Platform Overview — the e-commerce contexts at platform level.
- Order Management & State Machines — the Ordering context's lifecycle.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).