Shrinking an oversized order aggregate
Worked example: sort an online shop's order rules into true invariants, snapshots and rules that may lag, measure the cost of one oversized aggregate with a seeded simulation, split it, and decide how to compensate for the consistency you give up.
Contentsand lesson path
On this page
- The problem
- Step 1: List the rules and sort them
- Step 2: Measure before you change anything
- Step 3: Read the table
- Step 4: Draw the new boundaries
- Step 5: Decide what the customer sees
- Check your understanding
- Apply it
- Review prompt
Lessons of Tactical Domain-Driven Design
- Entities, value objects and making illegal states unrepresentable Concept · 20 min
- Aggregates as consistency boundaries Concept · 25 min
- Shrinking an oversized order aggregate Worked example · 25 min
- Domain events, domain services and avoiding an anemic model Concept · 20 min
- Implementing a booking aggregate with events Lab · 30 min
- Aggregate design check Knowledge check · 6 questions
What you will learn
- Design aggregates around invariants, sized so that one transaction changes one aggregate.
01. The problem
Fernleaf Tea is a fictional online tea shop. In its first year a small team wrote one Order class that reaches everything an order touches: its lines, the Customer with profile and addresses, the catalogue Product behind each line, and the StockItem that counts units of each tea. One mapping loads the whole cluster, one version check protects it, and checkout takes stock in the same transaction.
During last month's Darjeeling sale, shoppers kept seeing 'This order was changed by someone else, please try again', price edits failed, and the restock screen timed out. Your job is to shrink the aggregate without losing a business rule:
- every rule below must hold, at commit time or within a delay the business accepts;
- a command should change one aggregate per transaction, as in lesson 2;
- you must be able to say what the customer sees when a delayed rule fails.
02. Step 1: List the rules and sort them
Start from rules, not classes, because an aggregate exists to protect rules. Fernleaf's staff give six:
- An order's total is the sum of its lines, at the price shown when each line was added.
- A placed order does not change, except by refunding a line.
- Units promised to orders never exceed the units on the shelf, for each tea.
- The delivery address is the one chosen at checkout, even if the profile changes.
- A catalogue price change applies to new lines only.
- Every placed order gets its stock reserved; if a tea has run out, the customer is told and that line is refunded.
Rules 1 and 2 compare an order with its own lines: true invariants of Order. Rule 3 is a true invariant of one tea's stock, not of an order, because different orders compete for the same units. Rules 4 and 5 sound like consistency with the customer and the catalogue, but they say the opposite: the order must not follow later changes, so it keeps copies of the address and price as value objects. For rule 6, ask lesson 2's question: whose job is it? Not the shopper's; it is the system's, and the owner accepts a few seconds' delay as long as customers hear about a missing tea. So rule 6 may lag, with a refund as the compensation: a later action that makes up for a step that could not be completed. The oversized design treated rules 4 to 6 as invariants of the order, Vernon's false invariants.
03. Step 2: Measure before you change anything
Measure before changing code, so that two designs meet the same traffic. The script replays one seeded workload of 150 ticks; in a tick every request loads its data before any of them saves. A save is refused if anything the command loaded was saved by someone else in that tick, which is how a version check over the whole cluster behaves. You need Python 3.11 or newer. Paste the three parts, in order, into one file named order_sim.py.
Part 1 creates the traffic, with Darjeeling chosen far more often than other teas. random.Random(2026) makes it the same on every run.
"""Replay one seeded flash-sale workload against two Order designs."""
import random
from collections import Counter
SKUS = ["DARJ", "ASSAM", "SENCHA", "CHAI", "MINT", "EARL"]
POPULARITY = [10, 2, 2, 1, 1, 1] # Darjeeling is on sale today
CUSTOMERS = [f"C{n:02}" for n in range(1, 41)]
KINDS = ["add_line", "place", "profile", "price", "restock"]
MIX = [6, 2, 1, 1, 1] # shoppers add lines most often
def workload(seed: int = 2026, ticks: int = 150):
"""Yield (tick, kind, customer, sku). The same seed gives the same commands."""
rng = random.Random(seed)
for tick in range(ticks):
for _ in range(rng.randint(2, 5)):
kind = rng.choices(KINDS, MIX)[0]
yield tick, kind, rng.choice(CUSTOMERS), rng.choices(SKUS, POPULARITY)[0]Part 2 holds the decision under test. footprint() returns what a command loads (its consistency boundary) and what it writes. In the oversized design an order command loads the order, the customer, and the product and stock record of every tea in the cart, and checkout writes the stock records. In the split design it loads only the order, which holds copies and the customer's id. apply() holds the rules: the oversized design refuses the whole order at checkout if a tea has run out, while the split design places it and queues one reserve per tea, each a transaction on one StockItem; a failed reservation queues a refund.
class Shop:
def __init__(self, split: bool) -> None:
self.split = split
self.cart = {c: Counter() for c in CUSTOMERS} # lines of each open order
self.number = dict.fromkeys(CUSTOMERS, 1) # open order is C07#1, C07#2 ...
self.stock = dict.fromkeys(SKUS, 20)
self.stats = Counter()
def footprint(self, kind: str, who: str, sku: str) -> tuple[set, set]:
"""Records the command loads (its consistency boundary) and writes."""
single = {"profile": f"customer:{who}", "price": f"product:{sku}",
"restock": f"stock:{sku}", "reserve": f"stock:{sku}",
"refund": f"order:{who}"}
if kind in single:
return {single[kind]}, {single[kind]}
order = {f"order:{who}#{self.number[who]}"}
if self.split: # Order holds lines, price snapshots and a customer id
return order, order
skus = set(self.cart[who]) | ({sku} if kind == "add_line" else set())
loads = order | {f"customer:{who}"}
loads |= {f"{part}:{s}" for s in skus for part in ("product", "stock")}
writes = order | ({f"stock:{s}" for s in skus} if kind == "place" else set())
return loads, writes
def apply(self, kind: str, who: str, sku: str, qty: int) -> list[tuple]:
"""Change the state; return follow-up commands for the next tick."""
if kind == "add_line":
self.cart[who][sku] += 1
elif kind == "restock":
self.stock[sku] += 3
elif kind == "place" and self.cart[who]:
order = f"{who}#{self.number[who]}"
lines, self.cart[who] = self.cart[who], Counter()
self.number[who] += 1
self.stats["checkouts"] += 1
if self.split: # stock is reserved later, one StockItem per transaction
return [("reserve", order, s, n) for s, n in lines.items()]
if all(self.stock[s] >= n for s, n in lines.items()):
for s, n in lines.items():
self.stock[s] -= n
else:
self.stats["orders refused at checkout"] += 1
elif kind == "reserve":
if self.stock[sku] < qty:
return [("refund", who, sku, qty)] # compensate the placed order
self.stock[sku] -= qty
elif kind == "refund":
self.stats["lines refunded after placing"] += 1
return []Part 3 is the engine. A conflicting command is retried next tick: people give up after three tries, while handlers such as reserve keep retrying. It also records which command caused each conflict, and how long each reservation waited.
def run(split: bool) -> Counter:
shop, queue = Shop(split), {}
for tick, kind, who, sku in workload():
queue.setdefault(tick, []).append((kind, who, sku, 1, 1, tick))
tick = 0
while queue:
writer: dict[str, str] = {} # every command in a tick loads before any saves
for kind, who, sku, qty, attempt, since in queue.pop(tick, []):
loads, writes = shop.footprint(kind, who, sku)
shop.stats["attempts"] += 1
shop.stats["records loaded"] += len(loads)
clash = sorted(loads & writer.keys())
if clash: # a record we loaded was saved by someone else first
shop.stats[f"conflicts caused by {writer[clash[0]]}"] += 1
if attempt == 3 and kind not in ("reserve", "refund"):
shop.stats["requests failed after 3 tries"] += 1
else: # handlers keep retrying; people give up after 3 tries
job = (kind, who, sku, qty, attempt + 1, since)
queue.setdefault(tick + 1, []).append(job)
continue
writer.update(dict.fromkeys(writes, kind))
if kind == "reserve":
wait = shop.stats["longest wait for stock (ticks)"]
shop.stats["longest wait for stock (ticks)"] = max(wait, tick - since)
for job in shop.apply(kind, who, sku, qty):
queue.setdefault(tick + 1, []).append((*job, 1, tick))
tick += 1
shop.stats["records per attempt"] = round(
shop.stats["records loaded"] / shop.stats["attempts"], 1)
return shop.stats
def main() -> None:
big, small = run(split=False), run(split=True)
rows = ["attempts", "records per attempt"]
rows += [f"conflicts caused by {k}" for k in KINDS + ["reserve", "refund"]]
rows += ["requests failed after 3 tries", "checkouts",
"orders refused at checkout", "lines refunded after placing",
"longest wait for stock (ticks)"]
print(f"{'':32}{'oversized':>10}{'split':>8}")
for row in rows:
if big[row] or small[row]:
print(f"{row:32}{big[row]:>10}{small[row]:>8}")
if __name__ == "__main__":
main()04. Step 3: Read the table
python3 order_sim.py oversized split
attempts 719 751
records per attempt 4.5 1.0
conflicts caused by add_line 17 11
conflicts caused by place 109 1
conflicts caused by profile 3 1
conflicts caused by price 55 2
conflicts caused by restock 40 21
conflicts caused by reserve 0 45
requests failed after 3 tries 37 2
checkouts 61 72
orders refused at checkout 7 0
lines refunded after placing 0 10
longest wait for stock (ticks) 0 6This models one scenario; it is not a benchmark, and real numbers depend on traffic, database and timing. What it shows reliably is which commands collide: with five other seeds the counts moved, but the pattern did not. The table was identical on Python 3.11, 3.12 and 3.14.
- Records per attempt fell from 4.5 to 1.0.
- Conflicts caused by place fell from 109 to 1. Each oversized checkout with Darjeeling wrote the Darjeeling stock record, which every open cart holding Darjeeling had loaded, so ordinary 'add a line' requests failed.
- Conflicts caused by price fell from 55 to 2: once lines keep their own price, catalogue edits stop meeting shoppers.
- Requests failed after 3 tries fell from 37 to 2, and checkouts rose from 61 to 72.
- Conflicts caused by reserve (45) and restock (21) remain: reservations and restocks hitting the same
StockItemin one tick. That contention is real: rule 3 checks each reservation against the current total for that tea, so two reservations cannot both rely on an old count. The split moved it to the one place where the rule lives, where a retry settles it.
Now the price. The oversized design refused 7 orders at checkout, and those customers knew at once. The split design refunded 10 lines after placing, and a reservation waited up to 6 ticks. That is the consistency you gave up: for a few seconds an order can exist for tea the shop cannot send.
05. Step 4: Draw the new boundaries
The new boundaries follow the rules, and every reference between aggregates is an id:
Order (root) StockItem (root, one per tea)
order_id, customer_id sku, on_hand, reserved
lines: OrderLine values rule 3: reserved <= on_hand
sku, quantity, unit_price
delivery: Address value Customer (root) Product (root)
status: placed | refunded ... profile name, price
rules 1, 2, 4, 5
Order.place() --OrderPlaced--> reserve handler: StockItem.reserve(order_id, qty)
shortage --> Order.refund_line(sku) (rule 6)Each command now changes one aggregate. Placing an order changes Order and records an OrderPlaced event; a handler reserves each tea in its own transaction; a shortage leads to a refund on the order, again in its own transaction. Lesson 4 explains how such events are recorded and delivered.
06. Step 5: Decide what the customer sees
The last step is a product decision: what does the customer see while rule 6 catches up? Fernleaf has three reasonable options, each with a cost.
- Word the states honestly. Show 'Order received' at checkout and 'Confirmed' only after every tea is reserved. Cheap and truthful, but the confirmation arrives a moment later.
- Reserve first, then place. Reserve teas when checkout starts and let a reservation expire if payment never follows. No refunds after confirmation, but an extra state, and abandoned checkouts hold stock until they expire.
- Check a stock read model at checkout. Refunds become rarer but not impossible, because the figure may be seconds old when two shoppers buy the last tin.
What if Darjeeling sales grew ten times? Reservation conflicts would grow too, because one StockItem per tea serialises its reservations. Queueing reservations per tea, or splitting one tea's stock into buckets with their own invariant, are options beyond this lesson; change a boundary when a measurement says so.
07. Check your understanding
08. Apply it
- Predict first: change
footprint()so that the split order also loadscustomer:{who}, as if the address were read live instead of copied. Which rows of the table will change, and in which direction? Run it and compare. - Pick the largest aggregate in your clinic model, or in a codebase you know. List its rules and sort them into true invariants, snapshots and rules that may lag. For each lagging rule, write the compensation and what the user sees meanwhile.
- Write the two footprints, before and after, in the style of
footprint(), and count the records each command loads.
09. Review prompt
Without looking back:
- Why do rules 4 and 5 lead to copies inside the order rather than to a bigger aggregate?
- Which question decided that rule 6 may lag, and who had to agree?
- Why did a checkout in the oversized design make other shoppers' 'add a line' requests fail?
- Which conflicts did the split keep, and why are they acceptable?
- What did Fernleaf give up, and what are its three options for the customer?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.