The user wants a design for a "polyglot monorepo build" with specific constraints/features:
- Polyglot: Must handle multiple languages (e.g., Java, Go, Python, C++).
- Monorepo: Single repository containing multiple projects/libraries.
- Hermetic Toolchains: Builds must use declared, isolated tools, not system-wide tools.
- Remote Cache: Must support caching build artifacts remotely to speed up CI and local builds.
- Reproducible Outputs: Building the same source code must yield bit-for-bit identical results.
This is a system design/architecture question. I need to provide a comprehensive design document covering the technology stack, the architecture, the workflow, and specific implementation details for each requirement.
1. Technology Selection:
-
Options: Make/CMak (not polyglot enough/hermetic by default), Gradle/Maven (Java focused), npm/yarn (JS focused).
-
Real contenders for hermetic, polyglot monorepos:
- Bazel: The gold standard for this specific set of requirements. Built by Google. Handles polyglot, hermeticity, and remote execution/caching natively.
- Buck2: Facebook's successor to Buck. Rust-based, very fast,Starlark configuration. Good alternative.
- Pants: Python-focused but supports others. Good, but Bazel is more broadly "enterprise standard" for strict hermeticity.
- Nx: JS/TS focused, polyglot support exists but less strict on hermeticity compared to Bazel.
-
Decision: I will base the design on Bazel (or a Bazel-like architecture) because it is the most direct mapping to the user's requirements (Hermetic, Remote Cache, Reproducible).
2. Architecture Design:
- Directory Structure: Need a standard layout (e.g.,
WORKSPACE, .bazelrc, tools/, packages/).
- Hermeticity: Explain how to achieve this.
- Rules:
rules_java, rules_go, rules_python.
- Toolchains:
rules_go downloads the Go SDK, rules_java uses a specific JDK.
- Containerization: Using Docker/Podman or RBE (Remote Build Execution) to ensure the OS environment is also consistent.
- Remote Caching:
- Protocol: gRPC/REST (bytestream).
- Tools: Buildbarn, BuildGrid, or cloud providers (GCP RBE, AWS S3).
- Auth: mTLS or Tokens.
- Reproducibility:
- Sandboxing: Prevent access to non-declared inputs.
- Determinism flags:
--stamp=false (usually), sorting file orders, fixing timestamps (Zip files).
- Pinning dependencies:
go.mod, maven_install, requirements.txt.
3. Structuring the Response:
I should structure this as a "Design Specification" or "Architecture Blueprint".
- Title: Polyglot Monorepo Build System Architecture.
- Executive Summary: Why Bazel (or Bazel-like)? Speed, correctness, scale.
- 1. Repository Structure: The physical layout.
- 2. Hermetic Toolchains: How to isolate the environment.
- Workspaces vs. Bzlmod.
- Toolchain resolution.
- 3. Dependency Management: Lock files and vendoring.
- 4. Remote Cache & Execution: The scaling layer.
- Architecture diagram description.
- CAS (Content Addressable Storage).
- 5. Reproducibility Strategy: Ensuring correctness.
- Sandboxing.
- Timestamp handling.
- 6. CI/CD Integration: How this plugs into GitHub Actions/Jenkins.
4. Drafting the Content (Iterative Refinement):
- Polyglot aspect: I need to show examples. Let's say the repo has a Go backend, a TS frontend, and Python data pipelines.
- Hermeticity: Emphasize
rules_docker or rules_oci for the build environment if strict OS isolation is needed, but mostly emphasize that Bazel downloads the compilers.
- Remote Cache: Explain the concept of the Action Cache and CAS.
- Reproducibility: Mention "Sandboxing" on macOS/Linux.
5. Specific Technical Details (The "Secret Sauce"):
- Bzlmod: Bazel is moving to Bzlmod (MODULE.bazel). I should recommend that over the legacy
WORKSPACE file where possible, or at least acknowledge it.
- Platforms: How to handle building for Linux x86_64 vs ARM.
- Remote Execution (RBE) vs just Cache: The user asked for cache, but RBE is often implied in these setups for speed. I'll focus on Cache but mention RBE as an upgrade path.
6. Code Examples:
- I need to provide snippets of configuration files to make it concrete.
MODULE.bazel (or WORKSPACE).
BUILD.bazel files for different languages.
.bazelrc configuration for the remote cache.
7. Review against constraints:
- Polyglot? Yes, Go/Python/Java examples.
- Monorepo? Yes, structure supports it.
- Hermetic? Yes, toolchain rules.
- Remote Cache? Yes, gRPC setup.
- Reproducible? Yes, sandboxing flags.
Self-Correction during drafting:
Initially, I might just say "use Docker". But Bazel isn't Docker-native inside the build unless you use specific rules or RBE. I should clarify that Hermetic Toolchains usually means downloading the compiler into the Bazel output base, not necessarily running every compile action in a Docker container (though that's possible and better for strict reproducibility). I will stick to the "downloaded toolchains" approach as it's faster, but mention RBE/Docker for OS-level hermeticity.
Refining the "Reproducibility" section:
I need to mention timestamp normalization. Bazel does this for its own outputs, but for things like Docker containers or Zip files, you need specific flags or tools (e.g., zip -X).
Final Polish:
Organize with clear headings. Use bold text for key terms. Add a "Getting Started" or "Implementation Roadmap" to make it actionable.
(Self-Correction on Tool Selection): While Buck2 is great, Bazel has the most mature ecosystem for remote caching and polyglot rules currently available publicly. I will frame the solution around Bazel but mention that the architectural concepts apply to Buck2/Pants as well.
Plan:
- High-Level Architecture: The "Why" and "What" (Bazel).
- Filesystem Layout: Visualizing the monorepo.
- Hermeticity Mechanism: Managing tools via Starlark rules.
- Remote Cache Setup: gRPC, CAS, Action Cache.
- Reproducibility Techniques: Sandboxing & Determinism.
- CI/CD Workflow: The developer loop.
- Example Code: Concrete snippets.
Let's write it out.
This design specifies a build system architecture optimized for a polyglot monorepo. The industry-standard approach for meeting strict requirements around hermeticity, remote caching, and reproducibility is to adopt Bazel (or a Bazel-compatible architecture).
This design uses Bazel as the orchestration layer, gRPC for remote execution protocols, and Content-Addressable Storage (CAS) for artifact persistence.
1. High-Level Architecture
The system consists of three logical planes: Source, Orchestration, and Execution.
- Source Plane: A single Git repository containing all source code, build definitions, and locked dependencies.
- Orchestration Plane (Bazel): Analyzes the build graph, determines dependencies, and schedules tasks.
- Execution Plane: Hermetic containers (runners) that execute compile/link steps. They communicate with the Orchestration Plane via the Remote Execution API (REAPI).
- Storage Plane: A high-performance Remote Cache (e.g., Buildbarn, EngFlow, or Google RBE) storing outputs keyed by content hash.
2. Repository Structure (The Layout)
To support polyglot development, the repo is structured to separate infrastructure code (tools/) from application code (services/).
monorepo/
├── MODULE.bazel # Modern dependency declaration (Bzlmod)
├── .bazelrc # Config for remote cache, platforms, hermeticity
├── tools/
│ └── toolchains/ # Custom toolchain definitions
│ ├── go/
│ ├── nodejs/
│ └── cpp/
├── libs/ # Shared libraries
│ ├── auth/
│ └── logging/
└── services/ # Deployable artifacts
├── frontend/
└── api/
3. Hermetic Toolchains (Design)
Hermeticity ensures that builds are independent of the machine they run on. We achieve this by declaring toolchains explicitly and isolating the environment.
A. Toolchain Resolution
Instead of relying on /usr/bin/node or /usr/local/go, Bazel resolves toolchains via constraints.
Example: Defining a Node.js Toolchain
# tools/toolchains/nodejs/BUILD
load("@rules_nodejs//nodejs:toolchain.bzl", "nodejs_toolchain")
nodejs_toolchain(
name = "nodejs_linux_amd64",
node = "@nodejs_linux_amd64//:bin/nodejs", # Downloaded binary
npm = "@nodejs_linux_amd64//:bin/npm",
target_tool = "@nodejs_linux_amd64//:bin/node",
)
B. Environment Isolation
To ensure the build sees only what we declare, we utilize "Sandboxing".
- Linux: Uses
namespace(7) or seccomp(2) to restrict network access and filesystem visibility.
- macOS: Uses
sandbox-exec.
- Docker: Bazel runs actions inside a strictly defined container image (distroless) if remote execution is used.
Configuration (.bazelrc):
# Enforce hermeticity
build --experimental_sandbox_base=/tmp/bazel_sandbox
build --experimental_use_hermetic_linux_sandbox
build --reuse_sandbox_directories
4. Remote Cache & Execution (Design)
This architecture relies on the Remote Execution API (REAPI).
A. Content Addressable Storage (CAS)
Inputs (source files, toolchain binaries) and Outputs (object files, binaries) are addressed by their SHA-256 hash.
- Deduplication: If
lib/utils.js is unchanged, its hash is the same. The build server skips uploading it.
- Cache Hits: If a build request (Action) + Inputs Hash matches an existing entry in the Remote Cache, the build downloads the output instead of compiling.
B. The Build Flow
- Analysis: Client analyzes the graph locally.
- Check Cache: Client asks Remote Cache: "Do you have output for Hash
XYZ?"
- Execution (Miss): If No, Client uploads inputs to CAS. The Remote Execution worker downloads inputs, runs the compile command inside a hermetic container, uploads outputs to CAS, and returns the result.
- Download: Client downloads the final binary.
Configuration for Remote Cache:
# .bazelrc
build --remote_cache=grpcs://cache.build.company.com:443
build --remote_executor=grpcs://executor.build.company.com:443
build --tls_enabled=true
# Auth
build --remote_default_exec_properties=cache-silo-key=prod-repo
5. Reproducible Outputs (Design)
Reproducibility means byte-for-byte identical outputs given the same inputs.
A. Timestamp Normalization
Compilers often embed the current time into binaries. We force all toolchains to respect the SOURCE_DATE_EPOCH standard or use specific flags.
- C++:
-Wno-builtin-macro-redefined -D__DATE__= -D__TIME__=
- Go:
-trimpath
- Zip/jar: Stripping metadata timestamps.
B. Filesystem Ordering
Filesystem iteration order is non-deterministic (depends on underlying FS). We sort inputs alphabetically in build rules before passing them to tools.
C. Deterministic Randomness
Any build step requiring random numbers (e.g., ID generation) is seeded with a hash of the input file content.
6. Polyglot Example: Go Service + JS Frontend
Here is how the build graph connects a Go backend and a TypeScript frontend within this architecture.
services/api/BUILD (Go)
load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
go_library(
name = "api_lib",
srcs = ["main.go", "handler.go"],
deps = ["//libs/auth"], # Internal monorepo dep
importpath = "company.com/monorepo/services/api",
# Enforces hermeticity: strips GOPATH from binary
gc_linkopts = ["-s", "-w"],
)
go_binary(
name = "api_bin",
embed = [":api_lib"],
visibility = ["//visibility:public"],
)
services/frontend/BUILD (TypeScript)
load("@aspect_rules_js//js:defs.bzl", "js_binary")
js_binary(
name = "frontend_bin",
data = [
"src/index.ts",
"//libs/ui-components", # Shared internal UI lib
],
entry_point = "src/index.ts",
# Link against the hermetic NodeJS toolchain defined in /tools
)
7. Implementation Roadmap
To implement this design:
- Phase 1: Bazelification
- Install Bazel.
- Convert one language (e.g., Go or Python) to build using
rules_go or rules_python.
- Ensure
bazel build //... passes locally.
- Phase 2: Hermeticity
- Configure toolchains in
tools/toolchains.
- Ensure
bazel build //... works inside a Docker container with no pre-installed tools (verifying hermeticity).
- Phase 3: Remote Cache
- Deploy a cache service (e.g., Buildbarn or EngFlow).
- Point
.bazelrc to the cache. Verify cache hits on CI.
- Phase 4: Remote Execution (RBE)
- Set up a worker pool (Kubernetes cluster).
- Migrate heavy compile tasks (C++, Java, Linking) to run remotely.
Summary of Capabilities
| Feature | Implementation Mechanism |
|---|
| Polyglot | Bazel build graph + Language-specific rulesets (rules_...). |
| Hermetic | Custom Toolchain definitions + Linux Namespaces/Sandboxing. |
| Remote Cache | gRPC endpoint (REAPI) + Content Addressable Storage (CAS). |
| Reproducible | SOURCE_DATE_EPOCH, -trimpath, Sorted inputs, Pinned deps (lockfiles). |