DEV Community

Sam Amderson
Sam Amderson

Posted on

Mapping Monolith Dependencies With AI Agents Before You Extract a Service

Most teams pick the first service to extract by feel, then learn in week three that it shares tables with half the codebase. Good monolith dependency mapping AI work reverses that order.

Agents read the code and propose the graph, a script checks every edge, and an engineer chooses the first service from numbers instead of instinct.

This article builds the checking part step by step: a small Python scanner that maps imports and shared database tables, then ranks modules by how hard they will be to pull out.

What does a monolith dependency map need to find?

Whether you run monolith dependency mapping AI or do it by hand, it needs two kinds of edges. Code edges are the imports and calls between modules. Data edges are the tables that more than one module reads or writes.

Monolith dependency mapping AI needs two edge types: code edges (imports and calls) and data edges (shared tables)

The second kind is the one teams skip, and skipping it is how a split ends up as a distributed monolith.

Quick check: If two modules never import each other, are they independent? Not if they write the same table. A shared table is a dependency even when the code never mentions the other module.

Code edges

Imports are the cheap part. Python's ast module lists them without running anything, and the same idea works for Java or Go with their own parsers.

Data edges

Table names hide in SQL strings, migration files and ORM models. Collect every table a module touches, then flag the ones touched by more than one module.

How does monolith dependency mapping AI work without guessing?

Agents are good at the reading. They can summarize an unfamiliar module, label it with the business capability it serves, and spot routing that lives in configuration instead of code.

They are bad at being right every time, so the map needs a rule: every edge an agent claims must come with a file and a line, and the script below must be able to reproduce it. Edges it cannot reproduce go on a short list for an engineer to read, not into the plan.

Monolith dependency mapping AI flow: an agent reads code and drafts a graph, a script checks every edge, and an engineer signs off

The risk of skipping the data layer is documented. The authors of CARGO, a paper on AI-guided partitioning, found that existing partitioning techniques miss the links between applications and databases.

When they refined those partitions with a graph that included database access, they reported 11% lower latency and 120% higher throughput on average.

If you want agents to run this scan as one stage of a longer pipeline, what is agentic SDLC from Figma to deployed backend shows where that stage sits.

Quick check: Should the agent rank the candidates too? It can draft the ranking, but the score should come from counted edges, not from the agent's opinion. That keeps the result easy to audit.

How do you build a small dependency and table-coupling scanner?

This script is the checking half of any monolith dependency mapping AI workflow. It treats each top-level folder as one domain, the way the Strangler Fig pattern moves one domain's tables, stored procedures and data at a time into a store of their own. It records imports between modules, finds table names in SQL strings, and scores every module.

import ast, re, sys
from pathlib import Path
from collections import defaultdict

SQL = re.compile(r"\b(?:from|join|into|update)\s+([a-z_][a-z0-9_]*)", re.I)

def scan(root):
    root = Path(root)
    mods = {p.name for p in root.iterdir() if p.is_dir()}
    edges = defaultdict(set)    # module -> modules it imports
    tables = defaultdict(set)   # table  -> modules that touch it
    for f in root.rglob("*.py"):
        mod = f.relative_to(root).parts[0]
        for node in ast.walk(ast.parse(f.read_text())):
            if isinstance(node, ast.ImportFrom) and node.module:
                dep = node.module.split(".")[0]
                if dep in mods and dep != mod:
                    edges[mod].add(dep)
            elif isinstance(node, ast.Constant) and isinstance(node.value, str):
                for t in SQL.findall(node.value):
                    tables[t.lower()].add(mod)
    return mods, edges, tables

def score(mods, edges, tables):
    rows = []
    for m in sorted(mods):
        fan_out = len(edges[m])
        fan_in = sum(m in deps for deps in edges.values())
        shared = sum(1 for t, u in tables.items() if m in u and len(u) > 1)
        owned = sum(1 for t, u in tables.items() if u == {m})
        rows.append((fan_in + fan_out + 3 * shared, m, fan_in, fan_out, shared, owned))
    return sorted(rows)

if __name__ == "__main__":
    mods, edges, tables = scan(sys.argv[1])
    print("risk module   in out shared owned")
    for r in score(mods, edges, tables):
        print(f"{r[0]:>4} {r[1]:<10} {r[2]:>2} {r[3]:>3} {r[4]:>6} {r[5]:>5}")
Enter fullscreen mode Exit fullscreen mode

Run it with python scan.py shop, where shop holds one folder per module.

Reading the output

On a four-module sample app, it prints this:

risk module   in out shared owned
   1 users       1   0      0     1
   5 billing     1   1      1     1
   7 catalog     1   0      2     0
  11 orders      0   2      3     0
Enter fullscreen mode Exit fullscreen mode

in counts modules that import this one, and out counts modules this one imports. shared counts tables another module also touches, and owned counts tables only this module touches.

The scanner only sees SQL written as plain strings. Queries built by an ORM need a second pass over the model files, and it will miss any table that is only reached through a stored procedure.

How do you rank which service to extract first?

The score is fan_in + fan_out + 3 × shared tables. The weight of 3 is a starting choice, not a standard, and the reasoning is simple: a shared table is harder to untangle than an import, so it counts for more. Change the weight if your own history says otherwise.

Module Score Why
users 1 One inbound edge, one table it owns outright
billing 5 One shared table, one import each way
catalog 7 Two shared tables, owns none
orders 11 Three shared tables, two outbound imports

Run dependency mapping before extraction and the first pick usually falls out of the table. Here it is users. orders is the opposite: it touches three tables other modules also use, so extract it last, or only after those tables have owners.

Bar chart of module risk scores in a monolith: users 1, billing 5, catalog 7, orders 11, where a lower score means a safer first extraction

A related practice is worth borrowing from the research. A recent catalogue of seven refactorings for preparing a monolith focuses on the code-level dependencies developers have to resolve, and one of its moves is to give a shared column to a single owning service, with the others calling that service to update it. An agent can propose which service should own which column. A person should approve it.

Quick check: Is the lowest score always the right first service? No. It is the cheapest to move, not the most valuable. Pick from the bottom of the list, then ask whether the team gains anything by moving it.

Where do static maps go wrong?

A static scan reads what the code says, not what the system does. Reflection, plugin loading, config-driven routing and scheduled jobs all create edges that never appear as imports. Generated SQL creates table edges the regex cannot see.

Cover the gap with runtime evidence. Collect a few weeks of traces or query logs, then diff them against the static graph.

Any edge seen at runtime but missing from the scan is a finding, and the module it touches should lose its place at the top of your list until someone explains it.

Reading a live schema or query log also needs read access to a database, which is covered in integrating AI agents with customer systems.

Quick check: How often should the map be rebuilt? On every merge to the main branch. The scan takes seconds, and a stale map is worse than none, because people trust it.

What changes once the map exists?

The first change is the conversation. Instead of arguing about which service feels ready, the team looks at one table and asks about the numbers.

A module with a high score is not forbidden, it just has visible reasons, and those reasons turn into work items: give this table an owner, replace that import with a call, retire this join.

The extraction stops being a leap and becomes the last step of a list that was already getting shorter.

The second change is how you treat surprises. When the scan disagrees with someone's memory of the system, the scan is a prompt to look closer, not a verdict, and the answer goes back into the map so the next run is better.

Over a few cycles the map becomes the most accurate document the team owns, because it is rebuilt from the code every time.

That is a better foundation for any service boundary than a diagram drawn once and never checked, and it costs one script and some patience.

Top comments (0)