Optimize Bazel builds for large-scale monorepos. Use when configuring Bazel, implementing remote execution, or optimizing build performance for enterprise codebases.
Add this skill
npx mdskills install sickn33/bazel-build-optimizationComprehensive Bazel guide with production-ready templates, optimization patterns, and clear examples
1---2name: bazel-build-optimization3description: Optimize Bazel builds for large-scale monorepos. Use when configuring Bazel, implementing remote execution, or optimizing build performance for enterprise codebases.4---56# Bazel Build Optimization78Production patterns for Bazel in large-scale monorepos.910## Do not use this skill when1112- The task is unrelated to bazel build optimization13- You need a different domain or tool outside this scope1415## Instructions1617- Clarify goals, constraints, and required inputs.18- Apply relevant best practices and validate outcomes.19- Provide actionable steps and verification.20- If detailed examples are required, open `resources/implementation-playbook.md`.2122## Use this skill when2324- Setting up Bazel for monorepos25- Configuring remote caching/execution26- Optimizing build times27- Writing custom Bazel rules28- Debugging build issues29- Migrating to Bazel3031## Core Concepts3233### 1. Bazel Architecture3435```36workspace/37├── WORKSPACE.bazel # External dependencies38├── .bazelrc # Build configurations39├── .bazelversion # Bazel version40├── BUILD.bazel # Root build file41├── apps/42│ └── web/43│ └── BUILD.bazel44├── libs/45│ └── utils/46│ └── BUILD.bazel47└── tools/48 └── bazel/49 └── rules/50```5152### 2. Key Concepts5354| Concept | Description |55|---------|-------------|56| **Target** | Buildable unit (library, binary, test) |57| **Package** | Directory with BUILD file |58| **Label** | Target identifier `//path/to:target` |59| **Rule** | Defines how to build a target |60| **Aspect** | Cross-cutting build behavior |6162## Templates6364### Template 1: WORKSPACE Configuration6566```python67# WORKSPACE.bazel68workspace(name = "myproject")6970load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")7172# Rules for JavaScript/TypeScript73http_archive(74 name = "aspect_rules_js",75 sha256 = "...",76 strip_prefix = "rules_js-1.34.0",77 url = "https://github.com/aspect-build/rules_js/releases/download/v1.34.0/rules_js-v1.34.0.tar.gz",78)7980load("@aspect_rules_js//js:repositories.bzl", "rules_js_dependencies")81rules_js_dependencies()8283load("@rules_nodejs//nodejs:repositories.bzl", "nodejs_register_toolchains")84nodejs_register_toolchains(85 name = "nodejs",86 node_version = "20.9.0",87)8889load("@aspect_rules_js//npm:repositories.bzl", "npm_translate_lock")90npm_translate_lock(91 name = "npm",92 pnpm_lock = "//:pnpm-lock.yaml",93 verify_node_modules_ignored = "//:.bazelignore",94)9596load("@npm//:repositories.bzl", "npm_repositories")97npm_repositories()9899# Rules for Python100http_archive(101 name = "rules_python",102 sha256 = "...",103 strip_prefix = "rules_python-0.27.0",104 url = "https://github.com/bazelbuild/rules_python/releases/download/0.27.0/rules_python-0.27.0.tar.gz",105)106107load("@rules_python//python:repositories.bzl", "py_repositories")108py_repositories()109```110111### Template 2: .bazelrc Configuration112113```bash114# .bazelrc115116# Build settings117build --enable_platform_specific_config118build --incompatible_enable_cc_toolchain_resolution119build --experimental_strict_conflict_checks120121# Performance122build --jobs=auto123build --local_cpu_resources=HOST_CPUS*.75124build --local_ram_resources=HOST_RAM*.75125126# Caching127build --disk_cache=~/.cache/bazel-disk128build --repository_cache=~/.cache/bazel-repo129130# Remote caching (optional)131build:remote-cache --remote_cache=grpcs://cache.example.com132build:remote-cache --remote_upload_local_results=true133build:remote-cache --remote_timeout=3600134135# Remote execution (optional)136build:remote-exec --remote_executor=grpcs://remote.example.com137build:remote-exec --remote_instance_name=projects/myproject/instances/default138build:remote-exec --jobs=500139140# Platform configurations141build:linux --platforms=//platforms:linux_x86_64142build:macos --platforms=//platforms:macos_arm64143144# CI configuration145build:ci --config=remote-cache146build:ci --build_metadata=ROLE=CI147build:ci --bes_results_url=https://results.example.com/invocation/148build:ci --bes_backend=grpcs://bes.example.com149150# Test settings151test --test_output=errors152test --test_summary=detailed153154# Coverage155coverage --combined_report=lcov156coverage --instrumentation_filter="//..."157158# Convenience aliases159build:opt --compilation_mode=opt160build:dbg --compilation_mode=dbg161162# Import user settings163try-import %workspace%/user.bazelrc164```165166### Template 3: TypeScript Library BUILD167168```python169# libs/utils/BUILD.bazel170load("@aspect_rules_ts//ts:defs.bzl", "ts_project")171load("@aspect_rules_js//js:defs.bzl", "js_library")172load("@npm//:defs.bzl", "npm_link_all_packages")173174npm_link_all_packages(name = "node_modules")175176ts_project(177 name = "utils_ts",178 srcs = glob(["src/**/*.ts"]),179 declaration = True,180 source_map = True,181 tsconfig = "//:tsconfig.json",182 deps = [183 ":node_modules/@types/node",184 ],185)186187js_library(188 name = "utils",189 srcs = [":utils_ts"],190 visibility = ["//visibility:public"],191)192193# Tests194load("@aspect_rules_jest//jest:defs.bzl", "jest_test")195196jest_test(197 name = "utils_test",198 config = "//:jest.config.js",199 data = [200 ":utils",201 "//:node_modules/jest",202 ],203 node_modules = "//:node_modules",204)205```206207### Template 4: Python Library BUILD208209```python210# libs/ml/BUILD.bazel211load("@rules_python//python:defs.bzl", "py_library", "py_test", "py_binary")212load("@pip//:requirements.bzl", "requirement")213214py_library(215 name = "ml",216 srcs = glob(["src/**/*.py"]),217 deps = [218 requirement("numpy"),219 requirement("pandas"),220 requirement("scikit-learn"),221 "//libs/utils:utils_py",222 ],223 visibility = ["//visibility:public"],224)225226py_test(227 name = "ml_test",228 srcs = glob(["tests/**/*.py"]),229 deps = [230 ":ml",231 requirement("pytest"),232 ],233 size = "medium",234 timeout = "moderate",235)236237py_binary(238 name = "train",239 srcs = ["train.py"],240 deps = [":ml"],241 data = ["//data:training_data"],242)243```244245### Template 5: Custom Rule for Docker246247```python248# tools/bazel/rules/docker.bzl249def _docker_image_impl(ctx):250 dockerfile = ctx.file.dockerfile251 base_image = ctx.attr.base_image252 layers = ctx.files.layers253254 # Build the image255 output = ctx.actions.declare_file(ctx.attr.name + ".tar")256257 args = ctx.actions.args()258 args.add("--dockerfile", dockerfile)259 args.add("--output", output)260 args.add("--base", base_image)261 args.add_all("--layer", layers)262263 ctx.actions.run(264 inputs = [dockerfile] + layers,265 outputs = [output],266 executable = ctx.executable._builder,267 arguments = [args],268 mnemonic = "DockerBuild",269 progress_message = "Building Docker image %s" % ctx.label,270 )271272 return [DefaultInfo(files = depset([output]))]273274docker_image = rule(275 implementation = _docker_image_impl,276 attrs = {277 "dockerfile": attr.label(278 allow_single_file = [".dockerfile", "Dockerfile"],279 mandatory = True,280 ),281 "base_image": attr.string(mandatory = True),282 "layers": attr.label_list(allow_files = True),283 "_builder": attr.label(284 default = "//tools/docker:builder",285 executable = True,286 cfg = "exec",287 ),288 },289)290```291292### Template 6: Query and Dependency Analysis293294```bash295# Find all dependencies of a target296bazel query "deps(//apps/web:web)"297298# Find reverse dependencies (what depends on this)299bazel query "rdeps(//..., //libs/utils:utils)"300301# Find all targets in a package302bazel query "//libs/..."303304# Find changed targets since commit305bazel query "rdeps(//..., set($(git diff --name-only HEAD~1 | sed 's/.*/"&"/' | tr '\n' ' ')))"306307# Generate dependency graph308bazel query "deps(//apps/web:web)" --output=graph | dot -Tpng > deps.png309310# Find all test targets311bazel query "kind('.*_test', //...)"312313# Find targets with specific tag314bazel query "attr(tags, 'integration', //...)"315316# Compute build graph size317bazel query "deps(//...)" --output=package | wc -l318```319320### Template 7: Remote Execution Setup321322```python323# platforms/BUILD.bazel324platform(325 name = "linux_x86_64",326 constraint_values = [327 "@platforms//os:linux",328 "@platforms//cpu:x86_64",329 ],330 exec_properties = {331 "container-image": "docker://gcr.io/myproject/bazel-worker:latest",332 "OSFamily": "Linux",333 },334)335336platform(337 name = "remote_linux",338 parents = [":linux_x86_64"],339 exec_properties = {340 "Pool": "default",341 "dockerNetwork": "standard",342 },343)344345# toolchains/BUILD.bazel346toolchain(347 name = "cc_toolchain_linux",348 exec_compatible_with = [349 "@platforms//os:linux",350 "@platforms//cpu:x86_64",351 ],352 target_compatible_with = [353 "@platforms//os:linux",354 "@platforms//cpu:x86_64",355 ],356 toolchain = "@remotejdk11_linux//:jdk",357 toolchain_type = "@bazel_tools//tools/jdk:runtime_toolchain_type",358)359```360361## Performance Optimization362363```bash364# Profile build365bazel build //... --profile=profile.json366bazel analyze-profile profile.json367368# Identify slow actions369bazel build //... --execution_log_json_file=exec_log.json370371# Memory profiling372bazel build //... --memory_profile=memory.json373374# Skip analysis cache375bazel build //... --notrack_incremental_state376```377378## Best Practices379380### Do's381- **Use fine-grained targets** - Better caching382- **Pin dependencies** - Reproducible builds383- **Enable remote caching** - Share build artifacts384- **Use visibility wisely** - Enforce architecture385- **Write BUILD files per directory** - Standard convention386387### Don'ts388- **Don't use glob for deps** - Explicit is better389- **Don't commit bazel-* dirs** - Add to .gitignore390- **Don't skip WORKSPACE setup** - Foundation of build391- **Don't ignore build warnings** - Technical debt392393## Resources394395- [Bazel Documentation](https://bazel.build/docs)396- [Bazel Remote Execution](https://bazel.build/docs/remote-execution)397- [rules_js](https://github.com/aspect-build/rules_js)398
Full transparency — inspect the skill content before installing.