Domain-Driven Design
A visual companion for learning domain-driven design: strategic and tactical design, shown on one running webshop.
Click the image to enter
Strategic design: Where the boundaries go
Every piece of software serves a business. The problem space is that business and the parts it is made of, the subdomains. You discover them by learning how the business works. The solution space is the software, split into models with clear boundaries, the bounded contexts. You design them, and they could be designed differently. Strategic design is deciding where those boundaries go.
Subdomains: Core, supporting and generic
Not every part of the business deserves the same effort. Each subdomain gets a type: core parts are built with care, supporting parts are built simply, and generic parts are problems others have already solved, so they are rarely worth inventing: buy, rent, use open source or outsource, whichever fits. Select a part of the map to see why.
Webshop domain
The three subdomain types
- Core — Build it with care. What sets this business apart from its competitors. It gets the best people, the deepest model and close work with the domain experts, and it is never bought off the shelf.
- Supporting — Build it simply. Needed for the core to work, but not why customers choose the shop. It is built in-house when nothing ready-made fits, with a plain model and no more effort than it needs.
- Generic — Don’t invent it. A problem every business has, and one that others have already solved well. It is rarely worth inventing: buy it, rent it as a service, use open source or outsource it, whichever fits, and fit the shop around it.
The subdomains of the webshop
Selling — Core subdomain, served by the Sales bounded context.
Turning visitors into orders is how the shop makes money, and the checkout is where it competes on convenience.
Carts, orders and checkout get a carefully modelled design of their own, shaped together with the people who run the shop and refined as they learn.
Pricing and discounts — Core subdomain, served by the Pricing bounded context.
Campaigns and price rules are what set this shop apart from the one next door.
Price rules change with every campaign, so they get a rich, well-tested model that can take a new kind of discount without being rewritten.
Product information — Supporting subdomain, served by the Catalog bounded context.
The shop needs good product pages, but no customer picks a shop for how its catalogue is stored.
A plain model that stores and edits products, texts and images is enough. There is little to invent, so it should not take the best people.
Delivery — Supporting subdomain, served by the Shipping bounded context.
Parcels must go out correctly, but the carriers do the hard part.
A small model of shipments and parcels that books the carrier and follows the tracking. The carrier’s own systems do the heavy lifting.
Payments and invoicing — Generic subdomain, served by the Billing bounded context.
Every shop does it the same way, so it is bought from a payment provider rather than invented.
The payment provider’s service is used as it is. The shop writes only the thin glue that creates invoices and records what has been paid.
Ubiquitous language: One word, many meanings
The ubiquitous language is the one precise language that the domain experts, the team and the code share inside a bounded context. It is not a glossary handed down: the domain experts and the team work it out together in conversation, sharpen it as they learn, and use it everywhere, in meetings, documentation, tests and code. The same word can mean something else in the next context, and that is fine: the boundary keeps each meaning intact. Pick a word to see what it means behind each boundary.
What it costs
“Product” in each bounded context
Catalog: A description with images that shoppers browse. Editors write it, and it stays online until they take it down.
productIdname— edited at any timedescriptionimages
Pricing: Something with exactly one current price, which a campaign may discount for a while.
productIdprice— the current pricediscount— from a running campaign
Sales: A ProductId and a price on an order line. Both are fixed at the moment the customer orders.
productIdname— as the customer saw itprice— fixed when orderedquantity
Shipping: Something with a weight and a size that must fit in a parcel.
productIdweightsize
“Customer” in each bounded context
Sales: The person who places orders. They need a delivery address before they can place one.
customerIdnameemaildeliveryAddress
Shipping: A name and an address on a parcel. Shipping does not care who paid.
recipientNameaddress— where the parcel goesphone— for the driver
Billing: Whoever pays the invoice. That can be a company, not the person who clicked Buy.
payerNameaddress— printed on the invoicevatNumber
“Order” in each bounded context
Sales: A cart the customer has placed: its lines, its total and its status. A placed order can’t be changed.
orderIdlinestotalstatus— draft or placed
Shipping: Something to pack and send. Shipping knows the order only by its id, and turns it into a shipment of parcels.
orderIddeliveryAddressparcelsstatus— packed or dispatched
Billing: An amount to charge. The card is only charged once the goods are on their way.
orderIdtotal— must match Sales to the centinvoiceLinesstatus— unpaid or paid
Without boundaries: one shared “product”
What every context really shares
productId— The one thing every context really shares. Pointing at a product by its id needs no shared model.
What clashes
name— Catalog editors rename products. Sales must keep the name the customer saw, or old orders change on their own.price— Pricing means today’s price. Sales means the price on the day of the order. One field can’t hold both.
What it costs
- Every change to Product needs all four teams to agree.
- Shipping loads descriptions and images just to weigh a parcel.
- Nobody can tell which price a line of code means without asking.
Bounded contexts: A model is only true inside its boundary
A bounded context is a boundary around one model and one language. It is usually owned by one team, with its own code and its own data. Inside the boundary every word means one thing. Everything outside has to pass a checkpoint. Point at, tap or tab to any part of the Sales context below to see what it is.
The Sales boundary
A bounded context is a boundary around one model and one language. Inside the Sales boundary, Order, Customer and Product each mean exactly one thing. One team owns what is inside, together with its code and its data. Outside the boundary the same words may mean something else, and that is fine.
Nothing crosses the boundary except through a checkpoint.
Inside the boundary
Team: Checkout team
One team owns everything inside the boundary. It can change the model, the code and the tables without asking anyone, as long as its checkpoints keep working. It works closely with the people who run online sales, so the model follows how they talk.
Who is in it
- Developers and a tester
- The head of online sales, as domain expert
Language: The Sales language
The words the team, its domain expert and its code all use, each with one meaning inside this boundary. They are worked out together in conversation and change as the team learns: a new word in a meeting soon shows up in the code and the tests. When someone in Sales says Order, nobody has to ask which one.
Words and what they mean here
- Cart an order that is still a draft
- Order a cart the customer has placed
- Customer the person who places orders
- Product a ProductId and a price on an order line
Model: Order and Customer
The team’s understanding of selling: not just the words, but what happens to them, the rules they obey, how they relate and which events they cause. It is found by working through real cases with the domain expert, for example in an EventStorming workshop. It only has to be true inside this boundary: here the price on an order line is fixed when the customer orders, whatever Pricing does later.
Rules it keeps
- Order — A placed order can’t be changed.
- Customer — A customer needs a delivery address before placing an order.
Code: The Sales codebase
The code speaks the language: its classes are called Order and PlaceOrder, the same words the domain expert uses. It is built, tested and deployed on its own, and no other context imports it.
Some of what is in it
- PlaceOrder
- Order
- OrderLine
- Customer
- OrderRepository
Database: The Sales database
Sales keeps its own tables. No other context reads or writes them. When Shipping needs to know about an order, it hears about it through a checkpoint, not by querying these tables.
Tables
- orders
- order_lines
- customers
Checkpoints
Product lookup
When a customer adds something to the cart, Sales asks Catalog for the product’s name through this checkpoint. The order line keeps only the ProductId, a reference by id, and a copy of the name the customer saw. Catalog’s own Product model never comes in.
Price lookup
Sales asks Pricing for today’s price and fixes it on the order line. Pricing can change prices as often as it likes, but it cannot reach in and change the price of an order that is already placed.
OrderPlaced
When an order is placed, Sales announces it through this checkpoint. Shipping and Billing hear the event and do their own work with it. They never see the Order model itself.
PaymentReceived
Billing tells Sales that an order has been paid. Sales decides for itself what that means for its Order. Billing never changes an order directly.
Outside the boundary
Catalog
Catalog has its own Product: a description with images that editors change at any time. Sales never sees that model. It reaches Catalog only through the Product lookup checkpoint.
Pricing
Pricing owns prices and discount campaigns, with a model and a team of its own. It does not reach into Sales; Sales asks it for a price through the Price lookup checkpoint.
Shipping
Shipping has its own Order: something to pack and send. It cannot read the Sales tables, so it learns about new orders only when OrderPlaced comes through the checkpoint.
Billing
Billing has its own Customer: whoever pays the invoice. It hears OrderPlaced, and it tells Sales about payments through the PaymentReceived checkpoint.
Context map: How the contexts relate
A context map shows every bounded context in a system on one map, and how each pair of them relates. Each line is a relationship between two models and the teams behind them. In many of them one side is upstream: its model and its decisions influence the downstream side. The patterns describe how the two sides handle that influence. Select a line to see why it was chosen here.
A context map is not an API or data-flow diagram, and not a C4 diagram either: it shows how models influence each other and who gets to decide. It can show the relationships as they are today, or as the teams want them to be, which makes it a good starting point for a conversation about where to go next.
Highlight a pattern
Relationships
The relationship patterns
Partnership
Two teams that succeed or fail together plan and release together.
When to use it. When two teams can only reach their goals together and can work closely: they plan together, release together and fix a broken integration together straight away. It takes a lot of coordination, so keep it for pairs that really do move in step.
Shared kernel
A small piece of model is owned jointly and changed only by agreement.
When to use it. When a small, stable piece of model must mean exactly the same on both sides. Keep it tiny: every change to it needs both teams, so a kernel that grows turns into a bottleneck.
Customer–supplier
The downstream team asks; the upstream team plans its needs into its work.
When to use it. When one team depends on another that is willing to listen. The downstream customer says what it needs, the upstream supplier plans it in, and shared tests keep the promise from breaking.
Conformist
The downstream team simply adopts the upstream model as it is.
When to use it. When the upstream side will not change for you and its model is good enough to use. Taking it as it is saves the cost of translating. If it would bend your own model out of shape, build an anticorruption layer instead.
Anticorruption layer
The downstream team translates a foreign model at the boundary so it never leaks in.
When to use it. When the upstream model is foreign, messy or likely to change, and you cannot influence it. The translation sits at your own boundary, so your model stays clean and the upstream system can be replaced later.
Open host service
The upstream team offers one well-defined service that any context can use on the same terms.
When to use it. When several contexts need the same thing from you. Instead of a custom integration for each of them, offer one stable, documented service that they all use.
Published language
A documented, versioned format that both sides agree to speak.
When to use it. When information crosses between contexts that should not know each other’s models, often as events or through an open host service. Both sides translate to and from the published format, and it changes only in new versions.
Separate ways
Integrating costs more than it gives, so the two contexts don’t connect at all.
When to use it. When connecting two contexts would cost more than it returns. Each side solves its own needs, even if that means a little duplication.
The relationships on the map
Sales and Pricing
Sales and Pricing, neither upstream. Partnership.
A new discount only works when the cart and the price rules change together, so the two core teams release as one.
Sales and Billing
Sales and Billing, neither upstream. Shared kernel.
An invoice must show exactly the total the customer agreed to at checkout, to the last cent. So Sales and Billing share one small OrderTotal: how line amounts, VAT and rounding add up. Pricing sets prices but never totals an order, so it stays out of the kernel, and Money stays each context’s own. The two teams change OrderTotal only together.
What is shared
- Shared:
OrderTotal
Shipping and Billing
Shipping upstream, Billing downstream. Customer and supplier: Shipping supplies Billing.
Billing may only charge the card once the goods are sent, so it asked Shipping for ShipmentDispatched, and Shipping planned it in.
What crosses
- Event:
ShipmentDispatchedfrom Shipping. The parcels have left the warehouse with the carrier.
Payment provider and Billing
Payment provider upstream, Billing downstream. Conformist at Billing.
Payments are generic and the provider’s model is good enough, so Billing uses its terms directly instead of translating them.
Carrier API and Shipping
Carrier API upstream, Shipping downstream. Anticorruption layer at Shipping.
The carrier speaks of consignments and status codes. Shipping translates them into Shipment and Parcel at the boundary, so it can switch carrier later.
Catalog and Sales
Catalog upstream, Sales downstream. Open host service at Catalog.
Catalog offers one Product API. Sales uses it, and so does Shipping, on the same terms.
Catalog and Shipping
Catalog upstream, Shipping downstream. Open host service at Catalog.
Shipping reads weight and size from the same Product API that Sales uses.
Sales and Shipping
Sales upstream, Shipping downstream. Published language at Sales.
Sales publishes OrderPlaced in a documented, versioned format. Shipping and Billing both read it without knowing how Order works inside.
What crosses
- Event:
OrderPlacedfrom Sales. A customer has bought something. Carries the order id, lines, total and delivery address.
Catalog and Billing
Catalog and Billing, neither upstream. Separate ways.
Invoices print the line text already copied onto the order, so Billing never needs to ask Catalog anything.
Checkpoints at the boundary: Anticorruption layer, open host service, published language
Three of the patterns on the context map are checkpoints: the places where a message crosses a boundary. An anticorruption layer translates a foreign model on the way in. An open host service offers one stable way in for everyone. A published language fixes the shape of what crosses. A checkpoint is not an open door: each pattern decides what may cross, and in what shape. Follow one real message through each checkpoint and see how it changes on the way.
Anticorruption layer
On the relationship between Carrier API and Shipping.
The message that crosses: Tracking update.
The carrier reports that it has picked up the parcel for order ord-1042. Its answer is written in the carrier’s own words, codes and units. A translator in Shipping’s boundary turns it into Shipment and Parcel before anything inside sees it, so if Shipping changes carrier, only the translator changes.
Before the checkpoint: Tracking response (JSON).
After the checkpoint: Shipment (Shipping model).
shipper_ref→id— The carrier echoes the reference Shipping gave it when booking. The translator uses it to find the right Shipment.- nothing →
orderId— Already on the Shipment. The carrier never knew about orders. evt_code→status— The carrier’s code PU, picked up, is what Shipping calls Dispatched.evt_ts→dispatchedAt— Seconds counted since 1970 become a point in time.piece_id→trackingNumber— A piece is the carrier’s word for a parcel, and its id is what Shipping calls a tracking number.gross_weight_g→weight— Grams become Shipping’s own Weight, in kilograms.consignment_no, svc_lvl, route_hub→ nothing — The carrier’s own bookkeeping. Nothing inside Shipping needs it, so it stops at the boundary.
Open host service
On the relationship between Catalog and Sales.
The message that crosses: Product.
Sales and Shipping both need to know about the running shoe on order ord-1042. Catalog does not build a special integration for each of them. It offers one documented, versioned Product API, and every caller gets the same answer. Catalog can change how it stores products, as long as version 1 keeps answering this way.
Before the checkpoint: Product (Catalog model).
After the checkpoint: GET /v1/products/prd-2201 (JSON).
id→productId— The id every context already uses to point at a product.images→imageUrls— Callers get addresses they can show, not Catalog’s internal image ids.weight→weight— Written out with its unit, so no caller has to guess.box→size— The public name for the box’s measurements, in centimetres as the API documents.draftName, publishState, editedBy→ nothing — This is how Catalog’s editors work. Callers only ever see published products, so it stays inside.
Published language
On the relationship between Sales and Shipping.
The message that crosses: OrderPlaced.
The customer has placed order ord-1042. Inside Sales it is an Order aggregate with typed values and details only Sales cares about. Sales publishes it as an OrderPlaced event in a documented, versioned format. Shipping and Billing both read that format, and neither ever sees the Order model.
Before the checkpoint: Order (Sales model).
After the checkpoint: OrderPlaced, version 1 (JSON).
- nothing →
event— The event names itself and its version, so readers know which format they hold. id→orderId— Typed values such as OrderId become plain, documented strings.lines→lines— Each line keeps the product id, the name the customer saw, the quantity and the price.total→total— Worked out once in Sales and written down, so no reader has to add it up again. Money is written as an amount and a currency.- nothing →
deliveryAddress— Copied from the Customer, so Shipping never has to ask Sales who the customer is. campaignCode, rowVersion, status→ nothing — These only mean something inside Sales, so they are not published. Every reader knows the order is placed: that is what the event says.
Zoom in: Into the Sales context
The context map shows every boundary from the outside. Strategic and tactical design are two views of the same model, not two sides of a boundary. The words and rules inside Sales, like Order and ‘a placed order can’t be changed’, are part of its ubiquitous language, so they belong to the strategic picture too. Tactical design adds the building blocks to express that model in code, so the code says what the domain experts say. Pick one boundary on the map, Sales, and step through it.
Tactical design: Inside a bounded context
Strategic design drew the boundaries between contexts, but the model and its language do not stop at a boundary. Tactical design gives you the building blocks to express that model in code, and the few checkpoints that let anything in or out.
Ports and adapters: Layers inside a context
Ports and adapters, also called hexagonal architecture, keeps the domain model at the centre of a context and everything technical at its edge.
Inside the Sales boundary the code is arranged in rings. The domain model sits in the centre. Application services around it are the checkpoints for use cases. Adapters on the outside connect to the world: web pages, the database, the message bus and other contexts. The domain owns the ports, the interfaces its adapters implement, so every dependency points inward. Point at, tap or tab to a part to see what it depends on, and why.
Every arrow points inward, toward the domain model.
Driving side — Adapters
Adapters that start something: a shopper clicking Buy, another program calling the API, a test. Each one turns its own kind of input into a call on an application service. They depend on the application, and the application knows nothing about them, so a new way in needs no change inside.
Depends on Application.
Checkout page — Driving adapter, Web pages
The web pages where a shopper fills the cart and clicks Buy. A click becomes a call to AddToCart or PlaceOrder. The page knows the application services, but no application service knows that there is a web page.
Public order API — Driving adapter, POST /v1/orders
An HTTP endpoint for other programs that place orders, such as a mobile app. It reads the JSON request, calls PlaceOrder with plain values and writes the answer back as JSON. It is a second way in to the same use case, so no rule is written twice.
Test suite — Driving adapter, With fake ports
Tests go in through the same checkpoints as the checkout page. Because the domain only knows its ports, a test can plug in fakes that keep orders in memory, and check that a placed order can’t be changed without a database or a message bus.
Application — Layer
The use cases of Sales: one application service for each thing a customer or another program can ask Sales to do. Each one is a checkpoint. It loads what it needs through the ports, lets the domain model do the work and saves the result. The business rules are not here; they live in the domain model.
Depends on Domain model.
AddToCart — Application service
The use case behind the Add to cart button. It loads the draft order, asks for the product’s name and today’s price, lets Order add the line and saves it. It talks only to ports, so it never sees Catalog’s or Pricing’s own APIs.
PlaceOrder — Application service
The use case behind the Buy button. It loads the order and the customer through their repositories, asks Order to place itself, saves it and announces OrderPlaced. Whether the order may be placed is decided by Order, not here.
Domain model — Layer
Order and Customer with their rules, and the ports: the interfaces the model needs from the outside world, written in its own language. The domain model depends on nothing outside itself. It does not know whether orders are stored in SQL or whether events go to a message bus.
Order — Aggregate
The Order aggregate with its order lines. It keeps its own rules and has no idea that it is shown on a web page or stored in SQL. Nothing in it points outward.
Customer — Aggregate
The person who places orders. Like Order, it depends on nothing outside the domain model.
OrderRepository — Port
The interface for finding and saving orders, in the domain’s own words: get the order with this OrderId, save this order. The domain owns it. How orders are stored is up to the adapter that implements it.
CustomerRepository — Port
The interface for finding a customer by CustomerId, so PlaceOrder can check that there is a delivery address.
ProductLookup — Port
What Sales needs to know about a product: its name, for a ProductId. It is the Product lookup checkpoint in the Sales boundary, seen from inside. Sales says what it needs in its own terms and never mentions Catalog’s model.
PriceLookup — Port
Today’s price for a ProductId, as Sales’ own Money. It is the Price lookup checkpoint in the Sales boundary, seen from inside.
EventPublisher — Port
How the model announces that something has happened, such as OrderPlaced. The domain says what happened. It does not know that there is a message bus.
Driven side — Adapters
Adapters the application uses to reach the outside world: the Sales database, the message bus, and the Catalog and Pricing contexts. Each one implements a port that the domain owns. When the code runs, the calls go out to them. In the code, the arrow points in: the adapter depends on the port, never the other way round.
Depends on Domain model.
SqlOrderRepository — Driven adapter, orders, order_lines tables
Implements OrderRepository with SQL over the orders and order_lines tables. If the tables change, or Sales moves to another database, only this class changes.
SqlCustomerRepository — Driven adapter, customers table
Implements CustomerRepository with SQL over the customers table.
CatalogProductClient — Driven adapter, Catalog’s Product API
Implements ProductLookup by calling Catalog’s Product API and keeping only the product id and name. Catalog’s JSON stops here, so a new version of that API changes this class and nothing else.
PricingPriceClient — Driven adapter, The Pricing context
Implements PriceLookup by asking Pricing for today’s price and turning the answer into Sales’ own Money.
MessageBusPublisher — Driven adapter, OrderPlaced, version 1
Implements EventPublisher. It writes the event in the published OrderPlaced format, version 1, and puts it on the message bus, where Shipping and Billing pick it up.
Aggregates: Who is allowed to touch what
An aggregate is a cluster of entities and value objects that must stay consistent together. It is saved as one unit and reached only through its root.
Everything in the Sales context lives behind a boundary. Point at, tap or tab to a box to see what it holds, what it points to, and what may point to it. The coral boxes are checkpoints: the only ways through a boundary. On a narrow screen the drawing is shown whole: tap a boundary to zoom into it, drag to look around, and use the button under the drawing to zoom back out.
Everything inside an aggregate is reached through its root.
Sales — Bounded context
The boundary around one model and one language. Everything drawn inside it belongs to the Sales team: it can change the model, the code and the tables without asking anyone, as long as its checkpoints keep working.
Nothing crosses this boundary except through a checkpoint.
AddToCart — Application service
The use case behind the Add to cart button: load the draft order, ask for the product’s name and today’s price, let Order add the line and save it. It holds no business rules of its own.
A checkpoint into the Sales context for one use case.
Points to
- starts an empty cart with Order.StartCart
- loads and saves the cart through OrderRepository
PlaceOrder — Application service
The use case behind the Buy button: load the order and the customer, ask AccountCreditPolicy for the payment terms, tell Order to place itself and save it — all in one transaction. Whether the order may be placed is Order’s decision, not its own.
A checkpoint into the Sales context for one use case.
Points to
- loads and saves the order through OrderRepository
- asks for the payment terms from AccountCreditPolicy
- asks to place itself Order
AccountCreditPolicy — Domain service
Whether a customer may check out on account depends on what they already owe across every other order. No aggregate may go looking for its siblings, so the answer belongs to neither Order nor Customer: a stateless operation works it out and hands back a value.
Called as a plain operation — there’s nothing to reach inside.
Points to
- totals the unpaid orders through OrderRepository
- reads the total of Order
- reads the credit limit of Customer
Pointed to by
- PlaceOrder asks for the payment terms from
Customer aggregate — Aggregate
A second consistency boundary in the same context, saved in its own transaction. Order never holds a Customer; it holds a CustomerId.
Rule it keeps: A customer needs a delivery address before placing an order.
Customer — Aggregate root
The person who places orders. Order knows its id and nothing more, so a change to Customer can never break an order that is already placed.
The only checkpoint into the Customer aggregate.
Pointed to by
- AccountCreditPolicy reads the credit limit of
- CustomerId refers by id to
Sales.Ordering — Module
A namespace that groups everything about ordering — Order with its lines, OrderRepository and OrderPlaced — so the shape of the code matches the shape of the model. It is not a boundary: it keeps nothing out.
No checkpoint of its own: the parts inside keep theirs.
OrderRepository — Repository
Looks like a collection of whole Order aggregates and hides the database. One repository per aggregate, never one per entity or per table: OrderLine never gets one of its own, because nothing outside may reach it anyway.
Its own interface, owned by the domain, not by the database.
Points to
- finds and saves the whole Order
Pointed to by
- AddToCart loads and saves the cart through
- PlaceOrder loads and saves the order through
- AccountCreditPolicy totals the unpaid orders through
Order aggregate — Aggregate
A consistency boundary. Order, its lines and their values are loaded, changed and saved together, in one transaction. Nothing outside may reach past the root, so the rules that span the whole order can be kept in one place.
Rule it keeps: A placed order can’t be changed.
Order.StartCart — Factory
Builds a new, valid order in one step: the only way to get a first, empty cart into existence. There is no other constructor to misuse, so a half-built Order can never exist.
A static factory method on the aggregate itself.
Points to
- creates a valid, empty Order
Pointed to by
- AddToCart starts an empty cart with
Order — Aggregate root
Guards the rules that span the whole order. Every change goes through it, so “a placed order can’t be changed” is checked in exactly one place.
The only checkpoint into the Order aggregate. Nothing outside may hold on to an OrderLine.
Points to
- contains OrderLine
- holds CustomerId
- holds OrderStatus
- raises OrderPlaced
Pointed to by
- PlaceOrder asks to place itself
- Order.StartCart creates a valid, empty
- OrderRepository finds and saves the whole
- AccountCreditPolicy reads the total of
CustomerId — Value object
Points at a customer without holding the Customer object, so the two aggregates can be loaded, changed and saved on their own.
Points to
- refers by id to Customer
Pointed to by
- Order holds
OrderStatus — Value object
Draft or placed, and nothing else. Order checks it before every change, which is how “a placed order can’t be changed” is kept.
Pointed to by
- Order holds
OrderLine — Entity
Has an identity of its own inside the order, but no life outside it. It is created, changed and removed through Order, and no code outside the aggregate may hold on to one.
Its methods, which protect its rules — reached only through Order.
Points to
- holds ProductId
- holds Money
Pointed to by
- Order contains
ProductId — Value object
Points at a product in the Catalog context by id. Sales never loads Catalog’s own Product model; the line keeps the id and a copy of the name the customer saw.
Points to
- refers by id into Catalog
Pointed to by
- OrderLine holds
Money — Value object
An amount and a currency that never change. Its factory method rejects invalid values, so an invalid Money can never exist, and the price on a placed line stays what it was on the day of the order.
Money.From, the only way to make one.
Pointed to by
- OrderLine holds
OrderPlaced — Domain event
Something that happened, named in the past tense. It carries the order id, the lines, the total and the delivery address — nothing about how Order keeps its rules. Shipping and Billing each react to it in their own transaction.
The way out of the Sales context: others see the event, never the model.
Points to
- is published to Shipping
Pointed to by
- Order raises
Shipping — Bounded context
Another boundary, with its own idea of an order: something to pack and send. It cannot read the Sales tables, so it learns about new orders only when OrderPlaced comes through the checkpoint.
Pointed to by
- OrderPlaced is published to
Catalog — Bounded context
Another boundary, with its own Product: a description with images that editors change at any time. Sales never sees that model — from inside Sales a product is a ProductId and a price on a line.
Pointed to by
- ProductId refers by id into
Building blocks: Eight shapes, eight kinds of checkpoint
Tactical design has eight building blocks: value objects, entities, aggregates, domain services, domain events, repositories, factories and modules.
Each building block has its own way of keeping the outside world out. Once you know the checkpoint, you know how it may be used.
Value object
Defined only by its values, and it never changes. Two Money.From(100, "DKK") are the same money.
Checkpoint: Money.From, the only way to make one
Used by: Held by value inside an entity
public sealed class Money
{
private Money(decimal amount, string currency)
{
Amount = amount;
Currency = currency;
}
public decimal Amount { get; }
public string Currency { get; }
// The only way in: no Money exists unless it is valid
public static Money From(decimal amount, string currency)
{
if (amount < 0)
throw new DomainException("Money can’t be negative.");
return new Money(amount, currency);
}
// Same values, same money: no identity of its own
public override bool Equals(object? other) =>
other is Money money && money.Amount == Amount && money.Currency == Currency;
public override int GetHashCode() => HashCode.Combine(Amount, Currency);
}
Entity
Has an identity that stays the same while its data changes. Line 3 is still line 3 after you change the quantity.
Checkpoint: Its methods, which protect its rules
Used by: Only through its aggregate root
internal sealed class OrderLine
{
private const int MaxPerLine = 100;
// The identity: it stays while the data changes
public OrderLineId Id { get; }
public ProductId ProductId { get; }
public Money Price { get; }
public int Quantity { get; private set; }
// The checkpoint: only Order calls this, and the line’s own rules live here
internal void ChangeQuantity(int quantity)
{
if (quantity < 1)
throw new DomainException("Remove the line instead of ordering none of it.");
if (quantity > MaxPerLine)
throw new DomainException($"A line can hold at most {MaxPerLine} of one product.");
Quantity = quantity;
}
}
Aggregate
A cluster of entities and value objects that must stay consistent together, saved as one unit.
Checkpoint: The aggregate root
Used by: From outside: by identity only
public sealed class Order // the aggregate root
{
private readonly List<OrderLine> _lines = new();
public OrderId Id { get; }
public OrderStatus Status { get; private set; }
// Nothing outside this class reaches _lines directly
public IReadOnlyList<OrderLine> Lines => _lines;
public void Add(OrderLine line)
{
if (Status != OrderStatus.Draft)
throw new DomainException("A placed order can’t be changed.");
// One line per product: the same product twice is one line of two
var sameProduct = _lines.SingleOrDefault(l => l.ProductId == line.ProductId);
if (sameProduct is null)
_lines.Add(line);
else
sameProduct.ChangeQuantity(sameProduct.Quantity + line.Quantity);
}
}
Domain service
Whether a customer may check out on account depends on what they already owe across every other order. Hand Order the Customer and it still can’t answer: no aggregate may go looking for its siblings.
Checkpoint: Called as a plain operation — there’s nothing to reach inside
Used by: The PlaceOrder application service, before it asks Order to place itself
public sealed class AccountCreditPolicy // a domain service
{
private readonly OrderRepository _orders; // the domain’s own interface
public AccountCreditPolicy(OrderRepository orders) => _orders = orders;
// Order knows only its own lines; Customer knows nothing about orders;
// and neither may load the others. The answer belongs to no aggregate,
// so it comes back as a value instead of changing either one.
public PaymentTerms TermsFor(Order order, Customer customer)
{
Money owed = _orders.UnpaidTotalFor(customer.Id); // across every other order
return owed + order.Total > customer.CreditLimit
? PaymentTerms.PayNow
: PaymentTerms.OnAccount;
}
}
Domain event
Something that happened, named in the past tense. OrderPlaced carries what Shipping and Billing need to know, nothing about how Order keeps its rules.
Checkpoint: The event itself is the checkpoint — announced once, held by no one
Used by: Published by Order when it is placed; Shipping and Billing each react in their own transaction
public sealed record OrderPlaced(
OrderId OrderId,
IReadOnlyList<OrderLine> Lines,
Money Total,
Address DeliveryAddress);
Repository
One repository per aggregate, never per entity. OrderRepository finds and saves whole Orders; OrderLine never gets one of its own.
Checkpoint: Its own interface, owned by the domain, not by the database
Used by: Application services only, such as PlaceOrder
// Owned by the domain; SqlOrderRepository implements it
public interface OrderRepository
{
Order? Find(OrderId id);
void Save(Order order);
}
Factory
Builds a new, valid aggregate in one step. Order.StartCart is the only way to get a first, empty order into existence — there is no other constructor to misuse.
Checkpoint: A static factory method on the aggregate itself
Used by: AddToCart, the first time a customer adds something to an empty cart
public sealed class Order
{
// The checkpoint: the only way to get a first, valid Order
public static Order StartCart(CustomerId customerId) =>
new(OrderId.New(), customerId, OrderStatus.Draft);
}
Module
A namespace that groups the model, not a boundary of its own. Sales.Ordering holds Order, OrderLine, OrderPlaced and OrderRepository together, so the shape of the code matches the shape of the model.
Checkpoint: None of its own — the aggregates and services inside keep their checkpoints
Used by: Everything in Sales that touches ordering imports from it
namespace Sales.Ordering;
// Order, OrderLine, OrderPlaced, OrderRepository live here
public sealed class Order
{
private readonly List<OrderLine> _lines = new();
public OrderId Id { get; }
public CustomerId CustomerId { get; } // another aggregate, by id
public OrderStatus Status { get; private set; }
// The checkpoint: every change goes through the root
public void AddLine(ProductId product, int quantity, Money price)
{
if (Status != OrderStatus.Draft)
throw new DomainException("A placed order can't be changed.");
_lines.Add(new OrderLine(product, quantity, price));
}
}
Aggregate rules: Allowed and forbidden
Four rules keep aggregates apart: reach inside one only through its root, refer to another by its id, give each its own repository, and change only one per transaction.
Every rule here has the same shape: reach past an aggregate's root and the boundary stops you, with a blocked sign to show it; go through the root, its checkpoint, and it lets you in. Each pair shows the forbidden path next to the allowed one, with a one-line C# hint.
Reaching into OrderLine
Forbidden
order.Lines[0].ChangeQuantity(5); // skips Order’s rule
Order.Lines is a public, read-only list, so nothing stops other code in the same assembly from calling ChangeQuantity on a line it holds. That change never asks whether the order can still be changed.
Allowed
order.AddLine(productId, 2, price); // Order checks the rule
Order is the only checkpoint into the aggregate. Ask it to add or change a line, and it checks “a placed order can’t be changed” first, every time, in one place.
Holding a Customer
Forbidden
public Customer Customer { get; } // holds the aggregate
A live Customer reference lets Order reach into another aggregate’s state, and ties the two together: Order can no longer be loaded, changed or saved on its own.
Allowed
public CustomerId CustomerId { get; } // holds only the id
CustomerId is just a value. Order can be loaded and saved entirely on its own, and looks up Customer only when it needs to, through Customer’s own checkpoint.
One repository per aggregate
Forbidden
public interface OrderLineRepository { OrderLine? Find(OrderLineId id); }
OrderLine has no life outside Order, so a repository for it would let code load and save a line without going through the order that owns it — exactly what the boundary is there to stop.
Allowed
public interface OrderRepository { Order? Find(OrderId id); }
OrderRepository finds and saves whole Order aggregates. Whatever is inside — OrderLine included — comes along for the ride and never gets a checkpoint of its own.
One transaction, one aggregate
Discouraged
Save(order); Save(customer); // two aggregates, one transaction
It can be made to work, but now one transaction spans two aggregates: a lock held on Customer while Order is still changing, and a rule that has to know about both to keep them in step.
Encouraged
Save(order); // then OrderPlaced tells Customer, later
PlaceOrder saves Order alone, in one transaction, and Order raises OrderPlaced on the way out. Customer reacts to the event later, in a transaction of its own.
Transactions: One transaction, one aggregate
An aggregate is a consistency boundary, and a transaction is what makes that boundary real: one transaction loads, changes and saves exactly one aggregate. Step through placing an order and watch the boundary open around Order, close when it is saved, and never reach around anything else.
What happens when
One transaction changes one aggregate. Everything else follows later, each in a transaction of its own.
The steps
PlaceOrder opens one transaction
The Buy button reaches the Sales context through PlaceOrder, an application service. It is the checkpoint for this one use case, and it is where the transaction begins and ends. It holds no business rules of its own: those belong to Order.
Transaction: No transaction yet.
It loads one whole aggregate
OrderRepository finds the order by its id and hands back the whole Order aggregate — the root, its OrderLines and the values they hold — in one go. A repository deals in whole aggregates, so there is no way to load half of one, and no way to load a line without its order.
Transaction: Open — one aggregate loaded.
Anything else is read, never joined
Whether this customer may check out on account depends on what they already owe, so PlaceOrder asks AccountCreditPolicy for the payment terms and gets a value back. Order holds a CustomerId, never a Customer, so the Customer aggregate is read through its own checkpoint and stays outside the boundary.
Transaction: Open — still one aggregate.
Every change goes through the root
AddLine put the lines on the order; Place now closes it. Both go through Order, the only checkpoint into the aggregate, so “a placed order can’t be changed” is checked in exactly one place. Order raises OrderPlaced as it goes, and keeps it until the transaction commits.
Transaction: Open — Order changed.
One aggregate is saved, and the boundary closes
OrderRepository saves the same whole aggregate, and the transaction commits. One transaction, one aggregate: nothing else was locked while the order was changing, and nothing else has to be rolled back if the save fails.
Transaction: Committed — one aggregate saved.
The rest follows later, each in its own transaction
Once the transaction has committed, OrderPlaced leaves Sales through its checkpoint. Shipping creates a Shipment and Billing writes the invoice, each in a transaction of its own, and any change to Customer is made the same way. For a moment the order exists and the shipment does not: that is eventual consistency, and it is what keeping every transaction to one aggregate costs.
Transaction: Closed — the other changes are transactions of their own.
What happens when
Now: Order is saved
PlaceOrder saves the Order aggregate as one unit: the root, its lines and their values. Nothing else is in this transaction.
Later: A Shipment is created
OrderPlaced crosses the boundary. Shipping creates a Shipment and packs the parcels, in a transaction of its own.
Later: The invoice is written
Billing reads the same event and writes an invoice with the same lines and the same total, in a transaction of its own.
Later: Customer catches up
If the customer has to change too, that change is made in its own transaction, started by the same event — never inside the first one.
Domain events: Back out through the boundary
A domain event records something that happened in the domain, named in the past tense, like OrderPlaced.
Everything so far has been inside one boundary. The last thing to follow is the way out. Nothing reaches into Sales for an order, and Sales hands nothing of its model out: what leaves is an event, written in a language both sides agreed on, and the other side turns it into its own words.
Order is saved and raises OrderPlaced. Follow it out: it leaves the aggregate, it changes shape at the boundary, and what arrives in Shipping is a document, never the model behind it.
Inside the Sales boundary — A domain event
Order raises OrderPlaced while it is being saved, and at that moment the event is still Sales’ own: typed values such as OrderId and Money, and fields that only mean anything behind this boundary.
At the checkpoint — A published language
At the boundary the event becomes the document Sales publishes: OrderPlaced, version 1. Typed values turn into plain, documented ones, the delivery address is copied on so no reader has to ask for it, and Sales’ own bookkeeping stops here.
Inside the Shipping boundary — Shipping’s own words
Shipping reads the event and writes something of its own: a Shipment with parcels to pack, an address to send them to and, once the carrier has been booked, a tracking number. It keeps the order id, and nothing else of Sales.
What crosses
Shipping reads the three fields it needs and turns them into a Shipment of its own.
orderId— the one id both boundaries agree on, kept on the Shipment as a referencelines— what to pack, by product id and quantitydeliveryAddress— where the parcels go, copied onto the event so Shipping never has to ask Sales who the customer is
What stays inside Sales
None of this is published, and no reader can reach in for it.
the Order aggregate— the model itself, with its rule that a placed order can’t be changedthe Sales tables— orders, order_lines and customers, which only Sales reads and writescampaignCode, rowVersion— Sales’ own bookkeeping, meaningless on the other side of the boundary