Technical document

Four Bottlenecks and Solutions that Slow Down Builds After Bazel Adoption

When Bazel adoption doesn't speed things up, we organize a method to identify and resolve four bottlenecks—runner, Docker validation, dependency graph, and CPU/memory—from measurement to incremental improvement through remote execution.
Build Platform / Performance Optimization~18 minPublication Date September 22, 2026Update date November 23, 2026
Illustration of an engineer reconfiguring Bazel's serialized processes into multiple parallel paths

Summary

Key points of this document

  • Simply adopting Bazel does not speed up the entire build.
  • First, identify where the waiting occurs from the profile and total time.
  • Bottleneck 1: Fold the runner's for-loop into a single Bazel invocation.

Overview

While Bazel can parallelize builds and tests by understanding dependencies, it cannot achieve optimal performance if services are processed sequentially outside of it, or if a huge common dependency becomes a single queue. The key to maximum speed is to pass all necessary targets to Bazel at once, measure the critical path, and shorten the serialized sections, both external and internal, one by one.

Simply adopting Bazel does not speed up the entire build.

Bazel can only optimize the dependency graph passed to it and the actions defined within it. In a configuration where a shell script selects services one by one, launching Bazel each time, docker loading artifacts, and waiting for HTTP responses before proceeding, Bazel cannot see parallelizable work internally. Even if individual service builds are fast, the overall process is dominated by external queues.

Conversely, it's not always best to cram everything into a single call. //..., which represents the entire workspace, is an important target that should always be valid on a stable branch, but building all services with every change increases unnecessary analysis and actions. The principle is to 'pass multiple necessary targets at once,' not to 'always build all targets.'

For post-adoption performance improvement, measurement is not limited to Bazel's execution time. The total time from CI job start to artifact validation completion is considered, and this is divided into four layers: runner, validation, dependency graph, and execution resources. If these boundaries are ambiguous and only --jobs is increased, actual serialized sections will persist while increasing memory shortages and I/O contention.

First, identify where the waiting occurs from the profile and total time.

Bazel's JSON Trace Profile records the number of concurrent actions, CPU usage, main thread, garbage collection, and critical path. First, for the same set of targets, record a clean equivalent without cache and an incremental build after changes separately. Mixing them makes it impossible to distinguish between dependency graph improvements and cache hit effects.

If the action count remains low in the profile, suspect insufficient executable actions, serialized dependencies, resource reservation, or waiting due to external processing. If the CPU is idle but a single critical path is long, increasing --jobs will not shorten it. Conversely, if there are many executable actions but CPU and memory are maxed out, it indicates a problem with local resources or remote execution.

Time outside of Bazel is also recorded in sections by the runner. Target selection, Bazel invocation, artifact transfer, docker load, container startup, HTTP Probe, and cleanup are measured separately. Instead of just comparing end times, finding idle time when Bazel is not working is the first step to improvement.

// Example of saving profiles for the same target set
bazel build //services/... \
  --profile=/tmp/bazel-profile.json.gz

bazel analyze-profile /tmp/bazel-profile.json.gz

Bottleneck 1: Fold the runner's for-loop into a single Bazel invocation.

A for-loop that calls bazel build for each service passes only one top-level target at a time. Even if Bazel server state and local cache can be reused, serialization remains where service B's actions cannot start until service A completes. The more manually the runner determines dependency order, the less room Bazel's scheduler has to arrange things globally.

The fix is to first define the set of labels required for release or validation, and then pass them to a single bazel build or bazel test. If it's all rules under services, use //services/...; if it's only specific artifacts, list individual labels. Only choose //... when checking the entire workspace. Separate target selection and execution order, making the runner responsible for selection and Bazel for order based on the dependency graph.

Even when passing artifacts from multiple services to a subsequent stage, there's no need to separate Bazel invocations. Generate a dedicated target pattern to aggregate top-level targets or an explicit list of labels, and obtain the necessary artifacts as a result of a single invocation. For CI that wants to collect all failures, --keep_going is an option, but since downstream dependencies of failed ones cannot execute, measure and decide based on the trade-off with completion time.

  • If the target is the whole, use //..., if it's a single domain, use //services/..., and if it's a limited artifact, use multiple explicit labels.
  • The runner selects the target. Dependency order and parallel execution are left to Bazel.
  • Compare analysis time, number of actions, critical path, and idle time outside Bazel before and after batching.
// Sequential service calls to avoid
for service in api worker gateway; do
  bazel build "//services/$service:image"
done
// Pass the required top-level targets at once
bazel build \
  //services/api:image \
  //services/worker:image \
  //services/gateway:image

Bottleneck 2: Separate Docker validation into quick verification and artifact verification.

Validation that involves docker load for each artifact, starting a container, and waiting for an HTTP Probe includes I/O for image expansion, port allocation, process startup, and waiting for readiness. If you cannot start over 100 services simultaneously on a single machine, simply increasing the degree of parallelism will not solve the problem. It can lead to contention for disk I/O and memory, increasing timeouts and unstable validations.

First, separate the purposes of validation. Behaviors that do not require process boundaries, such as HTTP handlers, authentication decisions, routing, and serialization, are verified in-process. For Go, use httptest.ResponseRecorder or httptest.Server; for other languages, start the handler or application within the test process. Placing these in Bazel's test targets allows you to leverage caching and parallel execution according to the dependency graph.

On the other hand, for smoke tests that verify entry points, file placement within the image, non-root privileges, OS-dependent libraries, and actual listening, Docker cannot be omitted. Here, focus only on changed services or a representative set of images, and parallelize them with independent ports and working areas. This design does not replace container validation with unit/contract tests, but rather reduces the scope of what each validation guarantees.

In Bazel tests, adjust size and timeout to match reality, and correctly declare resource reservations for heavy tests. Tests that support sharding can be split, but tests that contend for the same Docker daemon or shared DB should not be unconditionally parallelized. Distinguish validations that depend on external state from cacheable hermetic tests, and explicitly define execution conditions and cleanup.

  • In-process: handler, routing, input validation, authentication decision, response contract.
  • Container smoke: startup command, artifact placement, permissions, listening, health check.
  • Integration validation: connection to external states like DBs and queues. Explicitly define shared resources and initialization for re-execution.
  • Determine the number of containers to launch based on change impact and validation responsibility, not the number of services.

Bottleneck 3: Split large common libraries to regain width in the dependency graph.

If all services depend on one giant common library, its build becomes the entry point of the critical path. If unrelated HTTP helpers, data transformations, monitoring, authentication, and generated code coexist within it, a single change invalidates a large target, and all downstream targets wait for completion. Even if the CPU is idle, actions that cannot yet be executed due to dependencies cannot be parallelized.

Bazel's recommendation is to declare only the directly needed dependencies and to separate directories containing buildable files into appropriate packages. The purpose of making BUILD definitions smaller is not to reduce the number of files, but to reduce the scope of invalidation due to changes and the number of dependency edges. If all services still depend on all targets after splitting, the shape of the graph will not change.

Use query to check the target graph, cquery for the configured target graph, and aquery for the actual action graph. Use somepath to find unintended paths to common targets, and aquery summary to track increases in actions like generation, compilation, and linking. The effect of splitting is determined not by the number of lines in BUILD files, but by the number of actions re-executed during changes and the shortening of the critical path.

Commonality itself is not bad. Contracts that are stable, computationally inexpensive, and genuinely used by many services are suitable for sharing. The problem is when frequently changing functional implementations or heavy generation processes are also gathered into convenient common targets. Separating stable interfaces from changeable implementations and restricting usage scope with visibility prevents a return to giant targets.

  • Evaluate common targets along three axes: frequency of change, computational cost, and number of consuming services.
  • Place only directly used dependencies in deps to reduce accidental references to transitive dependencies and excessive dependencies.
  • Perform package splitting, target splitting, visibility adjustments, and dependency edge modifications as a set.
// Example of checking dependency paths and action summaries
bazel query \
  'somepath(//services/orders:image, //libs/common:core)'

bazel aquery \
  'deps(//services/orders:image)' \
  --output=summary

Bottleneck 4: Solve local resource limits separately with caching and RBE.

When the dependency graph is wide enough and there are many executable actions, but the CPU and memory reach their limits, local resources become a bottleneck. --jobs sets the upper limit on the number of jobs that can be executed; increasing it does not always make things faster. Over-scheduling memory-intensive compilations or tests can increase swapping, garbage collection, and I/O wait times, actually slowing down the overall process.

The first option is remote caching. Bazel identifies results from action inputs, output names, commands, environment variables, etc., and if the same result exists, it can be reused on another terminal or CI. However, caching does not add execution capability. If a large number of actions are required due to low-level changes or cache misses, the local terminal will execute all of them.

RBE distributes build and test actions to multiple remote workers, scaling the execution itself during cache misses. While it can reduce terminal differences, it assumes that rules and toolchains are compatible with remote execution, inputs are declared, and there is no dependency on untracked tools or implicit environment variables on the host. Network transfer, queue time, worker configuration, and costs also become new operational considerations.

The basic order of introduction is to ensure reproducibility, measure cache hit rates, implement remote cache, and then RBE if necessary. Sharing irreproducible actions as-is can spread cache pollution and inconsistencies between terminals. Authentication, write permissions, and retention periods should also be included in the build design, such as limiting cache writers to CI and making development terminals read-only.

  • Remote cache: Reuses existing action results. Cache misses must be filled by execution.
  • RBE: Distributes action execution, including cache misses, to remote workers.
  • --jobs: Parallelism limit. Do not set higher than actual CPU, memory, I/O, and test resource availability.
  • Shared prerequisites: Inputs, toolchains, environment variables, and outputs are reproducible, and authentication and write permissions are managed.
// Example concept for .bazelrc to make the development machine a read-only cache client
build --remote_cache=<REMOTE_CACHE_ENDPOINT>
build --remote_upload_local_results=false

If you have more than 100 services, determine verification targets based on change impact instead of starting all of them.

As the number of services increases, the policy of building everything and starting everything every time becomes difficult to sustain, not only in terms of terminal performance but also as a design for feedback time. The value of using Bazel's dependency graph is not just to process everything quickly, but also to narrow down the processing volume to targets affected by changes.

For daily changes, select necessary builds and tests from the reverse dependencies of changed packages and pass the target labels to Bazel at once. For stable branches or periodic runs, use //... and a broad test suite to check for omissions in the daily path selection. By separating fast paths and comprehensive paths, the heaviest verification is not imposed on all changes, and errors in the verification scope are not overlooked.

Container smoke tests follow the same idea. Target changed services, services affected by common base images or startup conventions, and representative heterogeneous configurations. Instead of starting 100 containers simultaneously, they are executed in parallel within bounds by a small number of independent workers, and logs, exit codes, and startup times are preserved as artifacts in case of failure.

  • Pull request: Execute builds, tests, and necessary container smoke tests for change impact in one go.
  • Stable branch: Detect omissions in target selection with //... and a broad test suite.
  • Periodic execution: Measure clean builds, low cache hit conditions, and representative integration verifications.

Apply improvements layer by layer and compare before and after with the same metrics.

If multiple improvements are introduced simultaneously, it's impossible to distinguish why things got faster from why they became unstable. First, consolidate runner calls, then separate verification responsibilities, and then granularize the dependency graph. Evaluating remote cache and RBE after sufficient parallelism is achieved locally makes it harder to hide graph defects with infrastructure costs.

At each stage, record not only the median wall time but also P95, analysis time, number of executed actions, critical path, average concurrent actions, CPU and memory peaks, remote cache hit, remote queue, and Docker startup time. If speed improvement only appears in P50 and P95 worsens, it may indicate increased contention or network waiting.

The ultimate completion condition is not to create the fastest single run. It is to confirm that it is fast and reproducible under the same change conditions, that it is clear which layer got stuck on failure, that it completes within an acceptable time even with an empty cache, and that the same artifacts can be handled on development terminals and CI.

    1. Eliminate serial calls outside the runner.
    1. Divide verification responsibilities into in-process, Bazel test, and container smoke tests.
    1. Split large targets and excessive dependencies on the critical path.
    1. If executable actions reach resource limits, introduce remote cache, and RBE if necessary.
    1. Separate clean and incremental, P50 and P95, and monitor regressions under the same conditions.

There are bottlenecks that are not resolved even with remote execution.

Remote cache is effective only when results for the same action key exist. Actions that embed changing timestamps into artifacts, use undeclared host tools, or have environment variables that differ per terminal will lower the hit rate. Instead of attributing a low hit rate solely to network or cache capacity issues, it is necessary to compare execution logs with action inputs.

RBE also cannot parallelize serial dependency graphs. A single heavy action on the critical path remains a single action, even if it can be moved to a faster worker. Furthermore, tests that directly depend on the Docker daemon or processes that assume the state of the terminal may not be able to be sent to a remote worker as is.

When reducing container verification, explicitly state the lost guarantees. In in-process tests, the image's entrypoint, file owner, OS libraries, and signal handling are unknown. Increasing faster verifications while retaining a small number of smoke tests that actually launch the distribution is a realistic balance between speed and reliability.

Do not create a waiting line outside of Bazel; shorten the single path inside.

The most important aspect of speeding up after Bazel adoption is to pass the necessary target set and dependencies at once, rather than through per-service procedures. If the runner does not control the order, Bazel can execute available actions concurrently. Furthermore, moving verifications that do not require Docker to test targets and splitting large common dependencies expands the scope of work that can be run in parallel.

When CPU and memory truly reach their limits, remote cache provides reuse, and RBE adds execution capacity. Neither can substitute for reproducible actions and accurate dependency graphs. Measuring external serialization, internal critical paths, and local resource limits in order, and choosing corresponding solutions for each, leads to a Bazel operation that can be maintained even as scale increases.

References

Specifications for measurement methods, dependencies, tests, remote cache, and remote execution can be found in the following official documentation. Since Bazel flags and experimental features vary by version, please also check the documentation for the version you are actually using.

Technical documents

We will continue to increase technical documentation.

We will continue to organize our thoughts on AI, cloud, business app development, requirements definition, and operational design into documents.

Go to technical documentation list