4.4.4 Persistent Workers for Rule Authors
recommendedPersistent workers are worth adding only when the rule and the underlying tool can uphold a stronger contract than a normal one-shot action. Bazel can keep a worker process alive and send it many requests, but the rule author must define what stays stable at process startup, what varies per action, how Bazel talks to the process, and how correctness is preserved when state survives between requests.1 This builds on the execution-strategy vocabulary from 2.5 Execution Strategies. This article focuses on the rule-author surface, while pool sizing and performance operations continue in 6.5 Execution Strategies.
Start with the Tool, Not the Flag
A worker is either the tool itself or a wrapper around the tool. It must accept --persistent_worker, then read WorkRequest messages from stdin and write WorkResponse messages to stdout. When the flag is absent, it should still be able to run as a normal one-shot tool.2 That fallback matters because Bazel may invoke the same executable with and without worker mode in one build, depending on strategy selection and action support.3
Good worker candidates have repeated actions with high startup cost or useful cross-action caches: compilers, transpilers, code generators, and analysis tools. The official docs call out startup overhead, JIT warmup, and cached ASTs as the common wins.4 In practical terms, workers help when the compiler is architected to reset and reuse state safely. They are not a magic adapter for arbitrary command-line tools.5
The strongest design question is therefore: can the tool behave as if every request were isolated? If the tool leaves global state behind, uses process-wide temp files, or writes diagnostics to the wrong stream, worker mode can turn a harmless one-shot bug into a sequence-dependent build failure.6
Worker support belongs to actions that a rule registers with ctx.actions.run. A test rule cannot use it for the test run itself: the test API expects a flagless executable that Bazel runs with the Test Encyclopedia environment and judges by exit code. EngFlow describes a proposed PersistentTestInfo provider that would join the two APIs. It exists only in prototype forks of Bazel and rules_java, marked as not for production. On 46 of Bazel's own Java test targets, EngFlow reports the sum of median runtimes falling from 36.5 to 19.6 minutes, while 11 short tests got slower.7 An earlier java_test-only persistent test runner was removed in 2022. It mishandled classpath changes during incremental builds, so stale classes and leaked state corrupted test runs. That is the same correctness boundary this article asks every worker to prove.7
The Rule-Side Contract
The Starlark rule must expose a stable executable, usually through a private executable attr in the execution configuration, so the worker runs on the execution platform rather than the target platform.8 It must also register actions with a stable mnemonic, because users route worker strategy by mnemonic:
_my_rule = rule(
implementation = _impl,
attrs = {
"_worker": attr.label(
default = Label("//tools/my_compiler:worker"),
executable = True,
cfg = "exec",
),
},
)
The action must declare worker support through execution_requirements. supports-workers opts the action into the worker strategy, while requires-worker-protocol selects JSON or protobuf. Protobuf is the default when the protocol key is omitted.9 That protocol selection is part of the action's execution contract, and it can travel beyond the local machine. With remote persistent workers enabled through the experimental --experimental_remote_mark_tool_inputs flag, Bazel sends a worker-capable action's worker key as the persistentWorkerKey platform property. Bazel 10 also forwards requires-worker-protocol as the persistentWorkerProtocol platform property, so one remote backend can serve JSON and protobuf workers in the same build. Bazel 9.x sends only the key.10,11,12
args_file = ctx.actions.declare_file(ctx.label.name + ".worker.args")
ctx.actions.write(
output = args_file,
content = "\n".join(per_request_args),
)
ctx.actions.run(
executable = ctx.executable._worker,
inputs = depset(direct = [args_file], transitive = [src_inputs]),
outputs = [out],
arguments = [
"--max_mem=4G", # startup argument
"@%s" % args_file.path, # per-request arguments
],
mnemonic = "MyCompiler",
execution_requirements = {
"supports-workers": "1",
"requires-worker-protocol": "proto",
},
)
The arguments list has two roles. Everything before the final @flagfile is a startup argument for the worker process. The flagfile content becomes the per-request argument list in each WorkRequest.13 Keep startup arguments low-cardinality: Bazel includes the mnemonic and startup flags in the worker key, so letting every target choose different startup options can multiply live worker processes and memory use.14
The Protocol Is Part of the API
A WorkRequest carries request arguments, input path/digest pairs, and a request id. A WorkResponse carries the same request id, an exit code, and an output message.15 For singleplex workers, the request id is 0. Multiplex workers use nonzero ids to match concurrent responses to requests.16
stdout is reserved for protocol messages. If the worker or a wrapped compiler writes ordinary diagnostics there, Bazel can no longer reliably parse responses. Capture tool output and put user-facing text in the WorkResponse.output field. Use the worker process stderr only for worker logs, knowing that those logs are attached to the worker process rather than one specific action.17
JSON and protobuf carry the same logical fields, but JSON uses camelCase names such as requestId. Protobuf uses snake_case fields such as request_id. JSON workers must tolerate unknown fields and protobuf defaults.18 That detail sounds small until you maintain wrappers in multiple languages: even reading protobuf messages from an unbounded stdin stream requires library-level care around length-delimited messages.19
Correctness Before Warmth
Worker performance comes from keeping process state warm. Worker correctness comes from proving that warm state cannot change outputs for the wrong request. Bazel sends input digests in the request so the worker or wrapper can validate cached compiler state against the inputs Bazel knows about, but this is cooperative: it does not by itself prevent hidden in-memory state from leaking between requests.20
So before you ship a worker, list the state the tool keeps between requests and decide for each item whether the worker isolates it, discards it, or never creates it. Griffin's rules_clojure shows what that list looks like for a JVM compiler. Each compile request brings its own dependency jars. The worker hashes their contents, and when two requests need different files under the same name, it loads the conflicting request in a fresh class loader. The worker's own code lives in yet another loader, so it cannot clash with user jars. The worker also never takes the cheaper "require" path for a namespace and always compiles it, because it cannot predict which namespaces later requests will ask it to require and which to compile, and requiring a namespace and then compiling it can break code.21 The general techniques and their tests continue in 6.5.3 Isolating State Between Worker Requests.
Use --worker_sandboxing while developing and testing a worker-backed rule. It gives each request a sandboxed input view, which catches many undeclared input problems, but it is still weaker than a fresh one-shot sandbox because the process can retain internal state.22 A real GHC worker port surfaced test failures when the compiler had host-side access it should not have had. The practical fix was to always test worker mode with sandboxing enabled.23 In Bazel 9.x the flag is one global boolean. Bazel 10 also accepts --worker_sandboxing=<mnemonic>=<bool>, keyed by the worker-key mnemonic and repeatable, with later values winning. So --worker_sandboxing=MyCompiler=true can sandbox just the new worker in a mixed build.24
Cancellation is another correctness boundary. Workers can opt into cancellation with supports-worker-cancellation: 1 plus --experimental_worker_cancellation. Even when a request is cancelled, each non-cancel request must be answered exactly once, and after sending the response the worker must not touch files in its working directory because Bazel may clean them up.25
Multiplex Workers Raise the Bar
Multiplex workers are a different promise, not just a faster checkbox. A multiplex worker lets one process handle several concurrent requests, which can reduce memory pressure and share one cache across requests for tools such as Java or Scala compilers.26 To opt in, the action declares supports-multiplex-workers. This takes precedence over supports-workers when both are present.27
The worker implementation then has to become thread-safe. It must preserve request_id, write responses atomically so messages do not interleave, and handle user-visible output without mixing text from parallel requests.28 If multiplex sandboxing is needed, the worker must read sandbox_dir from each WorkRequest, translate all input and output paths through that directory, and declare supports-multiplex-sandboxing on the action. Bazel still needs --experimental_worker_multiplex_sandboxing or a dynamic-execution path that requires multiplex sandboxing before that support is used.29
Treat multiplexing as an extra capability after the singleplex contract is proven. A non-thread-safe worker with shared temp files, global compiler state, or output written straight to stderr is not ready for multiplex mode.30 Thread safety also reaches into the tool's own runtime. The rules_clojure worker compiles a namespace's dependencies on parallel threads. It found that Clojure marks a namespace as loaded before the rest of its file has run, so another thread could call a function that was not defined yet, and that namespace cycles in real libraries deadlocked its wait-for-dependencies logic until it added cycle detection at load time.21
The runnable mini-ruleset connects both halves of the contract: the worker-backed action and its persistent worker adapter.
The adapter's protocol binding also illustrates the distribution boundary from 4.11.2 Toolchainization. The published worker uses checked-in official protoc output and a release runtime wheel. A maintainer-only target regenerates it with Protobuf 34's official prebuilt compiler. The fail-closed check rejects Protobuf C++ actions before regeneration. This packaging choice is independent of whether GlyphCompile executes one-shot or as a persistent worker.31
Worker support is a public execution contract: stable mnemonic, executable in exec config, flagfile-shaped requests, explicit execution_requirements, a protocol-clean worker process, and tests that prove state does not leak between requests. Add it when startup or cross-action cache reuse is real. Keep one-shot execution working so users can still fall back when worker mode is wrong for a build.
Check your understanding · 3 questions
1.What must be true before a custom rule should advertise worker support?
Select one answer
2.Which action-side details are part of the persistent-worker contract?
Select all that apply
3.True or false: worker protocol and sandboxing behavior.
Choose True or False for each sentence
supports-multiplex-sandboxing alone guarantees multiplex sandboxing is active.requires-worker-protocol stays invisible to remote execution even when remote persistent workers are enabled.Footnotes
-
Creating Persistent Workers — worker implementation has two parts: the worker process and the rule that uses it. ↩
-
Creating Persistent Workers — worker requirements:
--persistent_worker,WorkRequeston stdin,WorkResponseon stdout. ↩ -
Persistent Workers — the same worker may be called with and without
--persistent_workerin one build. ↩ -
Persistent Workers — execution-strategy benefits: startup overhead, JIT compilation, and cached ASTs. ↩
-
How to Create a Persistent Worker for Bazel — compiler architecture and safe reset requirements for worker suitability. ↩
-
Bazel persistent workers — sandboxing and long-lived-process risks: in-memory state, shared temp areas, and cleanup assumptions. ↩
-
Persistent Test Runners: How Persistent Workers for Tests Can Cut Test Times by 46% — Existing Bazel APIs, The new PersistentTestInfo API, Results, and We've been here before. EngFlow's own experimental prototype. ↩1 ↩2
-
Creating Persistent Workers — worker attr uses
executable = Trueandcfg = "exec". ↩ -
Creating Persistent Workers —
supports-workers,supports-multiplex-workers, andrequires-worker-protocolaction requirements. ↩ -
Persistent Workers —
requires-worker-protocolalso forwards the selected protocol to remote execution via thepersistentWorkerProtocolplatform property. ↩ -
Bazel 10.0.0rc1 release notes — the
requires-worker-protocolexecution requirement is forwarded to remote execution as thepersistentWorkerProtocolplatform property, to support mixing JSON and proto remote persistent workers in one build. ↩ -
Bazel — core implementation, documentation, and regression corpus — Bazel adds worker platform properties only when
--experimental_remote_mark_tool_inputsis set and the action supports workers and has tool inputs. 9.3.1 sends onlypersistentWorkerKey. 10.0.0rc2 also sendspersistentWorkerProtocol. ↩ -
Creating Persistent Workers — startup arguments precede the final
@flagfile, whose contents become per-request arguments. ↩ -
Persistent Workers — WorkerKey composition from mnemonic and startup flags, with memory implications. ↩
-
Creating Persistent Workers —
WorkRequestandWorkResponsefield shape. ↩ -
Creating Persistent Workers —
request_id0 for singleplex and nonzero ids for multiplex requests. ↩ -
Creating Persistent Workers — stdout safety and response output vs worker stderr logs. ↩
-
Creating Persistent Workers — JSON/protobuf naming and compatibility notes. ↩
-
Bazel's Persistent Worker Mode for GHC: An Industrial Internship — protobuf streaming and stdin/stdout integration challenges in the GHC worker. ↩
-
Persistent Workers — input digests for worker cache validation and cooperative correctness. ↩
-
Compiling Clojure in Parallel using Bazel - Allen Rohner (Clojure/Conj 2026) — Conflicting Classpaths (per-request jar hashing and class loaders), Class Hell (the worker never requires), loaded? Is Not Transactional, and Cycles. ↩1 ↩2
-
Persistent Workers —
--worker_sandboxingbehavior and limits versus pure sandboxing. ↩ -
Bazel's Persistent Worker Mode for GHC: An Industrial Internship — rules_haskell worker tests and the need for
--worker_sandboxing. ↩ -
Bazel 10.0.0rc1 release notes —
--worker_sandboxingcan be set per worker-key mnemonic with--worker_sandboxing=<mnemonic>=<boolean>. In 9.3.1 it is a plain boolean. ↩ -
Creating Persistent Workers — cancellation protocol and post-response file access rule. ↩
-
Multiplex Workers (Experimental Feature) — multiplex workers share one process and cache across parallel requests. ↩
-
Multiplex Workers (Experimental Feature) —
supports-multiplex-workersenablement and precedence. ↩ -
Multiplex Workers (Experimental Feature) — thread-safe request handling, atomic responses, and output handling. ↩
-
Multiplex Workers (Experimental Feature) —
sandbox_dirandsupports-multiplex-sandboxingcontract. ↩ -
Bazel persistent workers — multiplex complexity around thread safety, shared temp files, and output directories. ↩
-
Pre-built protoc binaries for Bazel — Protobuf 34 defaults to the official prebuilt compiler after Protobuf 33.4 introduced the opt-in toolchain. ↩