Carving a big ball of mud into modules
Worked example: find the tangles and the shared tables in a small co-working app, turn its capabilities into modules with one owner per table, check that the target graph has no cycles, write the boundary contracts, and decide with stated triggers what may leave the process later.
Contentsand lesson path
On this page
- The problem: carving Deskwise
- Step 1: Find the knots
- Step 2: Name capabilities, not files
- Step 3: Give every table one owner
- Step 4: Break the cycles and check the plan
- Step 5: Write the boundary contracts
- Step 6: Decide what may leave the process, and when
- Check your understanding
- Apply it
- Review prompt
Lessons of Modular Monolith
- Why modular first: cost of distribution versus cost of coupling Concept · 15 min
- Module anatomy, owned tables and component principles Concept · 25 min
- Enforcing boundaries with architecture tests Lab · 25 min
- Cross-module calls, in-process events and transactions Concept · 20 min
- Carving a big ball of mud into modules Worked example · 30 min
- Modularity check Knowledge check · 6 questions
What you will learn
- Map bounded contexts to modules, each with a public API, hidden internals and a module-owned schema.
- Enforce module boundaries, including acyclic and stable dependency directions, with automated dependency checks that fail the build.
- Choose between direct calls and in-process events for cross-module communication and plan the seams that allow later extraction.
01. The problem: carving Deskwise
Suppose Deskwise runs co-working spaces. Its web application is four years old, written in Python by six developers, deployed as one unit with one PostgreSQL database. Members buy a plan, book desks and rooms, pay monthly invoices, open doors with a card and receive e-mails; the owners read reports. The code lives in eight flat files, and every change seems to touch three of them.
Your job is to carve it into modules without stopping feature work: no big-bang rewrite, and the product stays one deployment. At the end you need a module per capability with one owner per table, a dependency graph without cycles that CI checks, boundary contracts, and a short, conditional plan for what might leave the process later. One requirement comes from the owners: doors must open for members even when the building's internet link is down.
02. Step 1: Find the knots
Start from facts, not folder names. Two facts matter most: which file imports which, and which file writes which table. In a real codebase, collect the first with a tool such as import-linter's drawgraph command, and the second by searching for INSERT, UPDATE, DELETE and ORM save calls. Here both are typed into the script as data, with the target plan that later steps check.
"""carve.py: find the knots in the Deskwise code, then check a target module plan.
Usage: python3 carve.py mud
python3 carve.py target [from->to ...] (extra edges to try out)
"""
import sys
from graphlib import TopologicalSorter
MUD_IMPORTS = { # file -> files it imports
"members": ["bookings", "invoices", "doors", "emails", "models", "utils"],
"bookings": ["members", "invoices", "emails", "models", "utils"],
"invoices": ["members", "bookings", "emails", "models", "utils"],
"doors": ["members", "bookings", "models", "utils"],
"emails": ["models", "utils"],
"reports": ["models", "utils"],
"utils": ["models", "invoices"],
"models": ["utils"],
}
MUD_WRITES = { # table -> files that insert, update or delete its rows
"members": ["members", "doors"], "plans": ["members"],
"bookings": ["bookings", "invoices", "members"], "rooms": ["bookings"],
"invoices": ["invoices"], "invoice_lines": ["invoices", "bookings"],
"payments": ["invoices"], "door_cards": ["doors", "members"],
"door_events": ["doors"], "email_log": ["emails"],
}
TARGET_USES = { # module -> modules whose public API or events it uses
"shared_kernel": [],
"membership": ["shared_kernel"],
"booking": ["membership", "shared_kernel"],
"invoicing": ["membership", "booking", "shared_kernel"],
"access": ["membership", "booking", "shared_kernel"],
"notifications": ["membership", "booking", "invoicing", "shared_kernel"],
"reporting": ["membership", "booking", "invoicing", "access", "shared_kernel"],
}
TARGET_OWNS = { # module -> tables only it may write
"membership": ["members", "plans"], "booking": ["bookings", "rooms"],
"invoicing": ["invoices", "invoice_lines", "payments"],
"access": ["door_cards", "door_events"], "notifications": ["email_log"],
}
def tangles(graph):
"""Strongly connected components with more than one member (Tarjan, 1972)."""
index, low, stack, found = {}, {}, [], []
def visit(v):
index[v] = low[v] = len(index)
stack.append(v)
for w in graph.get(v, []):
if w not in index:
visit(w)
low[v] = min(low[v], low[w])
elif w in stack:
low[v] = min(low[v], index[w])
if low[v] == index[v]:
group = stack[stack.index(v):]
del stack[stack.index(v):]
if len(group) > 1:
found.append(sorted(group))
for v in graph:
if v not in index:
visit(v)
return found
def show_mud():
knots = tangles(MUD_IMPORTS)
for group in knots:
print("tangle:", ", ".join(group))
free = sorted(set(MUD_IMPORTS) - {f for g in knots for f in g})
print("outside any tangle:", ", ".join(free))
print("tables with more than one writer:")
for table, writers in MUD_WRITES.items():
if len(writers) > 1:
print(f" {table}: {', '.join(writers)}")
def check_target(extra):
uses = {m: list(deps) for m, deps in TARGET_USES.items()}
for edge in extra:
src, dst = edge.split("->")
uses[src].append(dst)
owned = [t for tables in TARGET_OWNS.values() for t in tables]
print("tables owned twice:", sorted({t for t in owned if owned.count(t) > 1}))
print("tables with no owner:", sorted(set(MUD_WRITES) - set(owned)))
knots = tangles(uses)
if knots:
print("tangles:", "; ".join(", ".join(g) for g in knots))
return
print("order, stable first:")
print(" " + " < ".join(TopologicalSorter(uses).static_order()))
print("module Ca Ce I")
for mod, deps in uses.items():
ca = sum(mod in d for d in uses.values())
print(f"{mod:<14}{ca:>4}{len(deps):>4}{len(deps) / (ca + len(deps)):>6.2f}")
if __name__ == "__main__":
if sys.argv[1:2] == ["mud"]:
show_mud()
else:
check_target(sys.argv[2:])python3 carve.py mudtangle: bookings, doors, emails, invoices, members, models, utils
outside any tangle: reports
tables with more than one writer:
members: members, doors
bookings: bookings, invoices, members
invoice_lines: invoices, bookings
door_cards: doors, membersA tangle here is a strongly connected component: a group of files in which every file can reach every other by following imports. The script finds them with Tarjan's algorithm from 1972. One tangle holds seven of the eight files, so none of them can be changed, tested or moved on its own; reports sits outside only because nothing imports it. Four tables have more than one writer, so the rules for their rows are spread over several files. Those two lists are the work to do.
03. Step 2: Name capabilities, not files
Modules come from what the business does, as the bounded contexts of strategic DDD do, not from the current files. Deskwise has six capabilities and one small shared piece:
- membership: plans, members, joining and leaving.
- booking: desks and rooms, availability and reservations.
- invoicing: invoices, invoice lines and payments.
- access: door cards and door events.
- notifications: e-mails, triggered by events of other modules.
- reporting: read-only views for the owners.
- shared_kernel: money, dates and the event bus, with no business rules.
There is no models module and no utils module. Each table class in models.py moves to its owner. utils.py is sorted helper by helper: money and date helpers go to the shared kernel, while a helper such as get_member_plan() moves into membership, the module whose rule it encodes. A utils that keeps growing becomes the next tangle.
04. Step 3: Give every table one owner
The owner of a table is the module whose rules decide how its rows change. For the four shared tables:
membersis written bydoors.py, which stores a last-seen time on every swipe. That is a fact about door use, so access derives it from its owndoor_events, and membership stops storing it.bookingsis written byinvoices.py, which flags booked days as invoiced, and bymembers.py, which cancels future bookings when someone leaves. Invoicing keeps its own record of what it billed (one invoice line per booking id), and booking cancels its own rows when it hears that a membership ended.invoice_linesis written bybookings.py. Invoicing creates each line itself when it hears that a booking was confirmed.door_cardsis written bymembers.pyto revoke cards. Access revokes them when it hears that a membership ended.
Every fix has the same shape: the outsider stops writing, and either asks the owner through its API or lets the owner react to an event. Not on the list: a trigger that copies rows, a wiki page about who may write, or merging two capabilities to make the conflict disappear.
05. Step 4: Break the cycles and check the plan
Now draw the target graph: for each module, the modules whose API or events it uses (TARGET_USES in the script). Booking needs an answer from membership (desk days left) before it books, so that is a call. Invoicing, access and notifications only react to facts, so they subscribe to events, and reporting reads them all. Nothing points back at membership. The target mode checks ownership, looks for tangles and computes instability per module, counting modules rather than classes.
python3 carve.py targettables owned twice: []
tables with no owner: []
order, stable first:
shared_kernel < membership < booking < invoicing < access < notifications < reporting
module Ca Ce I
shared_kernel 6 0 0.00
membership 5 1 0.17
booking 4 2 0.33
invoicing 2 3 0.60
access 1 3 0.75
notifications 0 4 1.00
reporting 0 5 1.00Each table has one owner, the graph has no tangle, and every edge points from a higher I to a lower one, so the stable dependencies principle holds. The order also suggests where to start carving: with the shared kernel and membership, which depend on almost nothing, and then upwards. Now try the most tempting shortcut: membership cancels the bookings of a leaving member by calling booking directly.
python3 carve.py target 'membership->booking'tables owned twice: []
tables with no owner: []
tangles: booking, membershipThe new edge recreates a tangle, because booking already depends on membership. The fix from step 3 stands: membership publishes MembershipEnded, and booking reacts.
06. Step 5: Write the boundary contracts
A boundary contract is the public API plus the rules that guard it. This is booking's API: plain data out, an event for other modules, and one call into membership for the answer it needs.
"""deskwise/booking/api.py: everything other modules may use from Booking."""
from dataclasses import dataclass
from datetime import date
from deskwise.membership.api import desk_days_left # Booking needs this answer now
from deskwise.shared_kernel.events import publish
@dataclass(frozen=True)
class BookingView: # plain data out: no ORM objects, safe to serialise later
booking_id: int
member_id: int
desk_code: str
day: date
@dataclass(frozen=True)
class BookingConfirmed: # event in: Invoicing, Access, Notifications subscribe
booking_id: int
member_id: int
desk_code: str
day: date
price_cents: int
def book_desk(member_id: int, desk_code: str, day: date) -> BookingView:
if desk_days_left(member_id) <= 0:
raise ValueError("no desk days left this month")
view = BookingView(1, member_id, desk_code, day) # real code: insert a row
publish(BookingConfirmed(view.booking_id, member_id, desk_code, day, 1500))
return viewThe import contracts for the target go into .importlinter, as in lesson 3. Modules that only react sit on top, the shared kernel at the bottom, and | separates siblings that must not import each other:
[importlinter]
root_package = deskwise
[importlinter:contract:public-api-only]
name = Modules use each other only through their public API
type = private_modules
[importlinter:contract:module-direction]
name = Deskwise modules depend towards stable modules
type = layers
layers =
deskwise.reporting | deskwise.notifications
deskwise.access | deskwise.invoicing
deskwise.booking
deskwise.membership
deskwise.shared_kernelThese contracts were checked against a stub package generated from TARGET_USES, with the booking API above in place: both were kept, and one added import from membership to booking broke the layers contract, as step 4 predicts. Checking the plan this way, before moving real code, costs minutes.
Then carve in small, shippable steps. For one capability at a time: route every outside write to its tables through the owner's API or events, add its contracts with the remaining violations listed under ignore_imports, and move its tables into the owner's schema only once the owner is their only writer. Delete each ignore_imports entry as you fix it, so that the list can only shrink.
07. Step 6: Decide what may leave the process, and when
Most modules should stay. For each candidate, write down the signal that would justify extraction and the evidence you would need, so that nobody extracts on a hope.
- Access is the one real candidate. Doors must open while the internet link is down, so some code must run inside the building, next to the door controllers; that need exists today. Prepare it inside the monolith first: access keeps its own table of who may enter, fed by membership and booking events, so a door decision never calls another module, and its API takes plain data.
- Reporting has no reason to leave. If its queries start to slow the main database, measured, the first step is a read replica, not a service.
- Notifications stays unless e-mail volume or a provider's terms demand separate scaling or separate credentials.
Record each decision and its trigger in an architecture decision record, so that the next person can check whether the trigger has fired. The later move itself, with strangler steps and data migration, belongs to legacy modernization and microservices.
08. Check your understanding
09. Apply it
This is the practice task of the skill. Use your own sample monolith and the notes from lessons 1 to 4.
- Collect its imports and its table writers, and run the mud analysis of
carve.pyon them. - Name at least three capability modules, give every table one owner, and give each module its own schema.
- Draw the target graph, check it with
carve.py target, write its import contracts, and show a CI build that fails on one forbidden import and passes after the fix. - Write the extraction note: for each candidate, the trigger that would justify it and the evidence you would need.
10. Review prompt
Without looking back, describe the order of work for carving a big ball of mud, and why it starts from imports and table writers rather than folder names. Explain what a strongly connected component tells you, how you choose the owner of a table that several files write, and why models and utils should not become modules. Say how you check a target plan before moving code, and what evidence justifies a later extraction.
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.