Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Worked example · 30 min · revision 1

Decomposing a retailer by capability and bounded context

Work through the decomposition of a fictional outdoor-gear retailer: list capabilities, check them against bounded contexts, assign one owner per table, trace the checkout calls, run a fitness check, and merge or re-route the parts that would create chatty or cyclic calls.

Contentsand lesson path

What you will learn

  • Decompose a system into services aligned with bounded contexts and business capabilities while avoiding distributed-monolith coupling.

Prerequisites: Strategic Domain-Driven Design

01. The brief

Tarnside Outfitters is a made-up retailer that sells outdoor gear online and in twelve stores. About forty engineers work in six teams on one monolith, and the co-change evidence from lesson 1 shows that release contention is real. You are asked for a first service decomposition of the online shop with these constraints:

  • every table has exactly one owning service, and every service has one owning team;
  • the synchronous calls made during a checkout form a graph with no cycles;
  • no service calls another more than three times for one checkout, so a 12-line basket must not mean 12 calls;
  • the checkout must keep working while non-essential parts, such as email, are down.

Each step below says why it is taken, because the same reasoning has to work on your own system.

02. Step 1: list business capabilities, then test them against contexts

A business capability is something the business does to earn or keep money, such as pricing goods, holding stock or shipping parcels. Capabilities change for business reasons and at different speeds, so a boundary that follows them keeps most changes inside one service. A split by technical layer (screens, logic, data) or by table does the opposite: every feature touches every part.

Tarnside's capabilities are catalogue, pricing, promotions, inventory, cart, ordering, payments, fulfilment, customer accounts, loyalty and notifications. Search stays inside the catalogue for now, since nothing yet shows it needs separate scaling.

Next, test each candidate against bounded contexts, the areas where one model and one vocabulary hold (why one model cannot serve everyone; the context-map lab shows how to draw them). Listen for words that change meaning. Product means a description and photos in the catalogue, a stock-keeping unit with a quantity per location in inventory, and a line in a price list in pricing: three models, three contexts. Order means the customer's request and its payment in ordering, but a set of parcels and a picking list in fulfilment. When two candidates share one vocabulary and one team, they may be a single context; pricing and promotions both speak of price rules, which step 4 comes back to.

03. Step 2: draft the services and trace the checkout

The first draft gives each capability a service and writes down two facts per service: the tables it owns and the synchronous calls it makes while one 12-line basket is checked out. Writing calls with their counts matters, because a design that looks tidy as boxes can still be chatty on the wire. The checkout as the first draft would run it:

Text · draft checkout, synchronous calls only
web -> cart: show basket
  cart -> pricing (x12, one per line)
    pricing -> promotions (x12) -> loyalty (member offers)
      loyalty -> cart (read basket to preview points)
web -> orders: place order
  orders -> cart, inventory (reserve), payments (authorise), customers
  orders -> fulfilment (create shipment) -> orders (read lines back)
  orders -> notifications (confirmation email)

Rather than inspect this by eye, encode the rules as a small fitness check. boundaries.py reports tables with two owners, cycles of synchronous calls (using Tarjan's algorithm, which finds groups of services that can all reach each other) and chatty edges. It needs Python 3.12 or newer; put the three files in one folder.

Python · boundaries.py
"""boundaries.py: check a proposed decomposition for three warning signs.

1. A table with more than one owning service.
2. A cycle of synchronous calls (services that cannot be deployed or fail alone).
3. A chatty edge: one caller makes many synchronous calls to one callee per request.
"""
CHATTY = 3  # more calls than this per checkout is a warning


def find_cycles(calls: dict[tuple[str, str], int]) -> list[list[str]]:
    """Groups of services that reach each other through synchronous calls (Tarjan)."""
    graph: dict[str, list[str]] = {}
    for caller, callee in calls:
        graph.setdefault(caller, []).append(callee)
        graph.setdefault(callee, [])
    index: dict[str, int] = {}
    low: dict[str, int] = {}
    stack: list[str] = []
    groups: list[list[str]] = []

    def visit(node: str) -> None:
        index[node] = low[node] = len(index)
        stack.append(node)
        for nxt in graph[node]:
            if nxt not in index:
                visit(nxt)
                low[node] = min(low[node], low[nxt])
            elif nxt in stack:
                low[node] = min(low[node], index[nxt])
        if low[node] == index[node]:
            group = []
            while True:
                member = stack.pop()
                group.append(member)
                if member == node:
                    break
            if len(group) > 1 or node in graph[node]:
                groups.append(sorted(group))

    for node in sorted(graph):
        if node not in index:
            visit(node)
    return sorted(groups)


def check(owns: dict[str, list[str]], calls: dict[tuple[str, str], int]) -> None:
    owners: dict[str, list[str]] = {}
    for service, tables in owns.items():
        for table in tables:
            owners.setdefault(table, []).append(service)
    problems = [f"table {t} has {len(s)} owners: {', '.join(s)}"
                for t, s in sorted(owners.items()) if len(s) > 1]
    problems += [f"sync cycle among: {', '.join(g)}" for g in find_cycles(calls)]
    problems += [f"chatty: {a} -> {b} makes {n} calls per checkout"
                 for (a, b), n in sorted(calls.items()) if n > CHATTY]
    print(f"{len(owns)} services, {len(calls)} sync edges, {sum(calls.values())} "
          f"sync calls per checkout")
    for problem in problems or ["no problems found"]:
        print("  " + problem)
Python · draft.py
"""draft.py: the first decomposition of the Tarnside Outfitters checkout."""
from boundaries import check

OWNS = {
    "catalogue": ["products", "categories"],
    "pricing": ["price_lists"],
    "promotions": ["promo_rules", "coupons"],
    "inventory": ["stock_levels", "reservations"],
    "cart": ["carts", "cart_lines"],
    "orders": ["orders", "order_lines"],
    "payments": ["payment_attempts"],
    "fulfilment": ["shipments", "pick_lists"],
    "customers": ["customers", "addresses"],
    "loyalty": ["members", "points_ledger", "promo_rules"],
    "notifications": ["sent_messages"],
}
# Synchronous calls while one 12-line basket is checked out: (caller, callee) -> calls
CALLS = {
    ("cart", "pricing"): 12,         # price each line
    ("pricing", "promotions"): 12,   # look for a promotion on each line
    ("promotions", "loyalty"): 1,    # member-only offers need the member's tier
    ("loyalty", "cart"): 1,          # loyalty reads the basket to preview points
    ("orders", "cart"): 1,           # read the basket being ordered
    ("orders", "inventory"): 1,      # reserve stock
    ("orders", "payments"): 1,       # authorise the card
    ("orders", "customers"): 1,      # check the delivery address
    ("orders", "fulfilment"): 1,     # create the shipment
    ("fulfilment", "orders"): 1,     # read the lines and address back
    ("orders", "notifications"): 1,  # send the confirmation email
}
check(OWNS, CALLS)
Terminal
python3 draft.py
Expected output
11 services, 11 sync edges, 33 sync calls per checkout
  table promo_rules has 2 owners: promotions, loyalty
  sync cycle among: cart, loyalty, pricing, promotions
  sync cycle among: fulfilment, orders
  chatty: cart -> pricing makes 12 calls per checkout
  chatty: pricing -> promotions makes 12 calls per checkout

Five problems, and 33 synchronous calls for one checkout. Each needs a decision, not a workaround such as a cache in front of a chatty call.

04. Steps 3 to 6: four decisions

Step 3: one owner for promo_rules. The loyalty team stored its member-only offers as promotion rules, so two services write one table and neither can change its schema alone. Ownership goes to the service whose rules give the table its meaning. A member offer is a price rule that depends on the customer's tier, so the rule belongs with pricing; loyalty owns the tier and announces changes with a MemberTierChanged event, from which pricing keeps a read-only member_tier_copy.

Step 4: merge promotions back into pricing. The two make 12 calls to each other per basket, speak the same language of price rules, are owned by the same team and change together whenever a campaign launches. As separate services they would be released together anyway, so separating them buys nothing and costs 12 network calls. Merged, the calls become function calls. Then make the remaining edge coarse: cart sends the whole basket in one pricing call and gets every line priced. What if promotions belonged to a separate marketing team that released daily, and pricing needed only a nightly snapshot of its rules? Then the interaction would be one nightly feed rather than 12 calls per basket, and keeping them apart could be right. The decision follows the interaction, not the names.

Step 5: break the pricing-loyalty-cart cycle. Pricing no longer calls loyalty, because it reads tiers from its own copy. Loyalty's points preview used to call cart to read the basket; reverse it, so that cart sends the basket total and loyalty returns the points. The rule of thumb: a caller passes the data the callee needs, and the callee does not call back.

Step 6: break the orders-fulfilment cycle. Orders waited while fulfilment created a shipment, and fulfilment called orders to read the lines and address back. The customer does not need a shipment to exist before seeing order confirmed, so orders publishes OrderPlaced carrying the lines and address, and fulfilment builds its own order_copy from it. Notifications and loyalty listen to the same event. Neither side waits for the other, and a fulfilment outage delays shipping instead of blocking checkout. Lesson 5 looks at that choice in more depth.

Python · revised.py
"""revised.py: the same checkout after the four decisions in this lesson."""
from boundaries import check

OWNS = {
    "catalogue": ["products", "categories"],
    "pricing": ["price_lists", "promo_rules", "coupons", "member_tier_copy"],
    "inventory": ["stock_levels", "reservations"],
    "cart": ["carts", "cart_lines"],
    "orders": ["orders", "order_lines"],
    "payments": ["payment_attempts"],
    "fulfilment": ["shipments", "pick_lists", "order_copy"],
    "customers": ["customers", "addresses"],
    "loyalty": ["members", "points_ledger"],
    "notifications": ["sent_messages"],
}
CALLS = {
    ("cart", "pricing"): 1,     # one call prices the whole basket
    ("cart", "loyalty"): 1,     # sends the total; 200 ms timeout, no points if down
    ("orders", "cart"): 1,
    ("orders", "inventory"): 1,
    ("orders", "payments"): 1,
    ("orders", "customers"): 1,
}
# Off the synchronous path, as events: OrderPlaced is consumed by fulfilment,
# loyalty and notifications; MemberTierChanged keeps pricing's tier copy current.
check(OWNS, CALLS)
Terminal
python3 revised.py
Expected output
10 services, 6 sync edges, 6 sync calls per checkout
  no problems found

05. Step 7: the ownership table and the teams

Constraint 4 needs a check by hand, because the checker cannot see it. Of the six synchronous calls left, five reach services checkout cannot work without; the sixth, cart to loyalty for the points preview, reaches a non-essential service, so it gets a 200 ms timeout and the basket is shown without points when loyalty is slow or down. Everything else non-essential is reached through events. With all four constraints met, write the result as the table the practice deliverable asks for. Each team owns whole services, so no boundary cuts through one team's daily work, and a typical change needs one team (Conway's law from lesson 1, used on purpose). Inside each service, tactical DDD shapes the model.

Text · Tarnside Outfitters, revised decomposition
service       team       owns                      publishes          sync API: caller
------------- ---------- ------------------------- ------------------ ------------------
catalogue     Discovery  products, categories      ProductChanged     web
pricing       Pricing    price_lists, promo_rules, PriceChanged       price basket: cart
                         coupons, member_tier_copy
cart          Checkout   carts, cart_lines         -                  basket: orders
orders        Checkout   orders, order_lines       OrderPlaced        place order: web
inventory     Fulfilment stock_levels,             StockReserved      reserve: orders
                         reservations
fulfilment    Fulfilment shipments, pick_lists,    ShipmentDispatched -
                         order_copy
payments      Payments   payment_attempts          PaymentCaptured    authorise: orders
customers     Customer   customers, addresses      AddressChanged     address: orders
loyalty       Customer   members, points_ledger    MemberTierChanged  points: cart
notifications Customer   sent_messages             -                  -

Every copy, such as member_tier_copy or order_copy, is owned by the service that keeps it but is fed only by the original owner's events: a consumer does not edit its copy to fix the source; corrections go to the owner. The checker sees only synchronous calls, so a loop of events, such as A reacting to B's event by publishing one that B reacts to, needs its own review.

06. Check your understanding

Practice check · 3 questions

Boundaries and ownership

Apply the steps of this lesson to new cases.

Q1. A draft has these synchronous calls: Returns calls Orders, Orders calls Payments, and Payments calls Returns to check whether a refund is pending. No two services call each other directly. What will boundaries.py report?
Q2. Merchandisers edit list prices on the same admin screen where they edit product descriptions. Catalogue and Pricing both claim `list_price`, while discounts, price history and the rules that check prices all live in Pricing. Which owner fits?
Q3. After the revision, boundaries.py reports no problems. Later, Pricing reacts to `MemberTierChanged` by recomputing member prices and publishing `MemberPricesChanged`, and Loyalty reacts to that by recomputing the tier, which publishes `MemberTierChanged` again. Why did the checker not warn?
Practice only: not graded, not saved, not evidence.

07. Apply it

Build the core of the practice deliverable for your online grocery with delivery slots.

  1. List its capabilities, then mark words that change meaning between them, such as slot, order or substitution.
  2. Write OWNS and CALLS for a first draft, counting calls for one checkout of a typical basket, and run boundaries.py.
  3. Fix every problem with one of this lesson's moves (single owner, merge, coarser call, reversed call, event), and note which move you used and why.
  4. Write the ownership table with team, data owned, events published and synchronous APIs. Trace one failure path, such as a cancelled delivery slot, before you trust the graph.

08. Review prompt

Without looking back: explain why capabilities and bounded contexts make better service boundaries than layers or tables, and how a changing word reveals a context boundary. Name the five problems the checker found in the Tarnside draft and the move that fixed each. Explain when keeping two services separate would be right even though they talk to each other.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check