Technical document

Design Principles for Simultaneously Reducing Execution Time and Cost in Large-Scale CI/CD

We organize the decision-making criteria for simultaneously improving CI/CD wait times and execution costs by combining Bazel's fine-grained targets, test impact analysis, ARM/Spot runners, priority queues, Fail-Fast, and Pre-warming.
CI/CD / Cost Optimization~18 minPublication Date September 22, 2026Update date November 23, 2026
Illustration of an engineer dividing a large CI process into fine-grained parallel tasks and distributing them to ARM, Spot, and cache resources.

Summary

Key points of this document

  • When CI is slow, separate execution time, wait time, and total computation.
  • Base on per-PR cost and P95 feedback time.
  • Divide Bazel targets according to the invalidation scope of changes.

Overview

When speeding up CI/CD, instead of immediately adding more high-performance runners, first reduce the work to be done, divide necessary work into smaller parts, prioritize their flow, and finally move to lower-cost computing resources. The key to simultaneously improving speed and cost is not the maximum parallelism, but managing the total CPU time and wait time from change to feedback.

When CI is slow, separate execution time, wait time, and total computation.

In large-scale CI/CD, simply shortening the pipeline's elapsed time does not necessarily reduce costs. Even if a 100-minute serial process can be done in 10 minutes with 10 machines, if the same amount of CPU time is spent on the same process, the total cost, including runner unit price and startup costs, may increase. Conversely, if the scope of execution can be halved, there is room to reduce both elapsed time and cost.

First, record the time spent waiting in the queue, preparing runners, fetching dependencies, executing builds and tests, and transferring artifacts. The feedback time perceived by developers is the sum of these, but improvement measures vary by segment. If you solve wait times with target splitting or force through unnecessary tests with high-performance VMs, only the cost remains.

The order of improvement is measurement, reduction of execution scope, task splitting, queue control, selection of execution infrastructure, and reduction of startup time. This order allows you to eliminate unnecessary work before increasing inexpensive computing resources.

Base on per-PR cost and P95 feedback time.

Average time alone cannot evaluate the developer experience during peak hours. Record P50 and P95 from PR creation to the completion of the first mandatory check, P95 for queue waiting, CPU minutes for success and failure, re-execution rate, and cache transfer volume. main and Nightly have different purposes, so they are not grouped into the same SLO.

Costs include not only VM uptime but also cache storage, artifact storage, network transfer, always-on warm pools, and re-executions after Spot interruptions. If transfer volume and re-executions increase after moving to cheaper VMs, both the bill and feedback time could worsen.

Before and after optimization, compare with the same change set and cache conditions. Do not use only warm cache numbers as improvement values; separate cold, incremental, peak hours, and Spot interruption scenarios. The goal is not the fastest single run, but consistently lowering the daily P95 and total cost per PR.

// Minimum metrics to track per PR
feedback_time = queue + provisioning + setup + build_test + upload

compute_cost = sum(vcpu_minutes * runner_unit_price)
total_cost = compute_cost + cache_storage + network + warm_pool + retry

track:
  p50_feedback, p95_feedback, p95_queue
  vcpu_minutes_per_pr, retry_rate, cache_hit_rate
  cache_download_bytes, spot_interruption_rate

Divide Bazel targets according to the invalidation scope of changes.

If many services, generation processes, and tests are gathered into one large target, even a small change will invalidate many actions that depend on its input. Since Bazel's parallel execution and caching work on an action-by-action basis, code and artifacts that change independently should be divided into small targets with explicit dependencies. Fine-grained dependencies create both parallelism and incremental builds.

However, creating a target for every single file is not always the best approach. If targets are too fine-grained, parsing the dependency graph, metadata, and numerous small communications with the remote cache increase. Set the boundaries of packages and targets where change frequency, reuse boundaries, and testing responsibilities align, and compare analysis time, number of actions, critical path, and cache hits before and after splitting.

If the runner calls targets one by one sequentially, the effect of splitting is lost. Select multiple necessary labels based on change impact, pass them to a single Bazel call, and let the dependency graph determine the execution order. On stable branches, regularly run a broad set of targets to detect any omissions in target selection for daily paths.

  • Splitting criteria: Separate where change frequency, reuse boundaries, artifacts, and testing responsibilities differ.
  • Designs to avoid: Many services depending on a large common target, invalidating the entire downstream with every change.
  • Evaluation metrics: Analysis time, number of executed actions, critical path, remote cache hit, transfer volume.
  • Execution method: Pass multiple necessary targets at once, do not serialize with an outer for loop.

Test impact analysis creates a fast path without discarding full tests.

In test impact analysis, we don't determine execution targets solely by changed file names. We trace reverse dependencies from the changed target to select affected builds and tests. Elements that are less likely to appear in static dependency graphs, such as dynamic loading, generated code, common configurations, and data contracts, are placed under explicit impact rules or conservative fallbacks.

If selected tests are the only validation path, missing dependency information directly leads to false negatives. We run fast selected tests in PRs, and full tests in main or Nightly, then reconcile failures in unselected tests. If a leak is found, we fix not only the code but also the dependency graph or selection rules.

In TIA evaluation, we prioritize the rate of missed selections and feedback time over the number of tests reduced. We achieve both the safety of always running full tests and the speed of not running irrelevant tests every time, through two paths.

  • Determine the scope of impact from target dependencies, not from the proximity of changed files.
  • Provide conservative fallbacks for dynamic dependencies, generated artifacts, common configurations, and data contracts.
  • Continuously audit for missed selections in PRs with full tests in main or Nightly.
// Conceptual example of separating selection paths and comprehensive paths
pull_request:
  affected_targets = reverse_deps(changed_targets)
  run(builds_and_tests(affected_targets))

main_or_nightly:
  run(all_required_builds_and_tests)
  compare(selection_log, full_suite_failures)
  repair_dependency_or_selection_rules()

Separate runner pools for ARM and Spot VMs based on compatibility and interruption tolerance.

ARM-based CPUs are a strong option if the target compiler, dependent binaries, container base image, and testing tools support arm64. Do not decide based solely on unit cost; measure whether expected artifacts and test results can be obtained from the same input on x86 and arm64, and whether price-performance, including processing time and transfer volume, improves. For cross-architecture caches, include toolchain and platform in the cache key to prevent confusion.

Spot VMs can be reclaimed by the provider at any time, and there is no guarantee that capacity will always be secured. Therefore, they are used for short unit tests, divisible builds, and jobs that do not cause side effects even if retried. Final gates for production releases, migrations, and processes that modify external states are left to regular runners.

Using Spot does not mean unlimited parallelization. Quota, capacity, queues, cache bandwidth, and external service rate limits are treated as upper bounds. When Spot is insufficient, options such as waiting, switching to a different zone or machine type, or limited fallback to regular runners should be available to avoid retry storms where all jobs retry simultaneously.

Migration is expanded after comparing the same job on x86 and ARM for a certain period, checking success rates, P95, CPU minutes, and artifact differences. For Spot, interruptions are intentionally induced to verify re-queuing, deduplication, and handling of intermediate artifacts.

  • ARM candidates: Builds and tests where native dependencies support arm64, and identity or acceptable differences can be verified.
  • Spot candidates: Short-duration, re-entrant, idempotent, divisible processes that can be safely re-executed after interruption.
  • Regular runners: Release gates, migrations, external writes, processes with strict completion times.
  • Common limits: Quota, capacity, queue, cache bandwidth, external API rate limits.

Separate queues for PR, main, and Nightly in the Admission Queue.

When resources are sufficient, any job can run immediately. An Admission Queue is needed to explicitly decide what gets priority and what waits during congestion. PRs under development, stable branches, Nightly, and releases are assigned to different classes, with not only priority but also reserved slots and maximum concurrency.

If PRs are always given the highest priority, starvation can occur where Nightly never starts in an environment with continuous PR submissions. Combine aging (increasing priority of jobs that have waited a certain time), minimum reserved slots per class, borrowing/lending unused quota, and maximum wait times. Fast tracks are not a mechanism to make low-priority jobs non-existent.

Preemption, which forcibly terminates running jobs to insert high-priority jobs, increases lost computation and re-execution costs. First, use a non-preemptive priority queue to give empty slots to high-priority jobs. If preemption is used, target only interruptible jobs and measure recoverable progress and lost CPU minutes.

  • Metrics to watch: Queue P50, P95, max for each class, number of executions, number of cancellations, starvation time.
  • Adjustment methods: Priority, reserved slots, maximum concurrency, aging, quota borrowing.
  • Use preemption as a last resort, and record CPU minutes lost and re-execution costs due to interruption.
// A conceptual example representing admission control during congestion
queues:
  pull_request:
    reserved_capacity: 60%
    max_concurrency: bounded
    aging: enabled
  main:
    reserved_capacity: 25%
    aging: enabled
  nightly:
    reserved_capacity: 15%
    borrow_unused_capacity: true

safety:
  max_queue_age: required
  preemption: interruptible_jobs_only

Fail-Fast separates stopping failures from collecting failures.

If all jobs are immediately stopped on every failure, the first flaky test or temporary network outage will result in insufficient diagnostic information. Fail-Fast is suitable for failures where it's clear that downstream success is impossible, such as uncompilable code, unresolvable dependencies, missing essential configurations, or confirmed lint violations.

If you want to collectively understand independent test failures, collect failures within the same stage and only stop subsequent high-cost stages. Whether to use Bazel's --keep_going equivalent depends on comparing the additional diagnostic information gained against the CPU cycles consumed. For PRs, place fast essential checks first, then make longer tests and image creation dependent on them.

Cancellation processing is also subject to validation. If child processes, VMs, containers, or leases remain even if the parent job fails, costs will not stop. We define the completion conditions for Fail-Fast as including cancellation propagation, grace period, saving logs and test reports, and completion of cleanup.

  • Immediate Stop: A prerequisite failure where downstream success is impossible, and retrying will not change the outcome.
  • Continue Collection: Independent tests, failures during flaky determination, failures where additional diagnosis is highly valuable.
  • Targets for Stopping: Propagate cancellation to subsequent stages, child processes, VMs, containers, and leases.
  • Targets for Saving: Logs that can reproduce the root cause, exit codes, test reports, and selected targets.

Pre-warming brings startup time closer to within budget, rather than zero.

Environmental caching involves pre-provisioning runner images, toolchains, dependent packages, and frequently used base images. However, warming everything constantly increases costs for unused VMs, stale caches, storage, and regular updates. The design should maintain a minimal warm pool that meets SLOs, rather than aiming for completely zero startup time.

Pre-warming targets are selected based on usage frequency and acquisition time. Restoring several GBs of cache from the network each time might be slower than a local build. Record not only the cache hit rate but also restore time, transfer bytes, decompression CPU, and eviction rate, prioritizing smaller, highly reusable layers.

Demand has time-of-day biases. Adjust the warm pool size based on PR arrival rates and queue length, reducing the lower limit during nights and holidays. When updating toolchains or images, gradually replace old warm instances and check digests and toolchain IDs at startup to prevent mixing different versions.

  • Pre-placement candidates: runner images, fixed toolchains, frequently used base images, highly reusable dependency layers.
  • Evaluation metrics: provisioning time, warm hit rate, cache restore time, transfer volume, idle cost.
  • Invalidation: Include image digest, lockfile, toolchain ID, and CPU architecture in the cache key.
  • Capacity Control: Increase or decrease the warm pool based on arrival rate and queue length, not maintaining a constant maximum.

Improvements: Reduce waste first, then move to cheaper computing resources.

If multiple measures are introduced simultaneously, it's impossible to isolate why speed or cost changed. First, collect metrics, then reduce the total workload with target and test selection. After that, control congestion with a priority queue, and move compatible jobs to ARM and Spot gradually. Finally, adjust Fail-Fast and Pre-warming.

At each stage, compare P50/P95 feedback time, queue time, vCPU minutes, cache hits, transfer volume, and rerun rate using the same method. If only P50 improves and P95 worsens, the design is fast under normal conditions but vulnerable to congestion or interruptions. If costs decrease but failure detection is delayed, review the order of essential checks or reserved slots.

Deployment should start with a subset of targets or a single runner pool, ensuring a fallback to the traditional path. If ARM result differences, increased Spot retries, missed TIA selections, queue starvation, or warm pool idle costs exceed the baseline, stop automatic scaling and investigate the cause.

  • Phase 1: Measure interval time, total CPU minutes, transfer volume, reruns, and billing.
  • Phase 2: Increase the amount of work not executed through target splitting and TIA.
  • Phase 3: Control priority and fairness during congestion with an Admission Queue.
  • Phase 4: Gradually introduce ARM and Spot for jobs with compatibility and interruption tolerance.
  • Phase 5: Adjust Fail-Fast and Pre-warming based on diagnostic value and waiting costs.

Even if it seems fast and cheap, skipping verification will lead to other increased costs.

Fine-grained targets, if dependencies are not accurate, will increase missed selections rather than cache reuse. TIA is similar; if full path traversal is omitted without capturing dynamic dependencies, fault discovery will shift to production, leading to recovery costs exceeding the amount saved by CI.

Spot instances are not always cheaper with every interruption. If a long job is interrupted near its end and restarted from the beginning, it might consume more CPU time than a regular VM. If checkpoints are expensive, it's simpler to break the job into smaller parts and reuse completed actions from the cache.

Priority queues, if the definition of importance is incorrect, create organizational starvation. Pre-warming, if demand forecasts are wrong, fixes waiting costs. Neither should be set once and forgotten; they require periodic adjustment based on queue age, idle rate, rerun rate, and PR arrival rate.

  • For small-scale, short-duration executions, the operational costs of Bazel migration or a dedicated queue infrastructure might outweigh the benefits.
  • Native dependencies not supported by ARM or x86-only toolchains should remain on regular runners.
  • Determine waiting and fallback strategies when Spot capacity is insufficient, and avoid unlimited retries.
  • Retain full TIA matching, queue aging, and warm pool idle limits as safety valves.

The decision-making criterion to take away is total work, not maximum parallelism.

CI/CD acceleration and cost optimization are not separate measures. By not executing work unrelated to changes, breaking down necessary work into smaller parts according to dependencies, and prioritizing important feedback, both elapsed time and total computation can be reduced simultaneously.

ARM and Spot VMs are means to improve unit cost and price-performance thereafter. Increasing only parallelism while ignoring compatibility, interruptions, quotas, and cache bandwidth will not reduce P95 and rerun costs. Fail-Fast and Pre-warming can only stabilize their effects when stop conditions and waiting budgets are defined.

The first numbers to look at are not 'how many machines can be run in parallel,' but 'how many CPU-minutes were used for one PR, and in how many minutes was the first effective failure returned?' Tracking these two on the same dashboard is the starting point for improving both speed and cost simultaneously.

Product-specific behavior should be confirmed in official documentation.

The following are official primary sources confirmed as of August 10, 2026. Bazel's recommended configuration, remote cache, Spot VM pricing and interruption conditions, ARM environments, and Kueue's fair admission control may be updated. Before actual implementation, reconfirm the version, region, machine type, quota, and pricing using current documentation.

Technical documents

We will continue to increase technical documentation.

We will continue to organize our thoughts on AI, cloud, business app development, requirements definition, and operational design into documents.

Go to technical documentation list