Platform Engineering · Lesson 169

Service Boundaries: Domain-Driven Design, Bounded Contexts, and Aggregates

The hardest design question is not inside a service. It is where one service ends and the next begins. Draw the line in the right place and teams ship independently, data has one owner, and a failure stays local. Draw it in the wrong place and you get a distributed monolith: every change needs four teams, every request crosses five network hops, and two services quietly write the same table. Domain-driven design gives you the tools to draw the line: a shared language, bounded contexts, aggregates that guard invariants, and a map of how contexts talk. This lesson follows one request, "please deliver to my neighbour instead", across the parcel company's contexts. By the end you can find boundaries from the domain, not from the org chart, and say what crosses each one and how.

Difficulty: Advanced · Know this first: Lesson 168, Lesson 47, Lesson 50

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar splits one address change, from the customer's request to the confirmation. It is a worked example, not a measurement. With clear boundaries the customer waits only for the owner; in a distributed monolith the slices of four other services are added to the customer's wait.

Try it: the cost of a synchronous chain

Move the sliders. Every service called synchronously adds its latency to the request and multiplies its availability into it. The context-map hop above follows your chain.

request availability = owner × each called service (owner 99.95 percent) · added latency = calls × latency · failing minutes per month = (1 − availability) × 43,200

99.55%availability of the change
~194failing minutes / month
400 mslatency added by the chain

The chain costs more than the owner's own error budget

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Boundary design grows in four levels: first one owner per piece of data, then bounded contexts and aggregates, then the context map and cross-boundary workflows, and finally boundaries that match teams and change over time.

Basic — One owner per fact

At the basic level a boundary is a promise about data: this service owns these facts, and it is the only one that changes them. Other services hold copies they receive, or ask the owner. You learn to list each service's facts and check that no fact has two writers.

Types:

  • Owned data: written only by the owning service, through its rules.
  • Copies: held by others for reading, refreshed from events or queries.
  • References: just an id pointing at the owner's record.

Uses: any system with more than one service, and any monolith being split.

Where it breaks: a shared database where every service can read and write every table. The boundaries exist in the deployment diagram and nowhere in the data, so every rule can be bypassed by someone.

Try it: Basic

Two services both update the delivery_address column. What is the first problem?

Now do it: List every table your service writes and check whether any other service writes it too.

Intermediate — Bounded contexts and aggregates

At the intermediate level you find boundaries from the language and guard rules inside aggregates. A bounded context is a region where every term has one meaning and one model. An aggregate is a cluster of objects changed together under one root, with invariants that must always hold, saved in one transaction.

Types:

  • Ubiquitous language: the shared vocabulary inside a context, used in code and in conversation.
  • Entities and value objects, as in the LLD lessons, now grouped into aggregates.
  • Aggregate root: the only entry point; outside code holds its id, not its internals.
  • Domain events: facts like DeliveryAddressChanged, named in the past tense.

Uses: designing services around business capabilities rather than database tables.

Scale and failure: aggregates that are too large, such as "Customer with all orders", serialise every change to a customer and lock under load. Keep aggregates as small as their invariants allow, and reference other aggregates by id.

Try it: Intermediate

Should Customer and all of a customer's orders be one aggregate?

Now do it: Pick one aggregate in your domain and write its invariants. Anything in it that no invariant needs is a candidate to split out.

Advanced — Context maps and workflows across boundaries

At the advanced level you design how contexts relate and how a business process that spans them stays consistent. The context map names each relationship. Cross-context workflows, like "change address, re-route, re-price, notify", become sagas: a series of local transactions connected by events, each with a compensating action if a later step fails.

Types:

  • Relationships: customer-supplier, conformist, anti-corruption layer, shared kernel, open host service.
  • Integration: domain events for facts, APIs for queries, never shared tables.
  • Sagas: choreographed by events or orchestrated by a coordinator, with compensations.
  • Eventual consistency budgets: how long a copy may lag, stated per consumer.

Uses: any business process spanning more than one service.

Scale and failure: each synchronous dependency multiplies into availability: an owner at 99.95 percent calling four services at 99.9 percent is about 99.55 percent, roughly 194 failing minutes a month. Events break that multiplication and cost you lag, ordering questions, and the need to design compensations.

Try it: Advanced

An address change must also re-price the delivery in Billing. Billing is sometimes down. What does the advanced design do?

Now do it: Use the chain simulator above: find how many 99.9 percent services can be called in line before the chain costs more than the owner's own error budget.

Master — Boundaries, teams, and change over time

At the master level boundaries are organisational as well as technical. Conway's law says systems mirror the communication structure of the teams that build them, so a boundary that cuts across a team, or a team that spans two contexts, will be redrawn by reality. You align contexts with teams, keep a modular monolith until a boundary has proven itself, and move boundaries with strangler migrations rather than rewrites.

Types:

  • Team-aligned contexts: one team owns one or a few contexts, end to end.
  • Modular monolith: contexts as modules with enforced dependencies, one deployment.
  • Strangler fig: route one capability at a time from the old system to the new.
  • Boundary health signals: lockstep releases, cross-team pull requests, shared tables, chatty calls.

Uses: growing engineering organisations and systems being split or merged.

Trade-off: every network boundary costs latency, partial failure, and operational work. A boundary is worth it when independent change and failure isolation are worth more than those costs; until then, a module boundary inside one deployment gives most of the clarity for little of the cost.

Try it: Master

A startup with eight engineers plans twelve microservices for v1. What does a master-level reviewer suggest?

Now do it: Check your last ten releases: which needed changes in more than one service at once? Each one points at a boundary in the wrong place.

Go deeper

A context map is the boundary design written down. It names every context, who owns which facts, and every relationship with its integration style. It fits on one page, and it is the first thing I ask for in a review of a multi-service design.

context        owns (writes)                        publishes                      consumes
Shipping       shipment, delivery address, attempts DeliveryAddressChanged,         OrderPlaced (from Sales)
                                                    ShipmentDispatched
Tracking       scan history, parcel status          ParcelStatusChanged            DeliveryAddressChanged (ACL)
Routing        routes, van assignments              RouteAssigned                  DeliveryAddressChanged
Billing        delivery charges, refunds            ChargeAdjusted                 DeliveryAddressChanged
Notifications  messages sent, preferences           -                              all of the above

relationships: Shipping -> Tracking/Routing/Billing  customer-supplier, events, ACL downstream
               Sales -> Shipping                     open host service (Orders API v2)
               shared kernel: none                   shared tables: none

One owner per fact, events across every line, and the last two lines written down on purpose: "none" is a design decision, not an omission.

Find shared writes before they find you

Given each service's list of tables it writes, this flags any table with more than one writer: the clearest sign of a boundary that exists only on paper.

# python3 shared_writes.py
writes = {
    "shipping":      {"shipments", "delivery_addresses", "attempts"},
    "tracking":      {"scan_history", "parcel_status", "delivery_addresses"},
    "routing":       {"routes", "van_assignments"},
    "billing":       {"charges", "refunds"},
}
owners = {}
for svc, tables in writes.items():
    for t in tables:
        owners.setdefault(t, []).append(svc)
for t, svcs in sorted(owners.items()):
    if len(svcs) > 1:
        print(f"SHARED WRITE: {t} written by {', '.join(sorted(svcs))}")
print("tables with one owner:", sum(1 for s in owners.values() if len(s) == 1), "of", len(owners))

Expected: one line, SHARED WRITE: delivery_addresses written by shipping, tracking, then tables with one owner: 8 of 9. In a real system, build the writes map from database audit logs or grants, not from what teams believe they write.

One time it broke

A parcel company I advised had split its monolith into services, but kept one database "for now". Tracking had a nightly job that normalised address formats for its search index, and it did the normalising in place, in the shared addresses table.

Timeline

  • 02:00The normalisation job runs and rewrites 40,000 addresses, including about 600 for parcels already loaded on vans.
  • 07:30Vans leave the depots. Driver apps refresh their manifests, and a few hundred stops move: "Flat 2" becomes "2", a building name disappears.
  • 11:00Failed-delivery reports spike. Drivers are at the right street and the wrong door.
  • 14:00The job is traced. Shipping's rule, no address changes after dispatch, lived in Shipping's code, and the job never went through Shipping.

What changed after

Each context got its own schema with grants that made other services' writes impossible, not just discouraged. Tracking kept its normalised copy in its own table, fed by DeliveryAddressChanged. The architecture review gained a standing question: show me the grants, not the diagram.

If you remember nothing else

Design exercise

A food-delivery company runs one large application handling restaurants, menus, orders, payments, courier dispatch, and customer support. Propose its bounded contexts, the owner of each key fact, and how an order flows across them.

Clarifying questions to ask

Does "order" mean the same thing to the restaurant, the courier, and payments? Which rules must be instantly true, such as "an order cannot be paid twice", and which can be eventual, such as "support sees the latest courier location"? How are the engineering teams organised today?

Rough sizing

Say 40 engineers in six teams, 30,000 orders an hour at the Friday peak. The peak matters less than the change rate: menus change hourly, payment rules quarterly, dispatch logic weekly.

Shape of the answer

Contexts: Catalogue (restaurants, menus), Ordering (cart, order aggregate), Payments (charges, refunds), Dispatch (couriers, assignments), Support (cases, read models). Order placed in Ordering, OrderPlaced to Payments and Dispatch, saga for "payment failed after dispatch" with a compensation. Context map with relationships, and a modular monolith first for the two least-proven contexts.

Trade-offs to name

Splitting Payments out early isolates compliance scope and adds a network hop to every checkout. Dispatch as its own context lets that team ship weekly without coordinating, at the cost of eventual consistency for order status. Support built on read models never writes other contexts' data, so it needs commands sent to the owners for every action.

Saved on this device, in this browser.
Next in this series · Lesson 170
Designing for Reliability and Operations: Failure Modes, SLOs, and Safe Rollout

A design that only describes the happy path is half a design. The other half answers the questions an SRE asks before go-live: what fails, how often, what the customer sees when it does, how we know, who gets woken, and how we…

Go to Lesson 170 →

Or browse the full course from the Lessons index.