TExcelTAD
Home › Monorepo Builds: Bazel (+ Buck2 & Pants) › Remote Execution & REAPI

Remote Execution & REAPI

A remote cache lets machines share results. Remote execution goes one step further: Bazel doesn't run actions locally at all, it sends them to a cluster of workers. A laptop can then drive a build with 500 parallel compiles, and every action runs in an identical, controlled environment, which makes the cache trustworthy by construction.

Note: Remote execution needs a cluster (or a service account), so nothing in this lesson runs in the course image. The model below shows the protocol's logic; the remote cache lesson showed the caching half for real. Build Performance & Artifacts compares it with distcc and other distributed-build approaches.

How an action is executed remotely

The Remote Execution API (REAPI, build.bazel.remote.execution.v2) is an open gRPC protocol implemented by Bazel, Buck2, Pants, BuildStream, recc/Goma-style compilers and several servers. One action goes through these steps:

  1. Bazel computes the Action message: a digest of the Command (arguments, environment, output paths, platform properties) and of the input root, a Merkle tree of directories whose leaves are file digests.
  2. It asks the Action Cache: has this action digest been executed? If yes, done (a cache hit, as before).
  3. Otherwise it asks the CAS which input blobs are missing (FindMissingBlobs) and uploads only those.
  4. It calls Execute. The scheduler picks a worker matching the platform properties (e.g. OSFamily=Linux, container-image=docker://…), the worker downloads the inputs from the CAS, runs the command in a clean sandbox, uploads the outputs and writes an ActionResult to the Action Cache.
  5. Bazel downloads the outputs it needs (with "Build without the Bytes", only top-level outputs).

Because the input root is a Merkle tree, uploading a large repository is cheap: directories that didn't change have the same digest and are already in the CAS.

python · try it yourself
import hashlib, json

def h(data):
    return hashlib.sha256(data.encode()).hexdigest()[:10]

CAS, ACTION_CACHE, uploaded, executed = {}, {}, [], []

def put(blob):
    d = h(blob)
    if d not in CAS:
        CAS[d] = blob
        uploaded.append(d)
    return d

def merkle(files):
    """files: {path: content} -> root digest of a directory tree (Merkle tree)."""
    tree = {}
    for path, content in files.items():
        node = tree
        *dirs, name = path.split("/")
        for d in dirs:
            node = node.setdefault(d + "/", {})
        node[name] = put(content)
    def digest_dir(node):
        entries = {k: (digest_dir(v) if isinstance(v, dict) else v) for k, v in sorted(node.items())}
        return put(json.dumps(entries, sort_keys=True))
    return digest_dir(tree)

def execute(argv, files, platform):
    command = put(json.dumps({"argv": argv, "platform": platform}))
    action = h(command + merkle(files))
    if action in ACTION_CACHE:
        return f"cache hit   {action}"
    executed.append(action)
    ACTION_CACHE[action] = "out-" + h(str(files))      # a worker ran it and stored the result
    return f"executed    {action}"

repo = {"lib/math.h": "int triple(int);", "lib/math.cc": "int triple(int x){return 3*x;}",
        "docs/README": "x" * 1000}
plat = {"OSFamily": "Linux", "container-image": "ubuntu-24.04@sha256:..."}

print("1", execute(["gcc", "-c", "lib/math.cc"], repo, plat), "| blobs uploaded:", len(uploaded))
uploaded.clear()
print("2", execute(["gcc", "-c", "lib/math.cc"], repo, plat), "| blobs uploaded:", len(uploaded))
repo["lib/math.cc"] = "int triple(int x){return x+x+x;}"
print("3", execute(["gcc", "-c", "lib/math.cc"], repo, plat), "| blobs uploaded:", len(uploaded))
print("4", execute(["gcc", "-c", "lib/math.cc"], repo, {"OSFamily": "Windows"}), "| blobs uploaded:", len(uploaded))
print("actions executed:", len(executed), "| CAS blobs:", len(CAS))
1 executed    911f1a8f3b | blobs uploaded: 7
2 cache hit   911f1a8f3b | blobs uploaded: 0
3 executed    c3afb170ec | blobs uploaded: 3
4 executed    dc8bdffd6a | blobs uploaded: 4
actions executed: 3 | CAS blobs: 11

Run 2 is a pure cache hit with nothing uploaded. In run 3 one file changed, so only that file, the lib/ directory node and the root node were new: the unchanged docs/ subtree (and its large README) wasn't uploaded again. Run 4 shows that the platform is part of the key: the same command for Windows workers is a different action.

Configuring Bazel for remote execution

text
# .bazelrc  (illustrative values)
build:rbe --remote_executor=grpcs://remote.example.com
build:rbe --remote_instance_name=main
build:rbe --remote_header=x-api-key=…            # or --credential_helper
build:rbe --jobs=200                             # far more than local cores
build:rbe --extra_execution_platforms=//platforms:rbe_linux
build:rbe --host_platform=//platforms:rbe_linux
build:rbe --remote_download_outputs=toplevel
build:rbe --remote_timeout=3600
build:rbe --bes_backend=grpcs://remote.example.com   # stream build events to the UI
build:rbe --bes_results_url=https://app.example.com/invocation/
python
# //platforms/BUILD.bazel: what the workers look like
platform(
    name = "rbe_linux",
    constraint_values = ["@platforms//os:linux", "@platforms//cpu:x86_64"],
    exec_properties = {
        "OSFamily": "Linux",
        "container-image": "docker://gcr.io/my-project/rbe-ubuntu24@sha256:…",
    },
)

Toolchains must match the workers: a hermetic C++ toolchain (or one generated for the worker image) and the remote JDK/Python/Go toolchains that Bazel downloads anyway. Actions that can't run remotely get tags = ["no-remote-exec"] or --strategy=Mnemonic=local.

The server landscape

Service Kind Notes
BuildBuddy open-core + SaaS cache, RBE, build results UI (BES), flaky-test dashboards; self-hostable
EngFlow commercial (SaaS / on-prem) founded by former Bazel team members; RBE, cache, build and test analytics
NativeLink open source (Rust) + cloud cache and RBE, also used with Buck2 and Reclient
Buildbarn open source (Go) modular bb-storage/bb-scheduler/bb-worker; Kubernetes deployments
Buildfarm open source (Java, bazelbuild) the original reference implementation
bazel-remote open source (Go) cache only (AC + CAS), no execution

When to adopt remote execution rather than just a remote cache: when clean builds dominate (CI agents without warm caches, huge test fan-out), when local machines are the bottleneck, or when you need the hermeticity guarantee of identical workers. When most builds are incremental and caches are warm, a remote cache gives most of the benefit for a fraction of the operational cost.

Test yourself

What does the Merkle-tree input root buy remote execution?

  1. Encryption
  2. Only changed files and directories need to be uploaded; unchanged subtrees have known digests
  3. Faster compilers
  4. Smaller binaries

Why is the same command for a Windows worker a different action?

  1. Bazel can't cache Windows
  2. Platform properties are part of the action's Command, so its digest differs
  3. Different file paths
  4. It isn't

Which of these is a cache-only server, without remote execution?

  1. Buildbarn
  2. BuildBuddy
  3. bazel-remote
  4. EngFlow