Bazel
Bazel uses a precise vocabulary built around directed acyclic graphs (DAGs) and pure functional execution. Understanding these core terms will help you read BUILD files, debug sandbox errors, and navigate the documentation without confusion.
Glossary
Section titled “Glossary”1. Structural & File Organization
Section titled “1. Structural & File Organization”- Workspace: The entire directory tree on your filesystem containing all the source files for a single Bazel project.
MODULE.bazel: The modern root marker file (introduced with Bzlmod) that defines the workspace boundaries, declares external dependencies, and configures module extensions. (Replaces the legacyWORKSPACEfile).- Package: Any directory inside your workspace that contains a
BUILDorBUILD.bazelfile. A package includes all files in that directory and any subdirectories except those that contain their ownBUILDfiles. BUILD(orBUILD.bazel): A declarative configuration file written in Starlark that defines the build targets, rules, and dependencies for a specific package.- Starlark: The configuration language used in
BUILD,MODULE.bazel, and.bzlfiles. It is a deterministic, sandboxed subset of Python without I/O, network access, or arbitrary side effects. .bazelignore: A root file listing workspace directories Bazel should completely ignore (e.g.,node_modules,target/) so wildcards like//...don’t crawl or fail on non-Bazel trees.- Output Symlinks (
bazel-bin,bazel-out,bazel-testlogs): Convenience symlinks Bazel creates in the workspace root pointing into its external output base where compiled artifacts and test logs live (should be gitignored). - Repo (External Repository): A mounted filesystem directory boundary (addressed via @repo_name) containing Bazel packages and targets. Every module is backed by a repo, and module extensions can generate additional plain repos.
- bazel_dep: A declarative statement in MODULE.bazel that registers an external module dependency and mounts it as a repo in your workspace.
- Module Extension (use_extension): A Starlark factory defined in a .bzl file that accepts configuration tags (like Scala versions or Maven coordinates) and dynamically generates external repos.
- use_repo: A statement in MODULE.bazel that imports specific repos generated by a module_extension into your workspace’s @ namespace.
- .bzl File: A Bazel extension file containing reusable Starlark logic, wrapper macros, custom rules (rule(…)), module extensions, or shared constants.
2. Graph Nodes & Addressing
Section titled “2. Graph Nodes & Addressing”- Target: An addressable node in Bazel’s dependency graph defined inside a
BUILDfile. Targets can be files (source code or generated artifacts) or rules (instructions on how to create files). - Rule: A function in a
BUILDfile (e.g.,scala_binary,py_library,cc_test) that specifies the relationship between inputs and outputs, and registers the execution steps required to build them. - Label: The unique identifier string used to address any target in the workspace. A standard canonical label looks like
@repo//path/to/package:target_name.//denotes the root of the current workspace.:separates the package directory path from the specific target name.
- Visibility: An attribute on a target (
visibility = [...]) that controls which other packages are allowed to depend on it. By default, targets are private to their own package. - Runfiles (
data): Files a binary or test needs at runtime (configs, test fixtures, helper executables) rather than compile time. Declaring them in a target’sdataattribute—instead ofsrcsordeps—tells Bazel to stage them into the runtime sandbox so they don’t fail with “file not found.”
3. Execution & Build Phases
Section titled “3. Execution & Build Phases”- Loading Phase: The first phase of a build, where Bazel reads
MODULE.bazeland relevantBUILDfiles to parse targets and construct the initial dependency graph. - Analysis Phase: The second phase, where Bazel evaluates the rules, resolves toolchains, validates dependencies, and generates the Action Graph (the exact blueprint of commands to run).
- Execution Phase: The final phase, where Bazel actually runs the compilers, linkers, and test runners defined in the Action Graph—or fetches their outputs from the cache.
- Action: A single, atomic step during the execution phase (e.g., invoking
scalacon a specific set of.scalafiles to produce a.jar). Every action has strictly declared inputs and outputs. - Client / Server: Bazel uses a lightweight CLI client that communicates with a background server process per workspace, keeping the parsed dependency graph warm in memory for fast incremental builds (
bazel shutdownstops it).
4. Reproducibility & Caching
Section titled “4. Reproducibility & Caching”- Hermeticity: The property of a build being completely isolated from the host machine’s environment. A hermetic build cannot access undeclared files, system environment variables, or ambient network resources, guaranteeing identical outputs anywhere.
- Sandbox: An isolated temporary directory (using OS-level namespaces or symlinks) created for a single Action. Bazel mounts only the explicitly declared input files into the sandbox so the compiler cannot accidentally touch undeclared local files.
- Action Cache: A lookup table mapping a cryptographic hash of an Action’s inputs, flags, and compiler tools (Action Key) to its previously built output artifacts.
- Repository Cache: A content-addressable local disk cache (
--repository_cache) that stores downloaded external files (like Maven JARs or Python wheels) indexed by their SHA-256 hash so they aren’t re-downloaded across clean builds. - Remote Cache & RBE: Network extensions of the Action Cache (and optional Remote Build Execution) that let developers and CI share cached outputs or offload build actions to remote workers.
5. Extensions & Tooling
Section titled “5. Extensions & Tooling”- Bzlmod: Bazel’s modern external dependency management system (powered by
MODULE.bazelandMODULE.bazel.lock) that handles version resolution via Minimal Version Selection (MVS). .bzlFile: A Starlark extension file where reusable custom rules, macros, and repository extensions are written and loaded intoBUILDfiles viaload(...).- Macro: A Starlark function in a
.bzlfile that expands into one or more rules during the Loading Phase. Unlike a Rule (which registers build actions during analysis), a macro encapsulates repetitive target definitions to keepBUILDfiles concise. - Toolchain: An abstraction that decouples a build rule (e.g., “compile Scala”) from the specific platform tools required to run it (e.g., “use JDK 17 and Scala 3.9 on Linux x86_64”).
- Platform: A target describing a machine environment (OS, CPU architecture, and custom constraints) used to select the matching Toolchain and evaluate conditional
select()branches across host, execution, and target platforms. - Persistent Worker: A long-lived background process (commonly used for JVM/Scala compilers like Zinc) that stays warm across multiple Actions to avoid heavy runtime startup overhead while maintaining sandbox isolation.
- Gazelle: A fast, automated build-file generator that scans source code imports (
import ...,#include ...) and automatically updatesBUILDfiles with the corresponding dependency labels. - Bazelisk &
.bazelversion: A launcher wrapper (similar tonvm/pyenv) that automatically downloads and runs the exact Bazel version pinned in your repository’s.bazelversionfile. - Named Profile (
--config): A labeled group of command-line flags defined in.bazelrcusing<command>:<name>syntax (e.g.,build:ci,build:opt,build:asan). Invoking Bazel with--config=<name>expands all flags under that profile, making it easy to switch between build modes or environments without typing long flag lists.
Bazel Starlark Functions
Section titled “Bazel Starlark Functions”Bazel provides distinct sets of built-in Starlark functions depending on whether you are editing MODULE.bazel or a BUILD file. Because MODULE.bazel resolves the external dependency graph and BUILD files declare compilation targets, each file scope exposes only the functions relevant to its phase.
1. Functions Used in MODULE.bazel (Bzlmod)
Section titled “1. Functions Used in MODULE.bazel (Bzlmod)”These functions manage your project’s identity, external Bazel modules, and third-party package resolvers like Maven.
module(): Declares the name, version, and compatibility level of your root Bazel module. Must be called first.- Scala Example:
module(name = "my_scala_app", version = "0.1.0")
- Scala Example:
bazel_dep(): Declares a direct dependency on another Bazel module from the Bazel Central Registry (BCR).- Scala Example:
bazel_dep(name = "rules_scala", version = "7.4.0")
- Scala Example:
use_extension(): Instantiates a module extension (a Starlark hook that runs custom resolution logic, like fetching Maven artifacts) and returns a proxy object.- Scala Example:
maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven")
- Scala Example:
use_repo(): Imports repositories generated by ause_extension()proxy into your module’s scope so@repolabels resolve.- Scala Example:
use_repo(maven, "maven")
- Scala Example:
register_toolchains(): Registers specific compiler or runtime toolchains for Bazel’s toolchain resolution engine to select.- Scala Example:
register_toolchains("@rules_scala_toolchains//...")
- Scala Example:
single_version_override(): Forces a transitive Bazel module to use a specific version or patch, resolving version conflicts.- Scala Example:
single_version_override(module_name = "protobuf", version = "27.1")
- Scala Example:
git_override(): Overrides abazel_depto pull directly from a specific Git repository and commit hash instead of the BCR.- Scala Example:
git_override(module_name = "rules_scala", remote = "...", commit = "abc1234")
- Scala Example:
Complete MODULE.bazel Flow Example
Section titled “Complete MODULE.bazel Flow Example”module(name = "analytics_service", version = "1.0.0")
bazel_dep(name = "rules_scala", version = "7.4.0")bazel_dep(name = "rules_jvm_external", version = "6.1")
scala_config = use_extension("@rules_scala//scala/extensions:config.bzl", "scala_config")scala_config.settings(scala_version = "3.9.0")use_repo(scala_config, "rules_scala_toolchains")
maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven")maven.install( artifacts = ["org.typelevel:cats-effect_3:3.5.4"], lock_file = "//:maven_install.json",)use_repo(maven, "maven")2. Core Built-in Functions Used in BUILD Files
Section titled “2. Core Built-in Functions Used in BUILD Files”These functions are globally available in every BUILD and BUILD.bazel file without needing a load() statement.
load(): Imports rule functions, macros, or constants from a.bzlextension file into the currentBUILDfile.- Scala Example:
load("@rules_scala//scala:scala.bzl", "scala_library", "scala_binary")
- Scala Example:
glob(): Matches files in the current package directory using wildcard patterns (*,**) and returns a list of file labels.- Scala Example:
srcs = glob(["src/main/scala/**/*.scala"])
- Scala Example:
package(): Sets default metadata (like defaultvisibility) for every target defined in the currentBUILDfile.- Scala Example:
package(default_visibility = ["//visibility:public"])
- Scala Example:
exports_files(): Exposes raw source or config files in this package so other packages can reference them directly by label.- Scala Example:
exports_files(["application.conf"])
- Scala Example:
filegroup(): Groups a collection of files under a single target label so they can be passed together as inputs or resources.- Scala Example:
filegroup(name = "configs", srcs = glob(["conf/*.yaml"]))
- Scala Example:
alias(): Creates an alternative target label that points to another target (useful for renaming or platform switching).- Scala Example:
alias(name = "server", actual = "//src/app:http_server")
- Scala Example:
config_setting(): Defines a named build condition matching specific command-line flags or platform constraints (OS, CPU, compilation mode) so targets can branch on it.- Example:
config_setting(name = "linux_x86", constraint_values = ["@platforms//os:linux", "@platforms//cpu:x86_64"])
- Example:
select(): Makes any rule attribute (likedeps,srcs, or compiler flags) conditional onconfig_setting()targets—the standard way to write portable, multi-platformBUILDfiles without breaking hermeticity.- Example:
deps = [":core"] + select({":linux_x86": [":native_linux"], "//conditions:default": []})
- Example:
genrule(): A built-in escape hatch for running an arbitrary Bash command to transform declaredsrcsinto declaredoutswhen no dedicated language rule exists. Prefer language-specific rules or custom.bzlrules for anything complex or cross-platform.- Example:
genrule(name = "version_txt", outs = ["version.txt"], cmd = "echo 1.0.0 > $@")
- Example:
3. Scala Rule Functions (Loaded from rules_scala)
Section titled “3. Scala Rule Functions (Loaded from rules_scala)”Unlike built-ins, language-specific rules are Starlark functions imported via load().
scala_library(): Compiles.scalasource files into a.jarlibrary that other targets can depend on.- Example:
scala_library(name = "core", srcs = glob(["*.scala"]), deps = ["@maven//:org_typelevel_cats_core_3"])
- Example:
scala_binary(): Compiles.scalafiles and packages an executable wrapper script (plus an implicit_deploy.jartarget).- Example:
scala_binary(name = "cli", srcs = ["Main.scala"], main_class = "com.app.Main", deps = [":core"])
- Example:
scala_junit_test(): Compiles and runs JUnit-compatible test suites (including MUnit and ScalaTest) with test caching.- Example:
scala_junit_test(name = "core_test", srcs = glob(["*Spec.scala"]), deps = [":core", "@maven//:org_scalameta_munit_3"])
- Example:
scala_macro_library(): Compiles Scala code containing macros, ensuring the macro definitions are available on the compile-time classpath.- Example:
scala_macro_library(name = "macros", srcs = ["Macros.scala"])
- Example:
Complete BUILD.bazel Flow Example
Section titled “Complete BUILD.bazel Flow Example”load("@rules_scala//scala:scala.bzl", "scala_binary", "scala_library")
package(default_visibility = ["//visibility:public"])
filegroup( name = "app_resources", srcs = glob(["resources/*"]),)
scala_library( name = "domain", srcs = glob(["*.scala"], exclude = ["Main.scala"]), deps = [ "@maven//:org_typelevel_cats_effect_3", ],)
scala_binary( name = "app", srcs = ["Main.scala"], main_class = "com.example.Main", resources = [":app_resources"], deps = [ ":domain", "@maven//:org_typelevel_cats_effect_3", ],)Configuration (.bazelrc)
Section titled “Configuration (.bazelrc)”.bazelrc is Bazel’s configuration file for specifying default command-line flags and reusable flag presets, keeping build behavior consistent across developers and CI without repeating long flag lists.
-
strict_deps: A rules_scala check that fails the build if your code directly references a symbol from a transitive dependency without declaring it in your target’s direct deps.
-
unused_dependency_checker: A rules_scala check that inspects compiled bytecode to flag declared deps that aren’t actually used by your code.
-
Command-Scoped Defaults: Apply flags automatically to specific Bazel commands (
startup,common,build,test,run,query), e.g.,common --enable_bzlmodortest --test_output=errors. -
Named Profiles (
--config): Group related flags into reusable profiles (e.g.,build:ci,build:opt,build:asan) that can be activated on demand viabazel test --config=ci //.... -
Layered Precedence: Bazel loads rc files in order—system (
/etc/bazel.bazelrc), workspace (<workspace>/.bazelrc), user (~/.bazelrc), explicit (--bazelrc=<path>), and CLI flags—with later entries overriding earlier ones. -
Modular Imports: Compose configs across files using
import(required) ortry-import(optional), commonly used for untracked local overrides liketry-import %workspace%/user.bazelrc. -
Shared Team Standards: Checking
<workspace>/.bazelrcinto version control standardizes toolchain options, remote caching/execution settings, and CI behavior across the team.
CLI Commands & Target Patterns
Section titled “CLI Commands & Target Patterns”Essential Commands
Section titled “Essential Commands”bazel build <target>: Compiles the target and its transitive dependencies, placing outputs underbazel-bin/.bazel test <target>: Builds and executes test targets, caching passing results so unchanged tests aren’t re-run.bazel run <target>: Builds an executable target and runs it with itsdatarunfiles staged (pass runtime args after--, e.g.,bazel run //src/app:cli -- --port=8080).bazel query <expr>: Inspects the dependency graph without building—invaluable for debuggingBUILDfiles (e.g.,bazel query 'somepath(//app:server, @maven//:cats)'to see why a target depends on a library, orrdeps(//..., //lib:core)to find all reverse dependencies).bazel mod <subcommand>: Inspects the resolved Bzlmod dependency graph (e.g.,bazel mod graph,bazel mod explain <module>).bazel clean: Deletes output artifacts (rarely needed thanks to hermetic caching;bazel clean --expungealso wipes the external repository cache and shuts down the server).- Buildozer: A CLI tool from bazelbuild/buildtools that safely edits BUILD.bazel files via their AST (e.g., adding or removing deps) without breaking formatting or comments.
Target Patterns (Wildcards)
Section titled “Target Patterns (Wildcards)”//...: All targets recursively across the entire workspace.//pkg/...: All targets inpkgand every subpackage underneath it.//pkg:all: All rule targets inpkg(non-recursive).:target: Shorthand for a target in the current working directory’s package.-//pkg/...: Excludes a package subtree when combined with broader patterns (e.g.,bazel test -- //... -//experimental/...).