Monorepo Dependency Analysis: How to Map Code Dependencies

Kyle · · 25 min read
Monorepo dependency analysis mapping code dependencies across projects

Monorepo dependency analysis matters when a “small” shared-module change suddenly touches six apps, stalls CI, and turns review into guesswork. If you use Claude Code, Cursor, Codex, or another MCP client, search alone won’t show what the edit can actually break.

What matters is tracing real internal relationships: imports, callers, build targets, entry points, and transitive dependents. You need paths, not a pretty diagram.

Start by asking:

  • Which production entry points reach this module?
  • Which dependents sit behind this changed symbol?
  • Where do cycles or high-churn shared packages widen the blast radius?

Change code with evidence, not hope.

What Monorepo Dependency Analysis Actually Means

Most teams say "dependencies" when they mean three different things at once. That's how people end up arguing past each other.

Monorepo dependency analysis is the work of finding how code units inside your repo depend on each other, then turning that into something visible and queryable. The output is usually a dependency graph. Nodes are code units. Edges are relationships.

There are two very different jobs here:

  • Third party package analysis tells you what you installed
  • Internal code dependency analysis tells you how your own code is wired together

That second one is the part teams keep underestimating. A package manifest can tell you that app-web depends on shared-ui. It cannot tell you which file in shared-ui is pulling in a slow validator, or which symbol change will wake up six services and three test suites.

A useful dependency graph can exist at several levels:

  • Folder or project level, for rough architecture
  • Package or workspace level, for boundaries and ownership
  • File level, for dead code hunts and import tangles
  • Symbol level, for blast radius and AI workflows
  • Build target level, for cache invalidation and CI cost

The important correction is simple: folder structure is not architecture.

Two files can sit side by side and never interact. One import can couple parts of the tree that look unrelated in the directory view. We've seen teams trust the folder tree because it's visible, then get blindsided by a transitive path nobody had in their head.

Grep doesn't save you either. It finds strings, not relationships. It misses alias resolution, interface dispatch, and transitive paths. Worst of all, it doesn't answer the question that usually matters most: what depends on the thing we're about to change?

That's where monorepo dependency analysis stops being a diagram exercise and starts being operational.

Why This Matters in Real Monorepos

You know the feeling. A shared utility changes and half the repo rebuilds. A refactor pauses on day two because nobody knows who imports the module buried two levels down. An AI assistant edits the right file for the wrong reason because it can't see the actual call path.

Those aren't edge cases. That's normal monorepo pain.

The day to day cost usually shows up like this:

  • Hidden coupling makes small changes feel dangerous
  • Reviews drag because blast radius is fuzzy
  • Refactors depend on tribal memory
  • CI runs too much or too little
  • Dead code stays forever because nobody trusts the delete

Scale breaks intuition fast. Large mobile repos have been shown to grow into graphs with more than 33,000 build targets and over 70,000 internal dependency edges. At that size, transitive structure stops being something a person can reason about by inspection. In large Python codebases, dependency tangles have been tied to slower imports, slower linting, more expensive testing, and tighter coupling across teams.

The real cost isn't "messy architecture." It's drag.

A deep nested chain means a change fans out farther than it should. A thick shared module turns into a traffic jam for the whole org. An unclear dependency path makes every diff look larger than it is, so people over-test, over-review, and still miss things.

AI-assisted development raises the stakes. Tools like Claude Code, Cursor, and Codex don't need more text alone. They need structure. Without a graph, they guess at callers, entry points, and side effects from chunks of code. With a graph, they can ask better questions before they touch anything.

Search explains code. Graphs explain consequences.
Monorepo dependency analysis in complex real-world codebases

What Counts as a Dependency in a Monorepo

If your graph only shows direct imports, it's useful for about ten minutes.

A real map needs to distinguish different kinds of dependency because they mean different things in practice.

The common ones:

  • Direct dependencies
  • Transitive dependencies
  • Reverse dependencies, or dependents
  • Runtime dependencies
  • Type only dependencies
  • Deferred or lazy dependencies
  • External dependencies versus internal ones

Then there are the edge types that actually change how you read the graph:

  • Imports and exports
  • Function and method calls
  • Inheritance or interface implementation
  • Containment, like package contains file or class contains method
  • Build target and task dependencies
  • Service contracts such as endpoints, events, or table usage

That last category matters more than teams expect. If your monorepo holds multiple apps or services, the dependency path often jumps through contracts, not imports. An endpoint call is still coupling. So is an event subscription. So is a table read everyone forgot was shared.

A few distinctions matter a lot:

  • Not every import creates runtime reachability
  • Type only edges still show coupling, but they shouldn't always count in cycle detection
  • Dynamic imports, reflection, runtime registration, and string keyed lookups can escape static analysis

That doesn't make the graph worthless. It just means you should read it like an operator, not like a machine outputting truth from heaven.

External packages still matter too, even if you don't expand them as first class internal nodes. They help explain missing declarations, unused packages, and whether a dev-only dependency leaks into a production path.

Start by Choosing the Right Graph for the Question

There isn't one perfect dependency graph. There are useful graphs for specific questions.

If you're asking "which workspace depends on this package?", a project or package graph is enough.

If you're asking "why is this file pulled into production?", you want file-level reachability from a real entry point.

If you're asking "what breaks if this function changes?", you need a symbol graph or call graph.

If you're asking "why did this harmless edit invalidate half our builds?", look at the build target graph.

If you're asking "which services call this endpoint across repos?", you need a contract or cross repo graph.

Here's the tradeoff:

  • Project graphs are readable, but they hide local tangles
  • Symbol graphs are precise, but noisy unless you filter hard

Most teams should work in layers. Start broad. Find the hot area. Then drill down until the graph matches the question. Otherwise you either drown in detail or get false confidence from a clean top level picture.

Some practical scoping advice helps:

  1. Pick a bounded slice first - one app, one feature area, one shared module
  2. Define the question before you parse anything
  3. Identify entry points early so reachability and dead code checks have a frame of reference

This sounds obvious. It isn't. A lot of failed analysis starts with "let's graph the whole repo and see what we learn." Usually what you learn is that a wall of nodes is not insight.

QuestionBest graphWhy this graph fits
Which workspace depends on this package?Project or package graphBroad dependency structure is enough for workspace and package lookup without drilling into file or symbol detail.
Why is this file pulled into production?File-level reachability from a real entry pointThis question depends on actual reachability paths from production entry points, not just direct imports.
What breaks if this function changes?Symbol graph or call graphFunction-level blast radius needs caller and symbol relationships, not only package boundaries.
Why did this harmless edit invalidate half our builds?Build target graphBuild and task dependencies explain cache invalidation and CI impact better than source-import views.
Which services call this endpoint across repos?Contract or cross-repo graphCross-service coupling often travels through endpoints, events, or tables rather than imports inside one repo.

A Step-by-Step Workflow to Map Monorepo Dependencies

The first pass doesn't need to be fancy. It does need to be disciplined.

1. Set the scope

Decide whether you're mapping one package, one app, one domain, or the whole monorepo. Name the question up front: blast radius, cycles, dead code, build cost, migration seams, AI context.

2. Inventory the units

List the units you care about: workspaces, packages, folders, files, services, or build targets. Normalize aliases and path mappings first. If imports don't resolve correctly, the rest is noise.

3. Collect dependency signals

Pull from the sources that actually describe relationships:

  • Workspace manifests and package metadata
  • Source imports and exports
  • Build tool metadata
  • API, event, or schema relationships if your apps cross service boundaries

4. Separate internal and external edges

Internal edges form the monorepo dependency graph. External packages stay as context unless your use case needs them expanded.

5. Build the graph

Model nodes and directed edges. Deduplicate repeated edges. Preserve edge type so runtime, type only, and deferred edges don't get flattened into one vague line.

6. Detect shape issues

Look for:

  • Cycles and strongly connected components
  • Roots and leaves
  • High fan-in modules
  • High fan-out modules
  • Deep chains

7. Add behavior

This is the part teams skip, and it's where the graph starts paying rent. Overlay change frequency, PR churn, build invalidation counts, or test coverage. A nested dependency isn't always a problem. A nested dependency that changes every week is.

One useful pattern from large build systems is combining graph shape with code churn. A shared module with high fan-in and frequent edits is where pain spreads.

8. Validate against real work

Take a recent PR and trace the actual impacted paths. Pick one suspected dead area and confirm whether any real entry point reaches it.

If the graph can't explain a change your team already lived through, fix the graph before you trust it.

Fast Ways to Get an Initial Dependency Graph

You don't need a perfect model on day one. You need something good enough to answer one real question.

A few quick starting points work well:

  • Package manager trees for external package investigation
  • Build system metadata if you already have target graphs
  • Import parsing for file and package edges
  • A manual sketch for one subsystem when you're trying to unblock a refactor

There's also a practical exploratory trick in monorepos. If you're considering splitting a folder into its own library, temporarily mark a few candidate folders as projects and generate a project graph between them. It gives you a rough picture of folder level coupling before you move any code.

That can save a week of wrong extraction work.

One caution: don't commit temporary exploratory config if it changes build and test invalidation behavior. We've seen teams accidentally distort their own cache inputs while "just experimenting."

Quick methods stop being enough when you need reverse lookups, transitive paths, or real reachability. A flat list of imports won't tell you why a file is reachable from production, or whether deleting a helper will break a path three modules away.

How to Read a Dependency Graph Without Getting Lost

Start small. Don't stare at the whole picture and hope meaning appears.

The first things worth checking are:

  • Roots - code that nothing internal depends on
  • Leaves - code with no internal dependencies
  • Dense clusters - where boundaries are probably weak

Then look at the metrics that actually change decisions.

The few numbers worth caring about

  • Fan-in: how many internal consumers depend on a node
  • Fan-out: how many things a node depends on
  • Depth: how long the dependency chains get
  • Reachability: what code an entry point pulls in
  • Centrality or bottleneck indicators: which modules sit in too many critical paths

Patterns usually tell on themselves. High fan-in plus high change frequency is a dangerous shared module. High fan-out often means orchestration code, leakage across boundaries, or a module doing too much. Deep chains raise cognitive load and widen invalidations. Strongly connected components mean isolation will be harder than the folder tree suggests.

A small stable API surface is usually safer than a giant shared package full of implementation detail. Big shared packages feel convenient right up until everyone depends on them.

When you're reading a graph, trace actual paths:

  • Why is this file reachable?
  • What pulls this entry point in?
  • Which path makes this package show up in production?

That's where the answers are.

The Patterns That Usually Signal Trouble

Some graph shapes are warning signs. They don't always mean "rewrite this now," but they should slow you down.

Cycles are the obvious one. Overlapping cycles are worse. They turn unrelated areas into a tangled cluster where changing one thing drags in five others.

Thick shared modules are another classic failure mode. Design systems, utility packages, and platform modules slowly absorb too much. Then every edit broadens rebuild scope, test scope, and fear.

A few others show up constantly:

  • Hidden cross-layer imports, like UI code reaching into data internals
  • Test helpers drifting into production paths
  • Orphan files that are either true dead code or forgotten entry points
  • Missing declared dependencies
  • Declared packages that no code uses
  • Deep chains where ownership and impact disappear into the stack
  • Dynamic behavior that static tools can't fully see

Dead code is worth calling out. A file that nothing imports might be a real script, test, or CLI entry. Or it might be garbage nobody had time to remove. Static reachability is a strong starting signal, not an automatic delete button.

Turn Dependency Analysis Into Better Engineering Decisions

This is where the work becomes useful.

You can use monorepo dependency analysis to plan refactors without guessing, split folders into libraries at the right seam, tighten import boundaries, scope tests by actual reachability, and audit production paths for risky dependencies.

A simple blast radius workflow usually works:

For change impact analysis

Assess change impact

  1. Changed node

    Start from the changed node

  2. Dependents

    Trace direct and transitive dependents

  3. Runtime filter

    Filter by runtime relevance and real entry points

  4. Risk overlay

    Overlay change frequency or criticality if you have it

That's a review artifact people trust because it's tied to paths, not opinions.

It also helps with migration work. If you're pulling many projects into one workspace, map the inter-project dependencies before you move anything. Natural seams rarely match the current folder boundaries.

Security and incident response benefit too. When a vulnerable module shows up, the hard question is never "is it in the manifest?" The hard question is "where is it actually deployed or reachable?" Those are different questions.

For AI workflows, we think the best pattern is straightforward: before asking an assistant to edit a shared package, ask which callers, endpoints, or services depend on it. Before accepting a refactor, trace the path from entry points to the edited symbol. Give the model structural context first.

Tooling Approaches and Their Tradeoffs

Different tools produce different truths.

Manifest based tools are good for declared package relationships. They are weak on file level reality and transitive code paths.

Source import analysis is better for actual coupling inside TypeScript, JavaScript, Python, and similar stacks. It still misses some runtime only behavior.

Build system graphs are excellent for targets, caching, invalidation, and CI impact. They usually won't answer symbol level questions cleanly.

Knowledge graph approaches are where things get more interesting for day to day engineering. They let you query architecture, callers, blast radius, dead code, and cross repo relationships in one model instead of switching mental modes.

Selection criteria are pretty simple:

  • Which languages are supported
  • Smallest unit of analysis
  • Can it answer reverse dependency questions
  • Can it trace paths, not just neighbors
  • Can it distinguish runtime from type only edges
  • Can it work across multiple repositories
  • How often the map refreshes

For teams using AI coding assistants, Pharaoh fits that last category. We map TypeScript, JavaScript, Python, C and C++ repositories into a knowledge graph, refresh on every push, and support cross repo analysis for MCP compatible workflows. The useful part isn't a pretty diagram. It's being able to query callers, dependencies, endpoints, environment variable usage, blast radius, and dead code before an assistant edits shared code.

Standard semantic search breaks down in large monorepos because it slices code into text chunks and throws away structure. Then the model has to infer architecture from fragments.

Sometimes it guesses right. Sometimes it confidently invents the call path.

Text retrieval is still useful for explanations and local patterns. Graph backed retrieval is better for callers, dependency paths, reachability, and blast radius. Different job.

A familiar workflow makes the difference obvious. In a Claude Code or Cursor session, ask what calls a shared validator, which entry points reach it, and what happens if its exception path changes. Search gives you a lot of nearby text. A graph gives you explicit paths.

That matters for efficiency too. Some graph based indexing workflows report cutting token usage by more than 65 percent by retrieving only the structural context needed instead of dumping huge slices of a monorepo into the model.

A 2026 preprint evaluating four multimodal models found that adding a visualized repository-structure graph to the usual text interface reduced input-token consumption by up to 26% while maintaining or improving issue-resolution accuracy. That result comes from a specific research prototype, so it is not a universal savings estimate for every graph-backed coding workflow.

The goal isn't to let AI roam around your repo unsupervised. The goal is to give it the same architectural awareness a careful maintainer would want before touching shared code.

Common Mistakes That Make Dependency Analysis Less Useful

A pretty graph is not the goal. Answering engineering questions is.

The mistakes we see most often are boring, which is why they keep happening:

  • Mixing imports, calls, type edges, and build edges into one undifferentiated diagram
  • Stopping at direct imports when the real risk is transitive reachability
  • Assuming static analysis sees everything
  • Ignoring reverse dependencies
  • Mapping once and letting the result go stale
  • Deleting dead code based only on static reachability
  • Looking only at structure and ignoring behavior
  • Forgetting the human side of painful modules

That last one matters more than people admit. The worst nodes are often the ones many teams touch, avoid, or quietly work around. You can feel those modules in review latency before you measure them.

Keep the Graph Current With Everyday Development

A graph that doesn't refresh loses credibility fast. Code moves every merge. Last quarter's architecture board can't explain today's PR.

The operating model doesn't need to be heavy:

  • Rebuild the map on every push or on a tight schedule
  • Use it during refactors, incidents, and PR review
  • Check the same signals each week: new cycles, rising fan-in, hot shared modules, dead code candidates

This fits naturally into review. Structural checks can flag unreachable exports, regression risk, test coverage gaps, or possible breaking changes before reviewers have to infer all of that from a diff.

That's where PR Guard is useful. It brings those structural checks into pull requests so dependency analysis shapes decisions while code is still moving, not after merge.

A few ownership habits help too:

  • Assign maintainers to high fan-in modules
  • Track boundary exceptions as debt
  • Use graph findings to guide library extraction and module splits

If the graph never affects a decision, it will stop getting maintained.

Keeping the graph current with everyday monorepo dependency analysis

Conclusion

Monorepo dependency analysis is not just a defensive audit. It's how you make a sprawling codebase legible enough to change with confidence.

The payoff is practical: clearer blast radius, better refactor planning, dead code cleanup you can trust, smarter review, and better context for AI assistants before they edit shared code.

A good next step is small and concrete. Pick one high churn shared package this week. Map its direct and transitive dependents. Trace one real production entry point through it. Write down the first boundary problem or dead code candidate you find.

If your team wants that graph to be queryable inside an MCP workflow, Pharaoh is one way to bring codebase structure into the assistant before edits begin.

Article Record

ReferencesPrimary sources used for this article
  1. Common investigative workflows | Rev-dep - High-Speed Dependency Graph Analysis for JavaScript and TypeScript Monorepos
  2. Understand dependencies across multiple repositories | ProvenMap
  3. Identify Dependencies Between Folders
  4. Building a Dependency Graph of Our Python Codebase | Our Success Stories | Python.org
  5. km deps · Kimün
  6. Log4Shell Remediation Visibility with JupiterOne | JupiterOne | JupiterOne
Update HistoryMeaningful revisions to this article
Initial publication.
← Back to blog