Building a Monorepo Remote Cache with Hermetic Toolchains and Sandboxing
I'll guide you through building a production-ready monorepo remote cache setup using Bazel as the core build system. Bazel natively supports:
Monorepos : Scales to millions of files with fine-grained dependency graphs.
Remote Caching : Share build artifacts across developers/CI via HTTP/GRPC.
Hermetic Toolchains : Tools (compilers, etc.) are downloaded/isolated in the Bazel cache—no host dependencies.
Sandboxing : Builds run in isolated environments (Linux namespaces, symlinks only to inputs).
This setup uses:
Bazel (v7.0+) for builds.
bazel-remote for a self-hosted remote cache (simple, scalable, supports AC + cas + action cache).
Docker for hermetic toolchain containerization (optional but recommended for cross-platform).
Nix (optional) for ultra-hermetic host setup.
Assumptions :
Linux host (Ubuntu 22.04+; sandboxing works best here).
Monorepo root: ~/monorepo.
100GB+ SSD for cache.
Step 1: Set Up Bazel Monorepo Basics
Install Bazel (hermetically via Bazelisk):
bash Copy code
curl -LO "https://github.com/bazelbuild/bazelisk/releases/latest/download/bazelisk-linux-amd64"
mkdir -p ~/bin && chmod +x bazelisk-linux-amd64 && mv bazelisk-linux-amd64 ~/bin/bazel
export PATH=~/bin:$PATH
bazel version # Should be latest (7.x)
Bootstrap Monorepo :
bash Copy code
mkdir ~/monorepo && cd ~/monorepo
git init
# Add your WORKSPACE.bazel (or MODULE.bazel for Bzlmod)
cat > WORKSPACE.bazel << EOF
# Minimal monorepo WORKSPACE
workspace(name = "monorepo")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
# Hermetic C++ toolchain example
http_archive(
name = "rules_cc",
urls = ["https://github.com/bazelbuild/rules_cc/releases/download/0.0.9/rules_cc-0.0.9.tar.gz"],
)
EOF
Enable Sandboxing (default on Linux; verify):
Add to ~/.bazelrc:
code Copy code
build --sandbox_debug
build --sandbox_add_mount_pair=/etc/localtime,/etc/localtime # For timestamps
test --test_output=errors # Faster with sandbox
Step 2: Hermetic Toolchains
Bazel toolchains are hermetic by default (fetched to ~/.cache/bazel). For full isolation:
Declare Toolchain in WORKSPACE.bazel (add):
python Copy code
# Hermetic Clang (fetches ~500MB)
http_archive(
name = "hedron_compile_commands",
url = "https://github.com/hedronvision/bazel-compile-commands-extractor/releases/download/v20230605-2/hedron_compile_commands_extractor-v20230605-2.tar.gz",
)
# Use rules_docker for containerized toolchains (ultra-hermetic)
http_archive(
name = "io_bazel_rules_docker",
sha256 = "b1e80761a8a8243d03ebca8845e9cc1ba6c82da60c95731cb9bd7a97b32266d4",
strip_prefix = "rules_docker-1.10.1",
url = "https://github.com/bazelbuild/rules_docker/releases/download/v1.10.1/rules_docker-v1.10.1.tar.gz",
)
Example BUILD.bazel (in //examples/cc):
python Copy code
cc_binary(
name = "hello",
srcs = ["hello.cc"],
deps = ["@rules_cc//cc:cc_toolchain"], # Hermetic CC
)
Configure in .bazelrc :
code Copy code
build --crosstool_top=@bazel_tools//tools/cpp:toolchain # Or custom hermetic
build --action_env=BAZEL_CC=/usr/bin/clang # Pin compiler
Test Hermeticity :
bash Copy code
mkdir -p examples/cc && echo 'int main(){return 0;}' > examples/cc/hello.cc
bazel build //examples/cc:hello --sandbox_debug
# Inspect sandbox: strace shows only input symlinks.
Pro Tip : For Go/Java/Python/Rust, use rules_go, rules_java, etc.—all hermetic.
Step 3: Build Remote Cache Server
Use bazel-remote (Go-based, supports CAS + AC + RE; 1GB RAM, scales to TBs).
Run Cache Server (Docker for hermeticity):
bash Copy code
docker run --name remote-cache \
-p 8080:8080 \
-v cache-volume:/data \
-e STORAGE_BASE_DIR=/data \
gcr.io/bazel-public/bazel-remote:v2.1.3 \
--backend=single_file \
--singleflight=true \
--max_bytes=10737418240 # 10GB limit
Volumes: docker volume create cache-volume.
Expose via nginx/TLS for prod.
Configure Bazel Client (add to ~/.bazelrc):
code Copy code
build --remote_cache=http://localhost:8080
build --remote_executor=http://localhost:8080 # Optional RE
build --remote_instance_name=monorepo
build --remote_upload_local_results=true
build --remote_verify_downloads=true # Integrity
build --keep_going # Robust
Test Remote Cache :
bash Copy code
bazel clean --expunge
time bazel build //examples/cc:hello # First: ~10s fetch+build
bazel clean --expunge
time bazel build //examples/cc:hello # Second: ~0.1s cache hit!
Cache Hits : 90%+ on CI/teams. Monitor: curl http://localhost:8080/metrics.
Step 4: Production Enhancements
Feature Setup Scaling Cluster with Redis backend: --backend=redis://redis:6379/0. Use Kubernetes. Auth --tls_ca_file=/path/ca.pem --tls_client_key --tls_client_cert.S3 Fallback --backend=s3://my-bucket/cache?region=us-east-1&endpoint=....CI Integration GitHub Actions/CircleCI: Use bazelisk + above rc. Nix Hermetic Host nix-shell -p bazel_7 docker for zero-OS deps.Monitoring Prometheus: Scrape /metrics. Grafana dashboard for hit rates.
Dockerfile for Prod Cache :
dockerfile Copy code
FROM gcr.io/bazel-public/bazel-remote:v2.1.3
COPY config.yaml /etc/bazel-remote/
CMD ["--config_file=/etc/bazel-remote/config.yaml"]
Step 5: Validation & Best Practices
Reproducibility : bazel build --nobuild --check_up_to_date.
Hermetic Check : --strict_action_env.
Sandbox Escape Test : Try cc_binary writing /tmp/evil; fails.
Monorepo Scale : Use bazel sync --configure for 1M+ files.
Cleanup : bazel clean --async + cron on cache server.
Full Test Script :
bash Copy code
#!/bin/bash
cd ~/monorepo
bazel build //examples/cc:hello --remote_cache=http://localhost:8080
echo "✅ Setup complete! Cache hit rate will skyrocket."
This gives you a fully hermetic, sandboxed, remotely cached monorepo in <30min. Ping for custom langs (e.g., Node/WebAssembly) or troubleshooting! 🕵️♂️