3.4.5 Managing unused_deps

Extra deps on a target are not free. Every declared edge widens the set of actions an input change can invalidate, expands the per-action input set so cache hit rates drop and invalidation broadens, and makes the target graph harder to reason about — exactly the failure mode catalogued from the diagnostic side in 2.1.4 Common Dependency Issues. The way a maintainer keeps that drift under control is by pairing strict enforcement on the "missing deps" side with periodic pruning on the "unused deps" side, and letting tooling drive the edits instead of hand-audit.

At Stripe, engineers were waiting for Bazel the equivalent of 150 engineer-hours per day, and the team suspected that BUILD files had drifted: a new payment service showed 1,400 Java library dependencies, and they believed people added or copied dependencies until the code compiled and moved on.1 That is the failure the unused_deps workflow is designed to correct.

What unused_deps actually does

The canonical tool is unused_deps from bazel-contrib/buildtools, the same repo that ships buildifier and buildozer. It is a Go binary, it takes a space-separated list of Bazel labels (with :all and ... target-pattern support), its documentation covers java_library rules, and it prints buildozer commands for the pruning it suggests rather than editing BUILD files in place.2 Upstream documents go install github.com/bazel-contrib/buildtools/v10/unused_deps@latest as a convenient evaluation path. A shared repository or CI job should replace latest with a reviewed buildtools tag or commit and expose that pinned binary through 3.5.3 Developer Tool Management. Applying the results is therefore a versioned, reviewable diff, not a blind rewrite.

The buildtools repository map keeps the public unused_deps workflow next to the buildozer command contract, which is the shortest upstream route for checking both halves of that emit-then-review workflow.

unused_deps //... > prune.sh
# review prune.sh
bash prune.sh

How it decides an edge is unused

The evidence comes from the Java compiler, not from parsing source. When Bazel compiles a Java target, its compiler wrapper writes a .jdeps file that lists the jars the compiler actually needed to resolve symbols. The same compiler-side tracking produces the [strict] deps errors described below. unused_deps diffs that record against what the target declares:3

  1. It queries for Java-family rules (kind('(kt|java|android)_*', ...)) and builds them with an injected aspect that writes the arguments of each Javac or KotlinCompile action to a .javac_params file.
  2. It reads the --direct_dependencies jars from that file and maps each jar back to a label through the Target-Label entry in the jar's MANIFEST.MF. rules_jvm_external, the Maven ruleset, stamps that entry into the Maven jars it processes so @maven//... deps can be mapped too.
  3. It removes the jars that .jdeps marks as explicitly used. The remaining direct deps were declared but not needed to compile.

For each leftover edge it prints a remove deps command, preceded by an add deps command for whatever the removed target exports, so code that reached those exported targets through it keeps a direct edge.3

This mechanism also predicts the false positives below. .jdeps records only what javac needed, so a dependency used only at runtime or through reflection never appears in it and is reported as unused.

How Stripe compared two dependency graphs

Stripe's internal tool extracts a target graph with bazel query --output proto and records imported and exported symbols per Java file with a javac plugin. It maps Java files to their Bazel targets and flags declared edges with no corresponding source dependency. It marks those edges unused and removes them, even though some may still be needed at runtime.1

unused_deps finds declared Java deps with no compile-time use
The set difference is the model. The pipeline gathers the two sets that it compares.
declared deps
from BUILD targets
−
compiler-observed deps
symbols javac resolved
=
removal candidates
review before applying
1 · Read declarations
Collect each target's declared deps
Bazel graph → declared set
2 · Observe Java compile
Record jars javac resolved symbols from
Java-specific plugin / .jdeps
3 · Subtract and emit
Print removal commands for the difference
buildozer commands → stdout
The middle stage sees only compile-time use. Generated code, annotation processors such as Dagger, reflection, and runtime-only edges can therefore be false positives — review the emitted commands.

Why a clean-looking tool gets noisy in practice

The reason unused_deps surprises people is that "used at compile time" and "declared in deps" are not the same set. Generated code, annotation processors like Dagger, and reflective runtime-only dependencies all show up as unused from a compile-time view even though removing them breaks the build at a later stage — run the upstream tool against such code and it produces a flood of errors, after which Bazel immediately suggests re-adding many of the dependencies it just deleted.1

Macros around Java targets make the problem worse. A wrapper macro layered on top of java_export that does many things at once can break unused_deps and buildozer edits together.4 This is the practical cost of abstraction layers on top of the native Java rules: the more the BUILD shape diverges from plain java_library, the less the upstream hygiene tooling applies.

Treat it as the other half of strict deps

unused_deps only makes sense when paired with --strict_java_deps. The flag controls whether javac refuses compilation when a source file references a type from a jar that is not part of the current target's direct dependencies. The accepted values are off, warn, error, strict, and the default (which behaves like strict).5 With it on, Bazel emits a [strict] error that names the missing target and suggests a shell command — in practice a buildozer 'add deps …' line — that automatically inserts the missing direct dependency.

Strict deps and unused_deps bracket the same hygiene problem from opposite sides. Strict deps stops you from relying on a transitive edge you never declared. unused_deps removes declared edges you no longer rely on. Strict transitive dependencies exist explicitly so that engineers can remove deps without fear of breaking distant targets, and pruning is the natural companion to that mode.6

In 2019, Wix described its plan for unused-deps removal as an on-demand action run before pushing or when running tests, rather than a check that blocks developers while they code, because the analysis has to consider every file in a target and may not be possible on the fly while coding.7 The guidance has aged well: run it at specific moments, not every CI build.

The pattern beyond Java

The same "Bazel graph vs source graph, emit buildozer" shape recurs across languages, just with different analysers.8

  • Python. rules_fawltydeps runs FawltyDeps as an aspect (see 4.8 Aspects) over py_library / PyInfo providers, compares declared deps with the imports it observes in source, and emits buildozer commands for fixes — with --strict_java_deps-like suggestions for missing packages and cached results because the analysis is executed through Bazel itself.9 Language-specific setup belongs in L3 Python.
  • JVM ecosystems. bazel-deps is the JVM equivalent, and the broader classpath governance story — duplicate classes, unwanted transitives — sits under L1 Java & Kotlin (JVM).
  • C++ and similar. Tools like depend_on_what_you_use and bazel_iwyu fill the same role for C/C++ by scanning headers, and they belong to the same state-of-the-art set as FawltyDeps and bazel-deps for keeping deps honest.8

None of these are fully safe to automate. Dep-metadata freshness generally cannot be automated end to end, because edge cases and occasional false positives are unavoidable.8 That is why every one of these tools emits buildozer commands for a human to review instead of editing BUILD files in place.

A workflow that survives the false positives

A few working patterns show up repeatedly in practice:

  • Scope to targets you understand. Publish the tool internally and let teams with the relevant runtime knowledge opt in. At Stripe, some services reduced their overall runtime dependencies by about 35% with the internal tool.1
  • Make the diff reviewable. The tool's output is a shell script of buildozer commands. Keep that separation: run the tool, inspect the diff, apply only the commands you trust, commit the rest for follow-up. buildozer is covered in more detail in 3.4.3 Buildozer. The build-maintenance app/BUILD.bazel keeps a deliberately stale //unused:unused_helper edge so the buildozer plan helper can emit the matching remove deps line — the same emit-then-review shape the real unused_deps tool produces, even though the example does not run unused_deps itself. The buildozer-command-file snippet narrows that pattern to one generated command file so the review step is easy to inspect.
  • Pair with --strict_java_deps rather than relying on it alone. Strict deps alone will eventually accumulate deps entries that have outlived their imports. Periodic unused_deps passes keep that list honest.5,6
  • Respect runtime and reflective edges. When a genuinely runtime-only dep shows up as "unused", the fix is documentation or a test that exercises it, not a blanket removal. This is exactly why hygiene belongs on-demand before push rather than in an interactive lint.
  • Do not confuse it with Gazelle. 3.4.2 Gazelle (BUILD File Generation) generates deps from source imports for supported languages. unused_deps prunes the deps list after humans or generators have written them. They complement each other, but Gazelle in file mode already enforces a narrower deps surface for the languages it supports, so there is less for unused_deps to remove on Gazelle-managed packages.

At repo scale, trimming unused edges is not just a tidiness concern — large transitive closures are a measurable driver of rebuild volume and CI cost, and the graph analysis tooling in 5.3 Graph Analysis is the natural place to quantify the benefit once this workflow is routine.8

extra

Kotlin, Android, and the aspect hand-off

The upstream tool documents support for java_library. Its query also matches kt_ and android_ rule kinds, and its aspect reads KotlinCompile actions as well as Javac ones, but treat results for those rules as outside the documented contract.2,3 Custom wrapper macros can also prevent tooling from editing the underlying target.2,4 Stripe's internal workflow collects symbols from Java sources. Applying the same graph comparison to another language requires an extractor for that language.1 See 4.8 Aspects for how build tools can collect compiler metadata.

key takeaway

Treat unused_deps pruning as the mirror image of --strict_java_deps: one stops drift on the "added too many" side, the other cleans up drift on the "never removed" side. Run it on targets you own, review the emitted buildozer commands as a diff, preserve runtime-only and reflective edges by hand, and expect equivalent but language-specific tools (FawltyDeps for Python, depend_on_what_you_use for C++, bazel-deps for JVM classpath shaping) to fill the same role everywhere else.1,5,8,9

Check your understanding · 3 questions

1.unused_deps reports a Java dependency as unused, but removing it breaks the build because Dagger uses it for annotation processing. What does this illustrate?

Select one answer

2.True or false about unused_deps and strict deps:

Choose True or False for each sentence

unused_deps and --strict_java_deps solve the same problem from the same direction.
The upstream unused_deps documentation covers java_library rules, and the tool decides an edge is unused by comparing declared direct deps with the jars the compiler recorded in .jdeps.
FawltyDeps, depend_on_what_you_use, and bazel-deps fill the same unused-dep role for Python, C++, and JVM classpath respectively.

3.A team wants to use unused_deps safely across a large Java monorepo. What is the most responsible rollout strategy?

Select one answer

0 of 3 answered

Footnotes

  1. How Stripe's new tool detects extraneous Java dependencies — the 150 engineer-hours/day figure, the failure modes of Google's unused_deps on generated code and Dagger, and the three-stage Bazel-graph / source-graph / comparison architecture with opt-in rollout. ↩1 ↩2 ↩3 ↩4 ↩5 ↩6

  2. unused_deps — bazel-contrib/buildtools — installation via go install, CLI shape (unused_deps TARGET... with :all / ... support), and scope limited to java_library rules with buildozer-command output. The aspect / .javac_params / .jdeps pipeline implementation is the upstream tool's public code. ↩1 ↩2 ↩3

  3. Bazel Knowledge: dive into unused_deps — the kind('(kt|java|android)_*') query, the .javac_params aspect over Javac/KotlinCompile actions, jar-to-label mapping through MANIFEST.MF Target-Label (stamped by rules_jvm_external), the .jdeps EXPLICIT entries subtracted from declared direct deps, and the add deps $(bazel query 'labels(exports, ...)') line emitted before remove deps ↩1 ↩2 ↩3

  4. Bazel for Everyone: Confluent — a wrapper macro over rules_jvm_external's java_export breaking unused_deps and buildozer automation. ↩1 ↩2

  5. Commands and Options — canonical semantics for --strict_java_deps (off | warn | error | strict | default). The accompanying Dependency Management basics page describes the mode as "fails with an error and a shell command that can be used to automatically insert the dependency". ↩1 ↩2 ↩3

  6. Dependency Management — Google's multi-year rollout of strict transitive dependencies so engineers could safely remove unused deps. ↩1 ↩2

  7. Make local development (with Bazel) great again! — Wix describing planned on-demand unused-deps removal (before push or on test) rather than a blocking check while coding, with auto-dep handling the strict-deps side. ↩

  8. Managing dependency graph in a large codebase — stale / extra deps as a hygiene problem, cross-language tooling survey (FawltyDeps, depend_on_what_you_use, bazel-deps), and the caveat that automation cannot be fully safe. ↩1 ↩2 ↩3 ↩4 ↩5

  9. Using FawltyDeps: when Gazelle does not tame your Python — aspect-based unused/missing dep detection for Python, emitting buildozer commands, and the opt-in-per-target design rationale. ↩1 ↩2