Dependency Mapping: Finding Hidden Connections in Your Codebase
Map dependencies in your codebase across imports, runtime calls, shared data and job order. Find hidden coupling and enforce useful architecture boundaries.
Last year I was asked to split a monolith into microservices. "It'll take a quarter," the VP of Engineering said. "The boundaries are pretty clear." They weren't. What looked like four independent modules turned out to be a web of 847 cross-module dependencies. The "simple split" took fourteen months.
The problem wasn't that the codebase was badly written. The problem was that nobody had mapped the actual dependencies. Everyone had a mental model of how things connected, and every mental model was wrong in different ways.
Dependency mapping discovers and documents connections between components in your codebase. Use it alongside the systematic codebase understanding guide when tracing an unfamiliar system.
Dependencies that only manifest at runtime. Dependency injection, dynamic imports, reflection, and string-based lookups.
typescript
// This dependency is invisible to static analysisconst service = container.resolve(config.serviceName);// So is this oneconst handler = await import(`./handlers/${eventType}`);
Two modules that share no code but depend on the same database table, the same cache key, or the same message queue topic. Change the schema, and both modules break.
typescript
// Module A writes:await prisma.user.update({ where: { id }, data: { status: "active" } });// Module B reads (in a completely separate file, no shared imports):const activeUsers = await prisma.user.findMany({ where: { status: "active" } });// If Module A changes "active" to "enabled", Module B breaks silently.
Components that must execute in a specific order. The nightly batch job must complete before the reporting job runs. The cache must be warmed before the API starts serving traffic. These dependencies live in deployment scripts, cron schedules, and tribal knowledge.
The most insidious kind. Two modules that share an implicit understanding about data format, business rules, or behavior. No code connection. No shared schema. Just an agreement that "status code 7 means the user has been soft-deleted" that exists only in two developers' heads.
# Install dependency-cruiser (more configurable than madge)npm install -g dependency-cruiser# Generate a dependency reportdepcruise --output-type dot src/ | dot -T svg > deps.svg# Or get a JSON report for further analysisdepcruise --output-type json src/ > deps.json# Check for violations against your architecture rulesdepcruise --validate .dependency-cruiser.js src/
Dependency-cruiser is my preferred tool because it lets you define rules about which dependencies are allowed:
javascript
// .dependency-cruiser.jsmodule.exports = { forbidden: [ { name: "no-circular", severity: "error", from: {}, to: { circular: true }, }, { name: "no-ui-to-data", comment: "UI layer should not import from data layer directly", severity: "error", from: { path: "^src/ui/" }, to: { path: "^src/data/" }, }, { name: "no-cross-module-internals", comment: "Modules should only import from each other's index", severity: "warn", from: { path: "^src/orders/" }, to: { path: "^src/payments/(?!index)", pathNot: "^src/payments/index\\.ts$", }, }, ],};
For Go:
bash
# Built-in toolinggo mod graph# Or for internal package dependenciesgo list -json ./... | jq '.ImportPath, .Imports'
Static analysis misses runtime dependencies. To find those, you need to observe the system running.
Approach A: Distributed tracing. Instrumented traces connect spans along an observed request path. Compare those paths with the static dependency report to investigate runtime connections. Sampling and instrumentation coverage affect which paths you can observe.[3]
Approach B: Log analysis. Add structured logging to module boundaries. Log every outbound call with the source and destination module. Run the system for a week. Aggregate the logs.
Approach C: Network analysis. For microservices, capture network traffic between services using a service mesh (Istio, Linkerd) or a network analysis tool. The network doesn't lie. If service A makes HTTP calls to service B, that's a dependency, regardless of what the documentation says.
# Find all modules that reference a specific database tablerg "prisma\.user\." --type ts -l# Find all modules that read from a specific cache keyrg "cache\.get\(\"user:" --type ts -l# Find all modules that publish or subscribe to specific eventsrg "order\.created" --type ts -l
Build a matrix:
Data Resource
Writers
Readers
users table
auth, admin
orders, billing, reports, notifications
orders table
orders
billing, reports, fulfillment
user:session cache
auth
api-gateway, orders
order.created event
orders
payments, notifications, analytics, fulfillment
Every row with multiple writers is a coordination problem. Every row with many readers is a blast radius problem (changing the schema affects many modules).
# Check cron schedulescrontab -l# Or in Kuberneteskubectl get cronjobs -o wide# Check startup dependencies in docker-composegrep "depends_on" docker-compose.yml -A 5
Build a timeline:
00:00 - Cache warmup job starts
00:15 - Cache warmup must complete before API health check passes
03:00 - Nightly data sync from external provider
04:00 - Report generation (depends on sync being complete)
06:00 - Email digest (depends on reports being generated)
Two modules depend on each other. The cycle can complicate independent testing, initialisation and changes. Its runtime effects depend on the language and module loader.
Fix: Extract the shared concept into a third module. If orders depends on payments and payments depends on orders, there's probably a shared concept (like MoneyCalculation or PricingRules) that both should depend on.
A module with many incoming dependencies deserves review. Count its distinct dependent modules, then inspect the consumers and their contracts before estimating the impact of a change.[4]
bash
# Find the most depended-on modules (highest afferent coupling)depcruise --output-type json src/ > deps.jsonpython3 - <<'PY'from collections import defaultdictimport jsonwith open("deps.json", encoding="utf-8") as stream: report = json.load(stream)dependents = defaultdict(set)for module in report["modules"]: for dependency in module.get("dependencies", []): dependents[dependency["resolved"]].add(module["source"])for target, sources in sorted(dependents.items(), key=lambda row: len(row[1]), reverse=True)[:10]: print(len(sources), target)PY
Fix: If the hub module is a utilities grab-bag, split it into focused modules. If it's a core domain module, ensure it has excellent test coverage and stability guarantees.
Two modules that look independent but share a database table. Changing one breaks the other without any compiler warning.
Fix: Define explicit data contracts. If the orders module needs user data, it should depend on a UserRepository interface, not directly on the users database table. This makes the dependency visible and testable.
For years I believed that splitting a monolith into microservices would eliminate dependency problems. It doesn't. It transforms compile-time dependencies into runtime dependencies, which are harder to detect, harder to debug, and harder to fix.
In a monolith, an orders/payments cycle may fail a configured architecture rule or cause initialisation problems, depending on the language and loader. Across services, a circular call chain can amplify failures and complicate recovery.
The discipline of mapping and managing dependencies applies regardless of your architecture. Microservices don't remove the need for it. They increase it.
If you've never mapped your dependencies, start small. Pick one module. Run madge or dependency-cruiser on it. Look at the output. Are there dependencies you didn't expect? Circular dependencies you didn't know about? Connections to modules that seem unrelated?
Then pick the most surprising dependency and investigate it. Why does it exist? Is it necessary? Can it be removed or inverted?
That single investigation will teach you more about your codebase than a week of reading source code. Dependencies are the skeleton of your architecture. Once you see them clearly, everything else makes more sense.
Frequently asked questions
Does an import graph show every dependency?
An import graph shows the connections the parser can resolve from source code. Add runtime traces, shared-table access and job ordering to investigate relationships that a static report may omit.
How do I start dependency mapping in TypeScript?
Run a dependency analyser on one module and inspect its imports and cycles. Configure its TypeScript resolution and file extensions, then compare the graph with the module boundaries the team expects.
Should every circular dependency be removed immediately?
Assess the cycle against the language, loader and deployment model. Record whether it causes initialisation problems or forces coordinated changes, then decide whether to extract a shared concept or change the boundary.
How do I keep a dependency map useful?
Generate the static report in CI and check the boundary rules that matter to the system. Revisit runtime, data and temporal relationships as the application changes, since source analysis alone cannot establish them all.
Architecture fitness functions are automated tests for your system's structural properties. Here's how to implement the 5 most impactful ones and integrate them into your CI pipeline.
Compare cyclomatic and cognitive code complexity with change risk. Check corrected examples, understand each measure’s limits and target refactoring effort.
Use Git history analysis to find frequently changed files, co-change patterns and contributor concentration. Run reproducible queries and inspect their limits.
No single person can hold a large codebase in their head. A knowledge graph externalizes understanding into a queryable structure. Here's the 4-week playbook to build one.
Choose code search tools for text, symbols and cross-repository exploration. Use ripgrep, GitHub and Sourcegraph queries to find code and related changes.