Pruning CI Build Graphs in Large Monorepos
How reverse DAG traversal and Merkle hashing cut a 47-minute Bazel rebuild down to the actual affected-target subgraph, without false negatives.

At 30,000 build targets, a monorepo CI pipeline that rebuilds and re-tests everything on every commit stops being an inconvenience and becomes an existential threat to delivery velocity. Every commit pays for the whole graph however small the change, and with many engineers committing daily that cost compounds into long CI queues. The fix is not more compute — it is dependency graph pruning: computing the minimal affected subgraph for a given commit and executing only that. This article covers the theory, the traversal algorithms, and the production configuration required to implement dependency graph pruning correctly, without introducing false negatives that let broken code merge silently.
#The Problem Statement: Linear Cost Growth in Monolithic Build Graphs
Monorepos centralise source control but do not, by default, centralise build efficiency. As target count grows, naive CI configurations that invoke bazel test //... or npm run test at the repository root scale linearly (or worse, given shared test fixtures) with the total number of targets, regardless of how small the actual diff is. A one-line change to a leaf-level utility library can trigger a rebuild of every downstream service, every integration test, and every container image in the repository.
The core inefficiency is that CI treats the commit as a black box rather than as a delta against a known graph state. Without dependency graph pruning, the build system has no way to distinguish "this change touches an isolated documentation file" from "this change touches a core authentication module consumed by forty services." Both trigger identical, maximal build behaviour. This is the bottleneck that must be architected away.
#Architectural Breakdown: The Graph, the Hash, and the Diff
Correct dependency graph pruning requires three cooperating subsystems, each with distinct correctness guarantees:
- The static dependency graph — a directed acyclic graph (DAG) where nodes represent build targets (libraries, binaries, test suites) and edges represent declared dependencies. Bazel, Nx, Pants, and Turborepo all maintain this internally, derived from
BUILDfiles,package.jsonworkspace references, or equivalent manifests. - The content-addressable hash layer — each node is assigned a Merkle-style hash computed from its own source files plus the hashes of its transitive dependencies. This is what allows a target to be skipped even if it sits inside the "affected" region of the graph but its actual inputs are byte-identical to the last successful build.
- The changed-file diff — the set of files modified between the base commit and the head commit, typically produced by
git diff --name-onlyagainst a merge-base reference.
Dependency graph pruning is the operation that maps the changed-file diff onto the static graph via an ownership index (which target owns which file), then performs a reverse traversal — walking from the changed nodes outward along incoming edges — to compute the full set of transitively affected targets. This reverse traversal is the computationally interesting part; everything downstream of it (scheduling, parallel execution, caching) depends on the traversal being complete and correct.
#Why Forward Traversal Is the Wrong Direction
Engineers new to this problem frequently attempt forward traversal — starting from a changed target and walking its own dependencies. This is backwards. A change to library A does not affect what A depends on; it potentially affects everything that depends on A. Correct dependency graph pruning always operates on the reverse dependency graph (sometimes called the "rdeps" graph), constructed by inverting every edge in the static DAG.

#Implementation Logic: Step-by-Step Execution
- Checkout the merge-base commit shared between the feature branch and the target branch.
- Compute the changed-file set via
git diffagainst that merge-base, not againstHEAD~1, to correctly handle squash-merges and rebased history. - Resolve each changed file to its owning build target(s) using the build system’s ownership query (e.g. passing each file path to
bazel query, which resolves it to its source-file label, as the script below does, or an Nxproject.jsonfile-to-project map). - Load the cached static dependency graph (do not recompute it from scratch on every run — persist it as a build artefact and incrementally patch it).
- Invert the graph edges to obtain the reverse adjacency list.
- Run a breadth-first traversal from every changed target across the reverse adjacency list, collecting all reachable nodes. This set is the affected subgraph.
- Let the content-addressable cache absorb unchanged work. In Bazel this is not a separate pruning step: when the affected targets are built, any action whose inputs are unchanged is served from the local action cache or a remote cache instead of being executed, and with the default
--cache_test_results=autoBazel reruns a test only when the test or its dependencies changed, it is marked external, or it failed last time, and otherwise reports the cached result. Those nodes stay in the affected set for reporting purposes but do no real work. - Topologically sort the remaining execution set to determine safe parallel execution order, respecting the original (non-inverted) edge direction.
#Reference Query with Bazel
Bazel exposes this natively through its query language. The rdeps function performs exactly the reverse traversal described above, scoped to a universe expression for performance:
1# Get merge-base and changed files
2MERGE_BASE=$(git merge-base origin/main HEAD)
3CHANGED_FILES=$(git diff --name-only "$MERGE_BASE" HEAD)
4
5# Fail safe: anything we cannot map precisely triggers a full build
6full_build() { echo '//...' > affected_targets.txt; echo '//...' > affected_tests.txt; exit 0; }
7
8# Ignore documentation; a genuinely empty diff means nothing to do
9CHANGED_FILES=$(echo "$CHANGED_FILES" | grep -vE '^docs/|\.md$')
10if [ -z "$CHANGED_FILES" ]; then
11 : > affected_targets.txt; : > affected_tests.txt
12 exit 0
13fi
14
15# Global files (module and workspace files, lockfiles, .bazelrc, BUILD and .bzl files) invalidate the graph
16if echo "$CHANGED_FILES" | grep -qE '(^|/)(MODULE\.bazel|WORKSPACE(\.bazel)?|\.bazelrc|BUILD(\.bazel)?|[^/]*lock[^/]*)$|\.bzl$'; then
17 full_build
18fi
19
20# Bazel resolves workspace-relative paths to source-file labels (lib/foo.py -> //lib:foo.py).
21# Map each file on its own, keep Bazel's errors visible and check every exit status:
22# a deleted file, or one Bazel cannot resolve to a target, falls back to a full build
23CHANGED_LABELS=""
24while IFS= read -r f; do
25 label=$(bazel query "$f" < /dev/null) || full_build
26 [ -n "$label" ] || full_build
27 CHANGED_LABELS="$CHANGED_LABELS $label"
28done <<< "$CHANGED_FILES"
29
30# Reverse traversal: every rule, and every test, that transitively depends on a changed file
31bazel query "kind(rule, rdeps(//..., set($CHANGED_LABELS)))" > affected_targets.txt || full_build
32bazel query "tests(rdeps(//..., set($CHANGED_LABELS)))" > affected_tests.txt || full_buildFor further detail on the query grammar, refer to the official Bazel Query Language reference, specifically the semantics of rdeps and universe scoping, which materially affect traversal performance on very large graphs.
#Graph Traversal in Custom Tooling
Teams without Bazel (e.g. polyglot monorepos with a hand-rolled dependency manifest) must implement the reverse BFS themselves. The following illustrates the core algorithm operating on a serialised adjacency map:
1from collections import deque, defaultdict
2import json
3
4def invert_graph(forward_edges: dict[str, list[str]]) -> dict[str, list[str]]:
5 reverse = defaultdict(list)
6 for node, deps in forward_edges.items():
7 for dep in deps:
8 reverse[dep].append(node)
9 return reverse
10
11def affected_subgraph(reverse_edges: dict, changed_nodes: set[str]) -> set[str]:
12 visited = set(changed_nodes)
13 queue = deque(changed_nodes)
14 while queue:
15 node = queue.popleft()
16 for parent in reverse_edges.get(node, []):
17 if parent not in visited:
18 visited.add(parent)
19 queue.append(parent)
20 return visited
21
22with open('graph.json') as f:
23 forward = json.load(f)
24
25reverse = invert_graph(forward)
26changed = {'lib/auth', 'lib/logging'}
27affected = affected_subgraph(reverse, changed)
28print(f"Dependency graph pruning yielded {len(affected)} affected targets")#Wiring Pruned Targets into CI
Once the affected set is materialised as a flat file, it becomes the input to a single Bazel invocation, through Bazel’s documented --target_pattern_file option, which reads the target patterns from the named file instead of the command line, rather than a static job list; Bazel parallelises the work itself, and one matrix job per target would hit GitHub’s 256-job matrix limit on large changes. This is where dependency graph pruning delivers its measurable throughput gain — the executor only schedules work for nodes present in affected_targets.txt:
1jobs:
2 build-affected:
3 runs-on: ubuntu-latest
4 steps:
5 - uses: actions/checkout@v4
6 with:
7 fetch-depth: 0
8 - name: Compute affected targets
9 # the query script above; writes affected_targets.txt and affected_tests.txt
10 run: ./scripts/compute_affected.sh
11 - name: Build affected targets
12 run: |
13 if [ -s affected_targets.txt ]; then
14 bazel build --target_pattern_file=affected_targets.txt
15 fi
16 - name: Test affected tests
17 run: |
18 if [ -s affected_tests.txt ]; then
19 bazel test --target_pattern_file=affected_tests.txt
20 fi
21 - uses: actions/upload-artifact@v4
22 with:
23 name: affected-targets
24 path: affected_*.txtThis pattern keeps the pruning decision as a first-class pipeline artefact, auditable independently of the build itself — which matters considerably when a pruning bug is suspected as the cause of a missed regression.

#Failure Modes and Edge Cases
Dependency graph pruning is only as trustworthy as the completeness of the declared graph. The most damaging failure mode is the undeclared dependency: a target that consumes another target’s output at runtime (via a shared config file, an environment variable, or a dynamically loaded plugin) without declaring it in the build manifest. In this scenario, the reverse traversal never discovers the consumer, the affected subgraph is incomplete, and a broken change ships with a fully green CI run. This is a false negative, and it is strictly more dangerous than the cost the pruning was meant to save.
Related edge cases worth architecting against explicitly:
- Cycle contamination — a genuine cycle in the declared graph (often from circular test fixtures) breaks topological sort and must be rejected at graph-load time, not silently tolerated with an arbitrary tie-break.
- Generated file drift — code generation steps (protobuf, GraphQL schema stitching) that run outside the tracked build graph create files the ownership index cannot map, effectively invisible to the diff resolver.
- Merge-base miscalculation — computing the diff against
HEAD~1instead of a true merge-base after a rebase produces an inflated or deflated changed-file set, corrupting the entire downstream traversal. - Global configuration files — a change to a root-level lockfile or compiler flag file should, by design, invalidate the entire graph. Pruning logic must special-case these paths, as the script above does, rather than resolve them through the ownership index, or it will incorrectly scope a global change to a narrow subgraph.
- Cache poisoning across branches — if CI jobs for untrusted forks or external contributors hold write access to the shared cache, they can upload malicious outputs under legitimate action keys, which trusted builds then reuse without executing anything. Restrict cache writes to trusted builders and make the cache read-only (or unavailable) to fork builds. This overlaps with the broader architectural patterns used in supply-chain security for build systems.
#Scaling and Security Trade-offs
Dependency graph pruning is not a free optimisation; it trades absolute correctness guarantees (full rebuild, every time) for throughput, and that trade must be actively managed rather than assumed safe.
- Full-graph builds: highest confidence, zero false-negative risk, but cost grows linearly (or superlinearly with shared fixtures) with repository size — eventually unsustainable on standard CI runner fleets as the repository grows.
- Pruned builds via dependency graph pruning: can cut CI wall-clock time sharply when most commits touch a small part of the graph (measure the gain on your own repository rather than assuming a figure), but introduce a dependency on the completeness of the declared manifest — a governance problem, not just a tooling problem.
- Periodic full-graph reconciliation: running an unpruned build on a schedule (e.g. nightly, or on merge to the trunk branch) acts as a safety net that catches undeclared-dependency drift before it compounds across many pruned merges.
- Remote cache trust boundary: pruning efficiency is amplified by remote caching, but every cache hit is an unverified trust decision. Signing cache entries with a content hash tied to a verified builder identity mitigates poisoning, at the cost of additional round-trip latency on cache lookups.
- Ownership index staleness: the file-to-target mapping must be regenerated on every graph change, not cached indefinitely; stale ownership data silently degrades traversal accuracy over weeks without triggering any visible CI failure.
Teams operating monorepos beyond the low tens of thousands of targets should treat dependency graph pruning as a core piece of build infrastructure with its own test suite, ownership, and on-call rotation — not as a CI script maintained informally by whichever engineer wrote it first. The traversal correctness of the reverse graph is now load-bearing for release safety, and it should be reviewed with the same rigour as the production services it gates.
Evidence trail
Sources and verification
Primary documentation and external technical references used in this article.
About this page
Credited to
Dates
Published
Last updated
Was this useful?
Reports go to the site owner and are used to correct pages. Corrections are listed at /corrections.
Engineering insights, direct to you.
Receive the latest Systems Engineering tutorials, production guides, Engineering Labs and operational best practices.
Comments
Add a thoughtful note on Pruning CI Build Graphs in Large Monorepos. Comments are checked for spam and held for moderation before appearing.