TExcelTAD

Remote Execution & REAPI

distcc and ccache bolt caching and distribution onto compilers that were never designed for it, using heuristics: preprocess, guess which inputs matter, hope every helper has the same compiler. Remote execution does it properly, from the build system down. Every build step is described as an action with exactly its inputs, its command and its expected outputs, so it can be cached and executed anywhere with a guarantee of the same result.

The standard protocol is the Remote Execution API (REAPI), a set of gRPC services that came out of Google's internal build system and is used by Bazel, Buck2, Pants, BuildStream, recc (a REAPI client for plain compilers) and others. Servers include BuildBarn, Buildfarm, BuildGrid, NativeLink, and commercial services (EngFlow, BuildBuddy, Google's RBE). Bazel uses all of this hands-on; this lesson covers the model.

The pieces

REAPI concept What it is
Digest sha256 hash + size of a blob: every file and message is addressed by its content
CAS (Content-Addressable Storage) a store of blobs by digest: source files, headers, compilers, outputs
Command argv, environment, output paths
Action digest of the Command + digest of the input root (a Merkle tree of all input files) + timeout and platform properties
ActionCache maps an Action digest to an ActionResult (exit code, stdout/stderr digests, output file digests)
Execution service runs an Action on a worker if the ActionCache has no result

A client builds the input tree, uploads only the blobs the CAS doesn't already have (FindMissingBlobs), asks the ActionCache for a result, and if there's none, calls Execute. The worker downloads the inputs from the CAS, runs the command in a sandbox, uploads the outputs and records the result in the ActionCache. Nothing depends on paths, mtimes or which machine you're on: the action digest is the cache key.

Computing an action key

This model computes REAPI-style digests in plain Python (real REAPI serialises protobuf messages; the principle is the same). It shows that the key changes when an input file, a flag or the compiler changes, and doesn't change when only the path of the workspace does:

python · try it yourself
import hashlib, json

def digest(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()[:12] + f"/{len(data)}"

def input_root(files: dict) -> str:
    # Merkle tree, flattened: sorted (relative path, content digest) pairs
    entries = [(path, digest(content.encode())) for path, content in sorted(files.items())]
    return digest(json.dumps(entries).encode())

def action_key(argv, files, compiler_blob):
    command = digest(json.dumps({"argv": argv, "env": {"PATH": "/usr/bin"}}).encode())
    root = input_root({**files, "toolchain/bin/g++": compiler_blob})
    return digest(json.dumps({"command": command, "input_root": root}).encode())

files = {"src/util.cpp": "#include \"util.hpp\"\nint util() { return 1; }\n",
         "src/util.hpp": "int util();\n"}
argv = ["toolchain/bin/g++", "-O2", "-Isrc", "-c", "src/util.cpp", "-o", "util.o"]
base = action_key(argv, files, "gcc-13.3.0")

checks = {
    "same inputs, other workspace path": action_key(argv, dict(files), "gcc-13.3.0"),
    "header edited": action_key(argv, {**files, "src/util.hpp": "int util(); // doc\n"}, "gcc-13.3.0"),
    "-O2 -> -O3": action_key([a if a != "-O2" else "-O3" for a in argv], files, "gcc-13.3.0"),
    "compiler upgraded": action_key(argv, files, "gcc-13.4.0"),
}
print("base action:", base)
for what, key in checks.items():
    print(f"{what:<35} {'cache HIT' if key == base else 'new key -> execute'}")
base action: 638b168a8779/65
same inputs, other workspace path   cache HIT
header edited                       new key -> execute
-O2 -> -O3                          new key -> execute
compiler upgraded                   new key -> execute

Note what's different from ccache:

  • The compiler is an input like any file (in real setups, a toolchain from a pinned container image or a hermetic toolchain rule), not something guessed by mtime.
  • Even a comment change in a header changes the key: REAPI hashes inputs, it doesn't preprocess. Bazel compensates with fine-grained targets so fewer actions see each header.
  • Paths are relative to the input root, so there's no base_dir problem.

Queueing: when remote execution helps

Remote execution gives you a pool of workers shared by everyone. Your build's speed then depends on how busy the pool is. This deterministic simulation runs 600 actions (durations from a fixed pattern) on pools of different sizes, with a fixed per-action overhead for uploading inputs and downloading outputs, while other teams' work occupies part of the pool:

python · try it yourself
def simulate(actions, workers, overhead, busy_fraction):
    """Greedy list scheduling: each action goes to the worker that frees up first."""
    free_workers = max(1, int(workers * (1 - busy_fraction)))
    finish = [0.0] * free_workers
    for d in actions:
        i = finish.index(min(finish))
        finish[i] += d + overhead
    return max(finish)

pattern = [1.5, 2.0, 0.5, 4.0, 1.0, 3.0, 0.8, 6.0, 1.2, 2.5]          # seconds, repeating
actions = [pattern[i % len(pattern)] for i in range(600)]
local = simulate(actions, 16, 0.0, 0.0)
print(f"local, 16 cores:                 {local:7.1f} s")
for workers, busy in [(64, 0.0), (256, 0.0), (256, 0.75), (1024, 0.5)]:
    t = simulate(actions, workers, 0.3, busy)
    print(f"remote, {workers:>4} workers, {busy:>4.0%} busy: {t:7.1f} s  ({local / t:4.1f}x)")
local, 16 cores:                    88.2 s
remote,   64 workers,   0% busy:    28.3 s  ( 3.1x)
remote,  256 workers,   0% busy:    10.5 s  ( 8.4x)
remote,  256 workers,  75% busy:    28.3 s  ( 3.1x)
remote, 1024 workers,  50% busy:     7.4 s  (11.9x)
  • With an idle pool, 256 workers turn a long local build into a short one, even with 0.3 s of transfer overhead per action.
  • When other teams keep 75% of the pool busy, you effectively have 64 workers.
  • Very large pools stop helping once there are more workers than actions in flight, and the longest action plus overhead sets the floor (the critical path again).

What remote execution needs from your build

  • Hermetic actions: every input declared, no reading of undeclared files (/usr/include on the worker isn't yours), no network. Bazel enforces this with sandboxing; see Hermetic Builds.
  • Deterministic outputs: timestamps, absolute paths or unordered maps in outputs produce different digests for the same action and poison downstream cache hits.
  • Platform properties: actions declare the OS, CPU and container image they need, so workers with the right toolchain pick them up.
  • Remote caching first: most teams start with only the cache part (--remote_cache), which the Bazel course runs locally with bazel-remote, and add execution later.

Test yourself

In REAPI, what is the cache key of a build step?

  1. The output file name
  2. The digest of the Action: the Command digest plus the input root digest
  3. The source file's mtime
  4. The worker's hostname

Why does moving the workspace to another path not change the action key?

  1. Paths are ignored entirely
  2. Inputs are addressed relative to the input root, and absolute paths aren't part of the action
  3. REAPI uses base_dir
  4. The key is the git commit

What does FindMissingBlobs avoid?

  1. Running actions twice
  2. Uploading files the CAS already has
  3. Cache misses
  4. Sandboxing