TExcelTAD

Why Bazel?

Make, CMake, Gradle and Cargo all work well for one project in one language. Things change when a company keeps hundreds of projects in one repository: a C++ library used by a Python tool, a Go service and a Java backend, thousands of engineers, and a CI system that must not rebuild and retest everything on every commit. Bazel was built for that situation. It is Google's internal build system Blaze, open-sourced in 2015, and today large companies and open-source projects such as TensorFlow, Envoy and gRPC build with it.

This course teaches Bazel 9 with Bzlmod, the way a build engineer runs it day to day, and compares it with Buck2 (Meta) and Pants (Toolchain Labs, Python-first).

Who this course is for

You already know what a build graph, an incremental build, a lockfile and a cache key are; Build Fundamentals covers them. Build Performance & Artifacts covers ccache, sccache and distributed builds, which this course builds on. You should be able to read code in at least one of C++, Python, Go or Java; every language rule is shown with a small example, so you don't need all four.

What Bazel promises

Promise How Bazel keeps it
Correct incremental builds every build step (an action) declares its inputs and outputs; Bazel reruns an action when the content hash of an input or of the command line changes, never because of a timestamp
Hermetic builds actions run in a sandbox that only contains their declared inputs, with a fixed environment; an undeclared dependency fails the build instead of working by accident
Reproducible results identical inputs give identical outputs, so outputs can be shared through a cache between machines
Scale the same build graph runs on a laptop, on a remote cache, or on hundreds of remote workers (remote execution)
One tool for every language C++, Java, Go, Python, Rust, protobuf, Docker images… are all rules in the same graph, so a change to a C++ library rebuilds exactly the Python and Go targets that depend on it

The price is that you must declare everything: every source file, every dependency, every tool. Most of this course is about how to do that well.

A first session

Every bash session in this course is a real Bazel run in a container: Bazelisk 1.30.0 launching Bazel 9.3.1, no network, with the rule sets served from a local mirror of the Bazel Central Registry. Here is the smallest possible C++ workspace:

bash · try it yourself
mkdir hello && cd hello
cat > MODULE.bazel <<'EOF'
module(name = "hello")

bazel_dep(name = "rules_cc", version = "0.2.27")
EOF
mkdir app
cat > app/BUILD.bazel <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_binary")

cc_binary(
    name = "hello",
    srcs = ["hello.cc"],
)
EOF
cat > app/hello.cc <<'EOF'
#include <iostream>
int main() { std::cout << "Hello from Bazel!\n"; }
EOF
bazel build //app:hello
./bazel-bin/app/hello
bazel build //app:hello
Starting local Bazel server (9.3.1) and connecting to it...
INFO: Analyzed target //app:hello (93 packages loaded, 545 targets configured).
INFO: Found 1 target...
Target //app:hello up-to-date:
  bazel-bin/app/hello
INFO: Elapsed time: 3.807s, Critical Path: 0.27s
INFO: 7 processes: 5 internal, 2 processwrapper-sandbox.
INFO: Build completed successfully, 7 total actions
Hello from Bazel!
INFO: Analyzed target //app:hello (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
Target //app:hello up-to-date:
  bazel-bin/app/hello
INFO: Elapsed time: 0.338s, Critical Path: 0.00s
INFO: 1 process: 1 internal.
INFO: Build completed successfully, 1 total action

Read it top to bottom:

  1. MODULE.bazel marks the root of the workspace and says which external modules it needs: only rules_cc, which provides cc_binary.
  2. app/BUILD.bazel makes app/ a package and declares one target, //app:hello.
  3. The first bazel build starts a Bazel server (a long-lived JVM process that keeps the build graph in memory between commands), loads the packages, analyzes the target, then runs 7 actions: most are "internal" bookkeeping, and 2 ran in the processwrapper-sandbox (compile and link).
  4. The output goes into bazel-bin/, a symlink into Bazel's output tree.
  5. The second build does nothing: the target is up to date. Bazel checked the content hashes of the inputs against its action cache.

The three phases

Every Bazel command goes through the same phases. Their names show up in error messages, so it pays to learn them now.

Phase What happens Errors you see here
Loading read MODULE.bazel, fetch external repositories, evaluate BUILD files and the .bzl files they load() syntax errors, unknown rules, missing packages
Analysis resolve dependencies and configurations, run each rule's implementation, which declares actions (nothing runs yet) visibility errors, missing providers, toolchain resolution errors
Execution run the actions whose outputs are needed and not cached, in a sandbox, locally or remotely compiler errors, test failures, sandbox violations

Bazel builds the action graph in analysis and then executes only the part of it the requested targets need. That's why bazel build //app:hello never compiles code from other packages unless hello depends on them.

What's in the workspace now

bash · try it yourself
mkdir hello && cd hello
printf 'module(name = "hello")\nbazel_dep(name = "rules_cc", version = "0.2.27")\n' > MODULE.bazel
mkdir app
printf 'load("@rules_cc//cc:defs.bzl", "cc_binary")\ncc_binary(name = "hello", srcs = ["hello.cc"])\n' > app/BUILD.bazel
echo 'int main() { return 0; }' > app/hello.cc
bazel build //app:hello 2>/dev/null
ls
readlink bazel-bin | sed "s#$HOME#~#"
bazel info output_base 2>/dev/null | sed "s#$HOME#~#"
MODULE.bazel
MODULE.bazel.lock
app
bazel-bin
bazel-hello
bazel-out
bazel-testlogs
~/.cache/bazel/_bazel_learner/a53c137e646f5eeecd4294c5c4273af1/execroot/_main/bazel-out/k8-fastbuild/bin
~/.cache/bazel/_bazel_learner/a53c137e646f5eeecd4294c5c4273af1
Path What it is
MODULE.bazel, MODULE.bazel.lock the module definition and the resolved dependency graph (commit both)
bazel-bin, bazel-out, bazel-testlogs convenience symlinks into the output tree: build outputs, all outputs, test logs
bazel-hello the execution root: the directory actions run in, a symlink forest of your sources and external repos
~/.cache/bazel/_bazel_$USER/<hash>/ the output base for this workspace (the hash is the MD5 of the workspace path); bazel clean --expunge deletes it

Add the bazel-* symlinks to .gitignore; they are recreated on every build.

How this course runs

Part Lessons
Basics Bzlmod, labels, visibility
Rules C++, Python, Go and Java rules, then all four in one graph
Testing and querying bazel test, sharding, query, cquery, aquery
Extending Starlark macros, genrule, custom rules, providers
Correctness platforms and toolchains, sandboxing, the action environment
Speed incremental builds, the disk cache, a real remote cache (bazel-remote), remote execution concepts
Adopting lockfiles and external repos, migrating CMake and Gradle repos, Buck2 and Pants compared
Practice Toolkit and Field Notes lessons, exercises, and a polyglot monorepo mini project

Note: Buck2, Pants, Gazelle, buildifier and remote execution services are not installed in the course image. Lessons about them say so and show their configuration as non-run examples.

Test yourself

Why does Bazel rerun a compile action?

  1. The source file's modification time is newer than the object file
  2. The content hash of an input or the action's command line changed
  3. Every build reruns all actions
  4. Only when you run bazel clean

In which phase does a rule's implementation function run?

  1. Loading
  2. Analysis
  3. Execution
  4. Fetching

What is bazel-bin?

  1. A directory you commit
  2. A symlink into Bazel's output tree where build outputs land
  3. The Bazel binary
  4. A cache server