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 4 of 5 · Lab · 30 min · revision 1

Finding bounded contexts and drawing the context map

Lab: group the courier company's EventStorming board into bounded contexts with stated heuristics and glossaries, record the context map as a TOML file with a named pattern for every relationship, and check it with a Python script against a reference map and a deliberately broken one.

Contentsand lesson path

What you will learn

  • Draw bounded contexts with their ubiquitous language and a context map naming each relationship pattern (for example customer-supplier, anti-corruption layer, open host service).

01. Goal and setup

In this lab you turn the EventStorming board from lesson 2 into bounded contexts and a context map, checked by a script. Every event, command and policy goes into a context with a stated heuristic and a small glossary, and every relationship gets a pattern name from the DDD Reference. The checker tests consistency, not wisdom, so step 4 compares your map with an explained reference and step 5 breaks the reference on purpose.

You need: Python 3.11 or newer, whose standard library reads TOML with tomllib; no packages. The lab was run with Python 3.12.13, and the outputs are identical on 3.11 and 3.14.

Project layout
context-lab/
├── board.toml       step 1: the typed-up EventStorming wall from lesson 2
├── check_map.py     step 1: checks a context map against the board
├── start.toml       step 2: your map, started with the Booking context
├── reference.toml   step 4: one reasonable map, for comparison
├── draw_map.py      step 4: prints a map as a Mermaid diagram
└── break_map.py     step 5: writes broken.toml with five mistakes
Terminal
mkdir context-lab && cd context-lab
python3 --version
Illustrative output (any version from 3.11 works)
Python 3.12.13

02. Step 1: The board and the checker

Create board.toml with the content below: the typed-up board from the end of lesson 2.

TOML · board.toml
# Hopwell Couriers: the EventStorming wall, typed up after the session.

# Orange notes, in timeline order.
events = [
    "Delivery booked",
    "Delivery window chosen",
    "Booking cancelled",
    "Booking cutoff passed",
    "Evening routes planned",
    "Sort labels printed",
    "Collection list issued",
    "Parcel collected",
    "Collection attempt failed",
    "Parcel received at hub",
    "Parcel damage recorded",
    "Route assigned to courier",
    "ETA message sent",
    "Route started",
    "Parcel delivered",
    "Delivery confirmation sent",
    "Window missed",
    "Delivery attempt failed",
    "Route replanned",
    "Stop order sent to courier",
    "Parcel returned to shop",
    "Delivery charge recorded",
    "Delivery fee credited",
    "Month closed",
    "Monthly invoices issued",
]

# Events that the clock causes, not a person or a policy.
clock = ["Booking cutoff passed", "Month closed"]

# Blue notes: command = { by = who issues it, causes = the event it causes }.
# by = "policy" means a lilac policy note issues the command.
[commands]
"Book delivery" = { by = "Shop assistant", causes = "Delivery booked" }
"Choose delivery window" = { by = "Recipient", causes = "Delivery window chosen" }
"Cancel booking" = { by = "Shop assistant", causes = "Booking cancelled" }
"Plan evening routes" = { by = "policy", causes = "Evening routes planned" }
"Print sort labels" = { by = "policy", causes = "Sort labels printed" }
"Issue collection list" = { by = "policy", causes = "Collection list issued" }
"Collect parcel" = { by = "Courier", causes = "Parcel collected" }
"Report collection failure" = { by = "Courier", causes = "Collection attempt failed" }
"Receive parcel at hub" = { by = "Hub operator", causes = "Parcel received at hub" }
"Record parcel damage" = { by = "Hub operator", causes = "Parcel damage recorded" }
"Assign route" = { by = "Dispatcher", causes = "Route assigned to courier" }
"Send ETA message" = { by = "policy", causes = "ETA message sent" }
"Start route" = { by = "Courier", causes = "Route started" }
"Confirm delivery" = { by = "Courier", causes = "Parcel delivered" }
"Send delivery confirmation" = { by = "policy", causes = "Delivery confirmation sent" }
"Flag missed window" = { by = "policy", causes = "Window missed" }
"Report failed attempt" = { by = "Courier", causes = "Delivery attempt failed" }
"Replan route" = { by = "policy", causes = "Route replanned" }
"Send stop order to courier" = { by = "policy", causes = "Stop order sent to courier" }
"Return parcel to shop" = { by = "policy", causes = "Parcel returned to shop" }
"Record delivery charge" = { by = "policy", causes = "Delivery charge recorded" }
"Credit delivery fee" = { by = "policy", causes = "Delivery fee credited" }
"Issue monthly invoices" = { by = "policy", causes = "Monthly invoices issued" }

# Lilac notes: whenever <when> happens, issue the command <then>.
[policies."Plan at the cutoff"]
when = "Booking cutoff passed"
then = "Plan evening routes"

[policies."Collect what was booked"]
when = "Booking cutoff passed"
then = "Issue collection list"

[policies."Label parcels for their routes"]
when = "Evening routes planned"
then = "Print sort labels"

[policies."Tell recipients when to expect us"]
when = "Route assigned to courier"
then = "Send ETA message"

[policies."Confirm each delivery"]
when = "Parcel delivered"
then = "Send delivery confirmation"

[policies."Check the window promise"]
when = "Parcel delivered"
then = "Flag missed window"

[policies."Replan after a failed stop"]
when = "Delivery attempt failed"
then = "Replan route"

[policies."Keep couriers' stops current"]
when = "Route replanned"
then = "Send stop order to courier"

[policies."Second failure goes back to the shop"]
when = "Delivery attempt failed"
then = "Return parcel to shop"

[policies."Charge each delivery"]
when = "Parcel delivered"
then = "Record delivery charge"

[policies."Missed window means free delivery"]
when = "Window missed"
then = "Credit delivery fee"

[policies."Invoice at month end"]
when = "Month closed"
then = "Issue monthly invoices"

# Pink notes: questions the room could not settle, next to the event they concern.
[[hotspots]]
near = "Parcel delivered"
question = "Does a parcel left in a safe place count as delivered?"

[[hotspots]]
near = "Window missed"
question = "Who decides that a window was missed?"

[[hotspots]]
near = "Parcel damage recorded"
question = "Who pays when a parcel is damaged before the hub?"

[[hotspots]]
near = "Route replanned"
question = "How late can we replan and still keep couriers' trust?"

Now create the checker. Read it before you run it; each numbered comment starts one group of rules.

Python · check_map.py
"""Check a context map against the EventStorming board it was drawn from.

Usage: python check_map.py board.toml map.toml   (exit code 1 when there are errors)
"""
import sys
import textwrap
import tomllib
from collections import defaultdict

KINDS = ["partnership", "shared-kernel", "customer-supplier",
         "upstream-downstream", "separate-ways"]
SYMMETRIC = {"partnership", "shared-kernel", "separate-ways"}
UPSTREAM_ROLES = {"open-host-service", "published-language"}
DOWNSTREAM_ROLES = {"conformist", "anticorruption-layer"}
ABBR = {"open-host-service": "OHS", "published-language": "PL",
        "conformist": "CF", "anticorruption-layer": "ACL"}
errors = []


def error(rule, text):
    errors.append(f"ERROR {rule}: {text}")


def count(n, word, plural=None):
    return f"{n} {word if n == 1 else plural or word + 's'}"


def load(path):
    with open(path, "rb") as f:
        return tomllib.load(f)


board, cmap = load(sys.argv[1]), load(sys.argv[2])
commands, policies = board["commands"], board["policies"]
contexts = cmap.get("contexts", {})
relationships = cmap.get("relationships", [])
NOTES = {"event": board["events"], "command": commands, "policy": policies}
PLURAL = {"event": "events", "command": "commands", "policy": "policies"}

# 1. Every note on the board sits in exactly one context.
owner = {}  # (kind, name) -> context name
for ctx_name, ctx in contexts.items():
    for kind, known in NOTES.items():
        for name in ctx.get(PLURAL[kind], []):
            if name not in known:
                error("unknown-note",
                      f'{kind} "{name}" in {ctx_name} is not on the board')
            elif (kind, name) in owner:
                error("placed-twice",
                      f'{kind} "{name}" is in {owner[kind, name]} and {ctx_name}')
            else:
                owner[kind, name] = ctx_name
for kind, known in NOTES.items():
    missing = [name for name in known if (kind, name) not in owner]
    if missing:
        names = textwrap.fill(", ".join(missing), 80, initial_indent="    ",
                              subsequent_indent="    ")
        error("unplaced", f"{count(len(missing), kind, PLURAL[kind])} in no context:\n"
              + names)

# 2. A command lives with the event it causes, a policy with the command it issues.
for name, cmd in commands.items():
    here, there = owner.get(("command", name)), owner.get(("event", cmd["causes"]))
    if here and there and here != there:
        error("command-split", f'"{name}" is in {here}, its event is in {there}')
for name, pol in policies.items():
    here, there = owner.get(("policy", name)), owner.get(("command", pol["then"]))
    if here and there and here != there:
        error("policy-split", f'"{name}" is in {here}, its command is in {there}')

# 3. An internal context owns events, states its heuristic and defines its terms.
for ctx_name, ctx in contexts.items():
    if ctx.get("external"):
        continue
    if not ctx.get("events"):
        error("empty-context", f"{ctx_name} owns no events")
    if not ctx.get("why"):
        error("no-reason", f"{ctx_name} has no 'why': name the heuristic you used")
    if len(ctx.get("glossary", {})) < 2:
        error("glossary", f"{ctx_name} defines fewer than 2 terms")


def arrow(rel):
    """Context Mapper style: Upstream [OHS,PL] -> [ACL] Downstream, or A <-> B."""
    if rel.get("kind") in SYMMETRIC:
        return " <-> ".join(map(str, rel.get("contexts", [])))
    up = ",".join(ABBR.get(r, r) for r in rel.get("upstream_roles", []))
    down = ",".join(ABBR.get(r, r) for r in rel.get("downstream_roles", []))
    return (f"{rel.get('upstream')}{f' [{up}]' if up else ''} ->"
            f"{f' [{down}]' if down else ''} {rel.get('downstream')}")


# 4. Each relationship names a pattern, a direction and roles on the right side.
pairs = {}  # frozenset of two context names -> (kind, [upstream, downstream])
for rel in relationships:
    kind, label = rel.get("kind"), arrow(rel)
    names = rel.get("contexts", []) if kind in SYMMETRIC else [
        rel.get("upstream"), rel.get("downstream")]
    if kind not in KINDS:
        error("unknown-kind", f'{label}: "{kind}" is not one of {", ".join(KINDS)}')
        continue
    if len(names) != 2 or names[0] == names[1] or not set(names) <= set(contexts):
        error("unknown-context", f"{label}: name two different contexts of the map")
        continue
    up, down = rel.get("upstream_roles", []), rel.get("downstream_roles", [])
    for role in up + down:
        if role not in ABBR:
            error("unknown-role", f'{label}: "{role}" is not one of {", ".join(ABBR)}')
    for role in set(up) & DOWNSTREAM_ROLES:
        error("role-side", f"{label}: {role} is a downstream role, listed upstream")
    for role in set(down) & UPSTREAM_ROLES:
        error("role-side", f"{label}: {role} is an upstream role, listed downstream")
    if kind in SYMMETRIC and up + down:
        error("symmetric-roles", f"{label}: {kind} has no upstream or downstream")
    if {"conformist", "anticorruption-layer"} <= set(down):
        error("protect-or-conform", f"{label}: the downstream conforms or translates,"
              " not both")
    if kind == "customer-supplier" and "conformist" in down:
        error("customer-conformist", f"{label}: a customer negotiates; it does not"
              " just conform")
    if "conformist" in down:  # a conformist speaks the upstream's language
        upstream = contexts[names[0]].get("glossary", {})
        theirs = {t.lower(): m for t, m in upstream.items()}  # terms ignore case
        for term, meaning in contexts[names[1]].get("glossary", {}).items():
            if theirs.get(term.lower(), meaning) != meaning:
                error("conformist-terms", f"{label}: a conformist shares the upstream's"
                      f' words, but {names[1]} gives "{term}" its own meaning')
    if kind == "upstream-downstream" and not up + down:
        error("no-pattern", f"{label}: name the roles, or use customer-supplier")
    if not rel.get("why"):
        error("no-reason", f"{label}: the relationship has no 'why'")
    if frozenset(names) in pairs:
        error("duplicate", f"{label}: these contexts already have a relationship")
        continue
    pairs[frozenset(names)] = (kind, names)

# 5. Every policy that crosses a boundary needs a relationship in the same direction.
flows = defaultdict(list)  # (context of the event, context of the policy) -> policies
for name, pol in policies.items():
    source, target = owner.get(("event", pol["when"])), owner.get(("policy", name))
    if source and target and source != target:
        flows[source, target].append(name)
reported = set()
for (src, dst), names in flows.items():
    kind, declared = pairs.get(frozenset((src, dst)), (None, None))
    reacts = f'{dst} reacts to {src} ("{names[0]}")'
    if kind is None:
        error("missing-relationship", f"{reacts}, but they have no relationship")
    elif kind == "separate-ways":
        error("separate-ways-crossed", f"{reacts}, but the map says separate ways")
    elif kind in SYMMETRIC or declared == [src, dst]:
        continue
    elif (dst, src) in flows:
        if frozenset((src, dst)) not in reported:
            reported.add(frozenset((src, dst)))
            error("mutual-dependency", f"{src} and {dst} react to each other's events,"
                  f" which {kind} cannot express")
    else:
        error("reversed", f"{reacts}, but the map makes {dst} upstream of {src}")

# 6. Report.
external = sum(1 for ctx in contexts.values() if ctx.get("external"))
print(f"Board: {count(len(board['events']), 'event')}, "
      f"{count(len(commands), 'command')}, "
      f"{count(len(policies), 'policy', 'policies')}")
print(f"Map: {count(len(contexts), 'context')} ({external} external), "
      f"{count(len(relationships), 'relationship')}")
if not errors:
    print(f"\n{'Context':<14}{'Events':>7}{'Commands':>10}{'Policies':>10}{'Terms':>7}")
    for ctx_name, ctx in contexts.items():
        print(f"{ctx_name:<14}{len(ctx.get('events', [])):>7}"
              f"{len(ctx.get('commands', [])):>10}{len(ctx.get('policies', [])):>10}"
              f"{len(ctx.get('glossary', {})):>7}")
    print("\nRelationships")
    for rel in relationships:
        print(f"  {arrow(rel):<40}{rel['kind']}")
    used = defaultdict(list)
    for ctx_name, ctx in contexts.items():
        for term in ctx.get("glossary", {}):
            used[term.lower()].append(ctx_name)
    print("\nTerms with a meaning in more than one context")
    for term, names in sorted(used.items()):
        if len(names) > 1:
            print(f"  {term}: {', '.join(names)}")
print()
for message in errors:
    first, _, rest = message.partition("\n")
    print(textwrap.fill(first, 86, subsequent_indent="    "))
    if rest:
        print(rest)
print(f"{count(len(errors), 'error')}: {'FAIL' if errors else 'PASS'}")
sys.exit(1 if errors else 0)

A map is a TOML file. Each [contexts.<Name>] table lists the events, commands and policies that the context owns, a why that states the heuristic behind the boundary, and glossary.<term> entries for its ubiquitous language. external = true marks a context you do not build, such as a bought product. Each [[relationships]] table has a kind, then either upstream and downstream or, for the symmetric kinds, contexts, plus optional roles and a why. These are the rules the checker applies:

The rules in check_map.py
Placement   every event, command and policy is in exactly one context
            a command sits with the event it causes
            a policy sits with the command it issues: the side that reacts
Contexts    an internal context owns events, has a why and 2+ glossary terms
Kinds       partnership, shared-kernel        contexts = [A, B]
            separate-ways                     contexts = [A, B], no integration
            customer-supplier                 upstream = U, downstream = D
            upstream-downstream               upstream = U, downstream = D
Roles       upstream:   open-host-service (OHS), published-language (PL)
            downstream: conformist (CF), anticorruption-layer (ACL)
            CF and ACL exclude each other; symmetric kinds take no roles;
            customer-supplier takes no CF; plain upstream-downstream needs a role;
            a CF downstream gives no upstream glossary term a meaning of its own
            (terms match ignoring case; a CF should copy the upstream wording)
Flows       a policy that reacts to another context's event needs a relationship
            in which that context is upstream, or a partnership or shared kernel;
            two contexts that react to each other need one of those two

The pattern names come from the DDD Reference. The role-side, CF and ACL, symmetric and customer-supplier rules follow Context Mapper, an open-source tool for writing context maps as text, whose authors note that the books are ambiguous in places. The conformist-terms rule applies the Reference's Conformist pattern, in which the downstream shares the upstream's language. The rest are this lab's own heuristics, including the role that a plain upstream-downstream relationship needs. For example, two contexts that react to each other's events usually depend on each other, so the checker asks for a partnership or shared kernel. The output prints relationships in a style close to Context Mapper's: Last Mile [OHS,PL] -> [CF] Messaging means Last Mile is upstream and offers an open host service with a published language, and Messaging is a conformist downstream.

One idea needs care: upstream and downstream describe influence, not data flow or who calls whom. The DDD Reference defines the upstream group as the one whose actions affect the downstream's success, while the downstream's actions do not significantly affect the upstream. A context that publishes events is usually upstream of its consumers, and when a downstream pulls data through an API, the context that owns the model is still upstream.

03. Step 2: Start from Booking

Create your own map, start.toml, with one finished context as an example: Booking, which ends at the pivotal event Booking cutoff passed.

TOML · start.toml
# My context map for board.toml. Booking is done as an example; add the rest.

[contexts.Booking]
why = "Shops and recipients; ends at the pivotal event Booking cutoff passed"
events = ["Delivery booked", "Delivery window chosen", "Booking cancelled",
          "Booking cutoff passed"]
commands = ["Book delivery", "Choose delivery window", "Cancel booking"]
glossary.delivery = "A shop's request to take one parcel to one recipient today"
glossary.window = "The two-hour evening slot the recipient picked"
glossary.cutoff = "13:00; anything booked later goes out the next day"
Terminal
python3 check_map.py board.toml start.toml
Expected output
Board: 25 events, 23 commands, 12 policies
Map: 1 context (0 external), 0 relationships

ERROR unplaced: 21 events in no context:
    Evening routes planned, Sort labels printed, Collection list issued, Parcel
    collected, Collection attempt failed, Parcel received at hub, Parcel damage
    recorded, Route assigned to courier, ETA message sent, Route started, Parcel
    delivered, Delivery confirmation sent, Window missed, Delivery attempt
    failed, Route replanned, Stop order sent to courier, Parcel returned to
    shop, Delivery charge recorded, Delivery fee credited, Month closed, Monthly
    invoices issued
ERROR unplaced: 20 commands in no context:
    Plan evening routes, Print sort labels, Issue collection list, Collect
    parcel, Report collection failure, Receive parcel at hub, Record parcel
    damage, Assign route, Send ETA message, Start route, Confirm delivery, Send
    delivery confirmation, Flag missed window, Report failed attempt, Replan
    route, Send stop order to courier, Return parcel to shop, Record delivery
    charge, Credit delivery fee, Issue monthly invoices
ERROR unplaced: 12 policies in no context:
    Plan at the cutoff, Collect what was booked, Label parcels for their routes,
    Tell recipients when to expect us, Confirm each delivery, Check the window
    promise, Replan after a failed stop, Keep couriers' stops current, Second
    failure goes back to the shop, Charge each delivery, Missed window means
    free delivery, Invoice at month end
3 errors: FAIL

The three unplaced lists are your to-do list, in timeline order.

04. Step 3: Group the rest and name the relationships

Work through the lists in start.toml using these heuristics, and write the one you used in each context's why:

  1. Pivotal events are natural edges. The tape marks from lesson 2 are where the people and the words change.
  2. Follow the language. If a word changes meaning, as route does between hub staff and dispatchers, you are probably crossing a boundary. Your glossary entries should show it.
  3. Follow the people and their reasons for change. Notes that the same experts decide, and that change for the same business reasons, belong together.
  4. Keep the core small and separate. Window promise planning from lesson 3 deserves its own context, undiluted by booking forms or invoice lines.
  5. Commands go with their events, policies with the side that reacts. The checker enforces both.

Run the checker often. Once nothing is unplaced, it reports missing-relationship for each pair where one context reacts to the other; add a [[relationships]] table for each, choosing the pattern by asking:

  • Does the downstream team have a real say in the upstream team's plans? Then customer-supplier.
  • Does the upstream offer one documented interface to many consumers? Then open host service, often with a published language such as a documented event schema.
  • Will the downstream take the upstream model as it is? Then conformist. Will it translate it into its own terms? Then anticorruption layer.
  • Do they succeed or fail together? Then partnership, or a small shared kernel of code they own together.
  • Do they not need to integrate at all? Then separate ways.

Keep going until the output ends with:

Expected output (last line, once your map is consistent)
0 errors: PASS

05. Step 4: Compare with a reference map

Here is one reasonable map. Save it as reference.toml and check it.

TOML · reference.toml
# Hopwell Couriers: one reasonable context map for board.toml.

[contexts.Booking]
why = "Shops and recipients; ends at the pivotal event Booking cutoff passed"
events = ["Delivery booked", "Delivery window chosen", "Booking cancelled",
          "Booking cutoff passed"]
commands = ["Book delivery", "Choose delivery window", "Cancel booking"]
glossary.delivery = "A shop's request to take one parcel to one recipient today"
glossary.window = "The two-hour evening slot the recipient picked"
glossary.cutoff = "13:00; anything booked later goes out the next day"

[contexts.Hub]
why = "Hub staff and their scanners; parcels as physical things"
events = ["Sort labels printed", "Collection list issued", "Parcel collected",
          "Collection attempt failed", "Parcel received at hub",
          "Parcel damage recorded"]
commands = ["Print sort labels", "Issue collection list", "Collect parcel",
            "Report collection failure", "Receive parcel at hub",
            "Record parcel damage"]
policies = ["Label parcels for their routes", "Collect what was booked"]
glossary.parcel = "A labelled item that the hub can scan, store and load"
glossary.route = "The shelf and van that a parcel is sorted to"

[contexts.Planning]
why = "The core: rules that keep the window promise change weekly"
events = ["Evening routes planned", "Route assigned to courier", "Route replanned"]
commands = ["Plan evening routes", "Assign route", "Replan route"]
policies = ["Plan at the cutoff", "Replan after a failed stop"]
glossary.route = "An ordered list of stops for one courier for one evening"
glossary.stop = "A planned arrival at an address, with its window to keep"
glossary.window = "A hard time limit that a stop's arrival must fall inside"

[contexts."Last Mile"]
why = "Couriers on the road: every handover, failed visit and return"
events = ["Route started", "Parcel delivered", "Window missed",
          "Delivery attempt failed", "Stop order sent to courier",
          "Parcel returned to shop"]
commands = ["Start route", "Confirm delivery", "Flag missed window",
            "Report failed attempt", "Send stop order to courier",
            "Return parcel to shop"]
policies = ["Check the window promise", "Keep couriers' stops current",
            "Second failure goes back to the shop"]
glossary.stop = "A doorstep where the courier hands parcels over"
glossary.delivery = "A completed handover, with a photo or signature as proof"
glossary.attempt = "A visit that ended without a handover"

[contexts.Messaging]
why = "What recipients are told and when; templates change for marketing reasons"
events = ["ETA message sent", "Delivery confirmation sent"]
commands = ["Send ETA message", "Send delivery confirmation"]
policies = ["Tell recipients when to expect us", "Confirm each delivery"]
glossary.eta = "A 30-minute range shown to the recipient"
glossary.recipient = "The person who receives the parcel and the messages"

[contexts.Billing]
why = "Finance language: charges, credits and invoices"
events = ["Delivery charge recorded", "Delivery fee credited", "Month closed",
          "Monthly invoices issued"]
commands = ["Record delivery charge", "Credit delivery fee", "Issue monthly invoices"]
policies = ["Charge each delivery", "Missed window means free delivery",
            "Invoice at month end"]
glossary.delivery = "A chargeable line on a shop's monthly invoice"
glossary.credit = "A fee given back because a window was missed"

[contexts."Route Solver"]
external = true
why = "Bought vehicle-routing service: a generic subdomain"

[[relationships]]
kind = "customer-supplier"
upstream = "Booking"
downstream = "Planning"
why = "Planning is the core, so its needs go into Booking's plans"

[[relationships]]
kind = "upstream-downstream"
upstream = "Booking"
downstream = "Hub"
downstream_roles = ["conformist"]
why = "Hub takes the bookings exactly as Booking defines them"

[[relationships]]
kind = "upstream-downstream"
upstream = "Planning"
downstream = "Hub"
upstream_roles = ["open-host-service", "published-language"]
downstream_roles = ["anticorruption-layer"]
why = "Hub turns each planned route into its own shelves and van loads"

[[relationships]]
kind = "partnership"
contexts = ["Planning", "Last Mile"]
why = "Each reacts to the other's events; the teams plan releases together"

[[relationships]]
kind = "upstream-downstream"
upstream = "Planning"
downstream = "Messaging"
upstream_roles = ["open-host-service", "published-language"]
downstream_roles = ["conformist"]
why = "Messaging uses Planning's route feed exactly as published"

[[relationships]]
kind = "upstream-downstream"
upstream = "Last Mile"
downstream = "Messaging"
upstream_roles = ["open-host-service", "published-language"]
downstream_roles = ["conformist"]
why = "Last Mile publishes documented delivery events"

[[relationships]]
kind = "upstream-downstream"
upstream = "Last Mile"
downstream = "Billing"
upstream_roles = ["open-host-service", "published-language"]
downstream_roles = ["anticorruption-layer"]
why = "Billing turns delivery events into its own charges and credits"

[[relationships]]
kind = "upstream-downstream"
upstream = "Route Solver"
downstream = "Planning"
upstream_roles = ["open-host-service"]
downstream_roles = ["anticorruption-layer"]
why = "The vendor's API is generic; Planning keeps its own words for routes"
Terminal
python3 check_map.py board.toml reference.toml
Expected output
Board: 25 events, 23 commands, 12 policies
Map: 7 contexts (1 external), 8 relationships

Context        Events  Commands  Policies  Terms
Booking             4         3         0      3
Hub                 6         6         2      2
Planning            3         3         2      3
Last Mile           6         6         3      3
Messaging           2         2         2      2
Billing             4         3         3      2
Route Solver        0         0         0      0

Relationships
  Booking -> Planning                     customer-supplier
  Booking -> [CF] Hub                     upstream-downstream
  Planning [OHS,PL] -> [ACL] Hub          upstream-downstream
  Planning <-> Last Mile                  partnership
  Planning [OHS,PL] -> [CF] Messaging     upstream-downstream
  Last Mile [OHS,PL] -> [CF] Messaging    upstream-downstream
  Last Mile [OHS,PL] -> [ACL] Billing     upstream-downstream
  Route Solver [OHS] -> [ACL] Planning    upstream-downstream

Terms with a meaning in more than one context
  delivery: Booking, Last Mile, Billing
  route: Hub, Planning
  stop: Planning, Last Mile
  window: Booking, Planning

0 errors: PASS

Compare it with your own map. A difference is not automatically a mistake, but you should be able to give a reason for each. The reference chose:

  • Six internal contexts and one external. Each internal context has its own people and words; Route Solver is the bought generic subdomain from lesson 3. The accounting product and SMS gateway are left out to keep the map small.
  • Planning is small on purpose. Its three events carry the core rules. An anticorruption layer keeps the vendor's route model out, and one published route feed serves every context that needs routes.
  • Booking to Planning is customer-supplier; Booking to Hub is conformist. Planning is the core, so its needs go into Booking's plans. The hub's needs do not, so it takes the bookings as Booking defines them. Same upstream, different influence.
  • Planning and Last Mile are partners. Each reacts to the other's events (Route replanned, Delivery attempt failed), which usually means each depends on the other. A partnership commits the teams to planning together; otherwise, move a policy so that the dependency runs one way.
  • Hub and Billing translate; Messaging conforms. Hub gives route its own meaning (shelf and van) and Billing keeps its own words (charge, credit), so both translate through an anticorruption layer, like two_contexts.py in lesson 1. Messaging uses the published feeds as they are, so it is conformist; the conformist-terms rule checks it.

The last block of the output lists terms with a meaning in more than one context: delivery in three, and route, stop and window in two, as lesson 1 predicted. Wherever a downstream gives an upstream word its own meaning, the map shows a translation: an anticorruption layer, or a simple translation agreed between cooperating teams (customer-supplier for window, partnership for stop).

To see the map drawn, print it as Mermaid with the script below and paste the output into the Mermaid Live Editor; external contexts get double-edged boxes. Draw your own map the same way.

Python · draw_map.py
"""Print a context map as a Mermaid flowchart. Usage: python draw_map.py map.toml"""
import sys
import tomllib

ABBR = {"open-host-service": "OHS", "published-language": "PL",
        "conformist": "CF", "anticorruption-layer": "ACL"}

with open(sys.argv[1], "rb") as f:
    cmap = tomllib.load(f)
contexts = cmap.get("contexts", {})
ids = {name: f"c{n}" for n, name in enumerate(contexts, start=1)}

print("flowchart LR")
for name, ctx in contexts.items():  # external contexts get a double-edged box
    print(f'  {ids[name]}[["{name}"]]' if ctx.get("external")
          else f'  {ids[name]}["{name}"]')
for rel in cmap.get("relationships", []):
    if "contexts" in rel:  # partnership, shared-kernel or separate-ways
        a, b = (ids[name] for name in rel["contexts"])
        link = "-.-" if rel["kind"] == "separate-ways" else "<-->"
        print(f'  {a} {link}|"{rel["kind"]}"| {b}')
    else:
        roles = " / ".join(",".join(ABBR[r] for r in rel.get(side, []))
                           for side in ("upstream_roles", "downstream_roles")
                           if rel.get(side))  # e.g. "OHS,PL / ACL"
        label = f'{rel["kind"]} ({roles})' if roles else rel["kind"]
        print(f'  {ids[rel["upstream"]]} -->|"{label}"| {ids[rel["downstream"]]}')
Terminal
python3 draw_map.py reference.toml
Expected output (Mermaid source)
flowchart LR
  c1["Booking"]
  c2["Hub"]
  c3["Planning"]
  c4["Last Mile"]
  c5["Messaging"]
  c6["Billing"]
  c7[["Route Solver"]]
  c1 -->|"customer-supplier"| c3
  c1 -->|"upstream-downstream (CF)"| c2
  c3 -->|"upstream-downstream (OHS,PL / ACL)"| c2
  c3 <-->|"partnership"| c4
  c3 -->|"upstream-downstream (OHS,PL / CF)"| c5
  c4 -->|"upstream-downstream (OHS,PL / CF)"| c5
  c4 -->|"upstream-downstream (OHS,PL / ACL)"| c6
  c7 -->|"upstream-downstream (OHS / ACL)"| c3

06. Step 5: Break it on purpose

The script below writes broken.toml, a copy of reference.toml with five common mistakes. It stops if your reference.toml differs from the one in step 4.

Python · break_map.py
"""Write broken.toml: a copy of reference.toml with five deliberate mistakes."""
from pathlib import Path

EDITS = [
    ('events = ["Delivery charge recorded",',
     'events = ["Parcel delivered", "Delivery charge recorded",'),
    ('"Parcel received at hub",\n          "Parcel damage recorded"]',
     '"Parcel received at hub"]'),
    ('downstream_roles = ["anticorruption-layer"]\nwhy = "Hub',
     'downstream_roles = ["conformist"]\nwhy = "Hub'),
    ('upstream = "Booking"\ndownstream = "Planning"',
     'upstream = "Planning"\ndownstream = "Booking"'),
    ('kind = "partnership"\ncontexts = ["Planning", "Last Mile"]',
     'kind = "upstream-downstream"\nupstream = "Planning"\n'
     'downstream = "Last Mile"\ndownstream_roles = ["anticorruption-layer"]'),
]
text = Path("reference.toml").read_text(encoding="utf-8").replace("\r\n", "\n")
for old, new in EDITS:
    if text.count(old) != 1:
        raise SystemExit(f"reference.toml differs from the lesson near {old[:30]!r}")
    text = text.replace(old, new)
Path("broken.toml").write_text(text, encoding="utf-8")
print(f"broken.toml written with {len(EDITS)} mistakes")
Terminal
python3 break_map.py
python3 check_map.py board.toml broken.toml
Expected output
broken.toml written with 5 mistakes
Board: 25 events, 23 commands, 12 policies
Map: 7 contexts (1 external), 8 relationships

ERROR placed-twice: event "Parcel delivered" is in Last Mile and Billing
ERROR unplaced: 1 event in no context:
    Parcel damage recorded
ERROR conformist-terms: Planning [OHS,PL] -> [CF] Hub: a conformist shares the
    upstream's words, but Hub gives "route" its own meaning
ERROR reversed: Planning reacts to Booking ("Plan at the cutoff"), but the map makes
    Planning upstream of Booking
ERROR mutual-dependency: Last Mile and Planning react to each other's events, which
    upstream-downstream cannot express
5 errors: FAIL

Decide how to fix each error before reading on:

  • placed-twice: Billing claims Parcel delivered, a fact about a handover that Last Mile owns; Billing only reacts to it.
  • unplaced: Parcel damage recorded fell off the map. It belongs in Hub, next to the command that causes it.
  • conformist-terms: Hub became a conformist of Planning but still uses route for shelves and vans. A conformist adopts the upstream's words, so Hub must use Planning's meaning or translate.
  • reversed: Planning reacts to Booking cutoff passed, so Booking is upstream. The arrow points the way influence flows.
  • mutual-dependency: the two contexts react to each other's events, which a one-way relationship cannot describe. Restore the partnership.

Fix broken.toml by hand until the checker prints 0 errors: PASS again.

07. Check your understanding

Practice check · 3 questions

Reading the map and the checker

Use the files from this lab to answer. Each question has one best answer.

Q1. Starting from `reference.toml`, you move the command *Record parcel damage* from Hub to Last Mile and change nothing else. What does `check_map.py` report?
Q2. Billing changes its design: instead of reacting to events, a nightly job calls a Last Mile API to fetch the day's handovers. In the context map, which context is upstream?
Q3. In your map, Planning reacts to a Last Mile event and Last Mile reacts to a Planning event, and you declared Planning upstream of Last Mile. The checker reports mutual-dependency. Which change fits best?
Practice only: not graded, not saved, not evidence.

08. Apply it: stretch tasks

  1. Your clinic map. Turn the clinic.toml board from lesson 2 into a map with three to six contexts, each with a why and a glossary, and get check_map.py to 0 errors: PASS.
  2. Add a rule. Context Mapper also forbids an open host service inside a customer-supplier relationship. Add that rule to check_map.py as a warning, then write a small map that triggers it.
  3. Try Context Mapper. Write the reference map in Context Mapper's CML language, for example Planning [U,OHS,PL] -> [D,ACL] Hub, and compare its diagram with the one from draw_map.py.

09. Review prompt

Without looking back:

  1. Why does a command belong to the context of the event it causes, and a policy to the context that reacts?
  2. What do upstream and downstream mean, and why is the direction not simply who calls whom?
  3. When would you choose a conformist downstream, and when an anticorruption layer?
  4. Why can a checker confirm that a map is consistent, but not that it is good?
  5. Which term appears in three contexts of the reference map, and what does each context mean by it?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

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