Skip to main content
When writing rules, the most common performance pitfall is to traverse or copy data that is accumulated from dependencies. When aggregated over the whole build, these operations can easily take O(N^2) time or space. To avoid this, it is crucial to understand how to use depsets effectively. This can be hard to get right, so Bazel also provides a memory profiler that assists you in finding spots where you might have made a mistake. Be warned: The cost of writing an inefficient rule may not be evident until it is in widespread use.

Use depsets

Whenever you are rolling up information from rule dependencies you should use depsets. Only use plain lists or dicts to publish information local to the current rule. A depset represents information as a nested graph which enables sharing. Consider the following graph:
Each node publishes a single string. With depsets the data looks like this:
Note that each item is only mentioned once. With lists you would get this:
Note that in this case 'a' is mentioned four times! With larger graphs this problem will only get worse. Here is an example of a rule implementation that uses depsets correctly to publish transitive information. Note that it is OK to publish rule-local information using lists if you want since this is not O(N^2).
See the depset overview page for more information.

Avoid calling depset.to_list()

You can coerce a depset to a flat list using to_list(), but doing so usually results in O(N^2) cost. If at all possible, avoid any flattening of depsets except for debugging purposes. A common misconception is that you can freely flatten depsets if you only do it at top-level targets, such as an <xx>_binary rule, since then the cost is not accumulated over each level of the build graph. But this is still O(N^2) when you build a set of targets with overlapping dependencies. This happens when building your tests //foo/tests/..., or when importing an IDE project.

Reduce the number of calls to depset

Calling depset inside a loop is often a mistake. It can lead to depsets with very deep nesting, which perform poorly. For example:
This code can be replaced easily. First, collect the transitive depsets and merge them all at once:
This can sometimes be reduced using a list comprehension:

Use ctx.actions.args() for command lines

When building command lines you should use ctx.actions.args(). This defers expansion of any depsets to the execution phase. Apart from being strictly faster, this will reduce the memory consumption of your rules — sometimes by 90% or more. Here are some tricks:
  • Pass depsets and lists directly as arguments, instead of flattening them yourself. They will get expanded by ctx.actions.args() for you. If you need any transformations on the depset contents, look at ctx.actions.args#add to see if anything fits the bill.
  • Are you passing File#path as arguments? No need. Any File is automatically turned into its path, deferred to expansion time.
  • Avoid constructing strings by concatenating them together. The best string argument is a constant as its memory will be shared between all instances of your rule.
  • If the args are too long for the command line an ctx.actions.args() object can be conditionally or unconditionally written to a param file using ctx.actions.args#use_param_file. This is done behind the scenes when the action is executed. If you need to explicitly control the params file you can write it manually using ctx.actions.write.
Example:

Transitive action inputs should be depsets

When building an action using ctx.actions.run, do not forget that the inputs field accepts a depset. Use this whenever inputs are collected from dependencies transitively.

Hanging

If Bazel appears to be hung, you can hit Ctrl-\ or send Bazel a SIGQUIT signal (kill -3 $(bazel info server_pid)) to get a thread dump in the file $(bazel info output_base)/server/jvm.out. Since you may not be able to run bazel info if bazel is hung, the output_base directory is usually the parent of the bazel-<workspace> symlink in your workspace directory.

Performance profiling

Bazel writes a JSON profile to command.profile.gz in the output base by default. You can configure the location with the --profile flag, for example --profile=/tmp/profile.gz. Location ending with .gz are compressed with GZIP. To see the results, open chrome://tracing in a Chrome browser tab, click “Load” and pick the (potentially compressed) profile file. For more detailed results, click the boxes in the lower left corner. You can use these keyboard controls to navigate:
  • Press 1 for “select” mode. In this mode, you can select particular boxes to inspect the event details (see lower left corner). Select multiple events to get a summary and aggregated statistics.
  • Press 2 for “pan” mode. Then drag the mouse to move the view. You can also use a/d to move left/right.
  • Press 3 for “zoom” mode. Then drag the mouse to zoom. You can also use w/s to zoom in/out.
  • Press 4 for “timing” mode where you can measure the distance between two events.
  • Press ? to learn about all controls.

Profile information

Example profile: Example profile Figure 1. Example profile. There are some special rows:
  • action counters: Displays how many concurrent actions are in flight. Click on it to see the actual value. Should go up to the value of --jobs in clean builds.
  • cpu counters: For each second of the build, displays the amount of CPU that is used by Bazel (a value of 1 equals one core being 100% busy).
  • Critical Path: Displays one block for each action on the critical path.
  • grpc-command-1: Bazel’s main thread. Useful to get a high-level picture of what Bazel is doing, for example “Launch Bazel”, “evaluateTargetPatterns”, and “runAnalysisPhase”.
  • Service Thread: Displays minor and major Garbage Collection (GC) pauses.
Other rows represent Bazel threads and show all events on that thread.

Common performance issues

When analyzing performance profiles, look for:
  • Slower than expected analysis phase (runAnalysisPhase), especially on incremental builds. This can be a sign of a poor rule implementation, for example one that flattens depsets. Package loading can be slow by an excessive amount of targets, complex macros or recursive globs.
  • Individual slow actions, especially those on the critical path. It might be possible to split large actions into multiple smaller actions or reduce the set of (transitive) dependencies to speed them up. Also check for an unusual high non-PROCESS_TIME (such as REMOTE_SETUP or FETCH).
  • Bottlenecks, that is a small number of threads is busy while all others are idling / waiting for the result (see around 15s-30s in above screenshot). Optimizing this will most likely require touching the rule implementations or Bazel itself to introduce more parallelism. This can also happen when there is an unusual amount of GC.

Profile file format

The top-level object contains metadata (otherData) and the actual tracing data (traceEvents). The metadata contains extra info, for example the invocation ID and date of the Bazel invocation. Example:
Timestamps (ts) and durations (dur) in the trace events are given in microseconds. The category (cat) is one of enum values of ProfilerTask. Note that some events are merged together if they are very short and close to each other; pass --noslim_json_profile if you would like to prevent event merging. See also the Chrome Trace Event Format Specification.

analyze-profile

This profiling method consists of two steps, first you have to execute your build/test with the --profile flag, for example
The file generated (in this case /tmp/prof) is a binary file, which can be postprocessed and analyzed by the analyze-profile command:
By default, it prints summary analysis information for the specified profile datafile. This includes cumulative statistics for different task types for each build phase and an analysis of the critical path. The first section of the default output is an overview of the time spent on the different build phases:

Memory profiling

Bazel comes with a built-in memory profiler that can help you check your rule’s memory use. If there is a problem you can dump the heap to find the exact line of code that is causing the problem.

Enabling memory tracking

You must pass these two startup flags to every Bazel invocation:
Note: The bazel repository comes with an allocation instrumenter. Make sure to adjust $(BAZEL) for your repository location. These start the server in memory tracking mode. If you forget these for even one Bazel invocation the server will restart and you will have to start over.

Using the Memory Tracker

As an example, look at the target foo and see what it does. To only run the analysis and not run the build execution phase, add the --nobuild flag.
Next, see how much memory the whole Bazel instance consumes:
Break it down by rule class by using bazel dump --rules:
Look at where the memory is going by producing a pprof file using bazel dump --skylark_memory:
Use the pprof tool to investigate the heap. A good starting point is getting a flame graph by using pprof -flame $HOME/prof.gz. Get pprof from https://github.com/google/pprof. Get a text dump of the hottest call sites annotated with lines: