CI/CD pipeline optimization is where engineering velocity lives or dies. A 20-minute build that fails 30% of the time costs more than the infrastructure running it. This guide covers patterns that reduce build time, increase reliability, and make pipelines debuggable – based on optimizing pipelines for teams shipping 50+ times/day.
The Optimization Hierarchy
Reliability > Speed > Features
A fast pipeline that produces broken artifacts is worse than a slow one. Fix reliability first, then speed.
Phase 1: Reliability (Fix Flakiness First)
Test Quarantine System
# .github/workflows/test.yml
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run tests with quarantine
run: |
# Run tests, capture flaky ones
pytest --tb=short -q --junitxml=results.xml \
--reruns=2 --reruns-delay=1 \
--only-rerun=tests/flaky_list.txt
- name: Update flaky test list
if: always()
run: |
# Parse results, identify flaky tests
python scripts/update_flaky_list.py results.xml
continue-on-error: true
Flaky test criteria: Fails >1% of runs, passes on rerun without code change.
Deterministic Test Data
# tests/conftest.py
import pytest
from faker import Faker
@pytest.fixture(scope="session")
def deterministic_faker():
"""Seeded faker for reproducible test data"""
fake = Faker()
fake.seed_instance(42) # Same data every run
return fake
@pytest.fixture
def user_factory(deterministic_faker):
def _create(**overrides):
return User(
email=deterministic_faker.email(),
name=deterministic_faker.name(),
**overrides
)
return _create
Dependency Caching with Content Hashing
# .github/workflows/build.yml
- name: Cache dependencies
uses: actions/cache@v4
with:
path: |
~/.npm
~/.cache/pip
~/.cargo/registry
~/.m2/repository
key: ${{ runner.os }}-deps-${{ hashFiles('**/package-lock.json', '**/requirements.txt', '**/Cargo.lock', '**/pom.xml') }}
restore-keys: |
${{ runner.os }}-deps-
Critical: Hash the lock files, not package.json. Lock files = exact versions.
Phase 2: Speed (Parallelize Everything)
Test Parallelization
# Split tests by timing, not by directory
jobs:
test:
strategy:
matrix:
shard: [1, 2, 3, 4]
steps:
- name: Run test shard
run: |
pytest --forked --dist=loadgroup \
--numprocesses=4 \
--shard-id=${{ matrix.shard }} \
--shard-count=4
Result: 40-minute test suite → 12 minutes (with 4 shards).
Build Matrix for Multi-Arch
jobs:
build:
strategy:
matrix:
include:
- platform: linux/amd64
runner: ubuntu-latest
- platform: linux/arm64
runner: ubuntu-latest-arm64
runs-on: ${{ matrix.runner }}
steps:
- uses: docker/build-push-action@v5
with:
platforms: ${{ matrix.platform }}
push: true
Selective Testing (Only What Changed)
# scripts/affected-tests.sh
#!/bin/bash
# Get changed files since main
CHANGED_FILES=$(git diff --name-only origin/main...HEAD)
# Map to affected test files
python scripts/map_changes_to_tests.py "$CHANGED_FILES" > affected_tests.txt
# Run only affected tests
pytest $(cat affected_tests.txt)
Tools that do this automatically:
- Nx (JavaScript/TypeScript)
- Bazel (polyglot)
- Turborepo (JavaScript)
- Earthly (polyglot)
Docker Layer Caching in CI
- name: Build with BuildKit cache
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{ env.REGISTRY }}/${{ env.IMAGE }}:${{ github.sha }}
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: |
BUILDKIT_INLINE_CACHE=1
Requirements: # syntax=docker/dockerfile:1.4 in Dockerfile, BuildKit enabled.
Parallel Job Execution
jobs:
lint:
runs-on: ubuntu-latest
steps: [...]
typecheck:
runs-on: ubuntu-latest
steps: [...]
unit-test:
runs-on: ubuntu-latest
steps: [...]
integration-test:
needs: [lint, typecheck, unit-test] # Run after fast checks
runs-on: ubuntu-latest
steps: [...]
build:
needs: [lint, typecheck, unit-test]
runs-on: ubuntu-latest
steps: [...]
deploy:
needs: [integration-test, build]
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps: [...]
Fast jobs first: Lint/typecheck (30s) → Unit tests (2m) → Integration (10m) → Build (3m) → Deploy
Phase 3: Debuggability (Make Failures Obvious)
Structured Pipeline Output
- name: Run tests with structured output
run: |
pytest --tb=short -q \
--junitxml=test-results.xml \
--json-report --json-report-file=test-report.json \
--log-cli-level=INFO
- name: Upload test results
if: always()
uses: actions/upload-artifact@v4
with:
name: test-results
path: |
test-results.xml
test-report.json
retention-days: 30
Failure Annotations
- name: Annotate failures
if: failure()
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const results = fs.readFileSync('test-report.json', 'utf8');
const { tests } = JSON.parse(results);
for (const test of tests) {
if (test.outcome === 'failed') {
core.error(test.call?.longreprtext || test.message, {
file: test.nodeid.split('::')[0],
startLine: test.lineno
});
}
}
Build Artifacts for Debugging
- name: Save build artifacts on failure
if: failure()
uses: actions/upload-artifact@v4
with:
name: build-debug-${{ github.run_id }}
path: |
dist/
build/
target/
*.log
retention-days: 7
Reproducible Local Debugging
# scripts/ci-local.sh
#!/bin/bash
# Run CI pipeline locally with act or docker
# Option 1: act (GitHub Actions locally)
act -j test -s GITHUB_TOKEN=${GH_TOKEN}
# Option 2: Docker-based reproduction
docker run --rm -it \
-v $(pwd):/workspace \
-w /workspace \
ghcr.io/catthehacker/ubuntu:act-latest \
bash -c "
# Install tools
apt update && apt install -y nodejs npm python3
# Run pipeline steps
npm ci
npm test
"
Advanced Patterns
Monorepo: Affected Project Detection
# .github/workflows/monorepo.yml
jobs:
detect-changes:
outputs:
projects: ${{ steps.filter.outputs.projects }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: dorny/paths-filter@v2
id: filter
with:
filters: |
frontend:
- 'packages/frontend/**'
backend:
- 'packages/backend/**'
shared:
- 'packages/shared/**'
build-frontend:
needs: detect-changes
if: needs.detect-changes.outputs.projects == '["frontend"]'
steps: [...]
Dependency Update Automation
# .github/workflows/dependabot.yml
on:
schedule:
- cron: '0 2 * * 1' # Weekly Monday 2AM
workflow_dispatch:
jobs:
update-deps:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm ci
- run: npx npm-check-updates -u
- run: npm install
- run: npm test
- uses: peter-evans/create-pull-request@v5
with:
token: ${{ secrets.GITHUB_TOKEN }}
branch: deps/update-${{ github.run_number }}
title: 'chore: weekly dependency updates'
body: 'Automated dependency update'
Security Scanning in Pipeline
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# SAST
- name: Run CodeQL
uses: github/codeql-action/init@v2
with:
languages: javascript,python,go
# Dependency scanning
- name: Audit dependencies
run: |
npm audit --audit-level=high
pip-audit --desc
cargo audit
# Container scanning
- name: Scan image
uses: aquasecurity/trivy-action@master
with:
image-ref: ${{ env.REGISTRY }}/${{ env.IMAGE }}:${{ github.sha }}
severity: HIGH,CRITICAL
exit-code: 1
# SBOM generation
- name: Generate SBOM
uses: anchore/sbom-action@v0
with:
image: ${{ env.REGISTRY }}/${{ env.IMAGE }}:${{ github.sha }}
Progressive Deployment
jobs:
deploy-staging:
needs: build
runs-on: ubuntu-latest
environment: staging
steps:
- name: Deploy to staging
run: |
kubectl set image deployment/app \
app=${{ env.REGISTRY }}/${{ env.IMAGE }}:${{ github.sha }} \
-n staging
kubectl rollout status deployment/app -n staging
- name: Run smoke tests
run: |
./scripts/smoke-tests.sh https://staging.example.com
deploy-canary:
needs: deploy-staging
runs-on: ubuntu-latest
environment: production
steps:
- name: Deploy canary (10%)
run: |
# Argo Rollouts / Flagger / manual
kubectl argo rollouts set image rollout/app \
app=${{ env.REGISTRY }}/${{ env.IMAGE }}:${{ github.sha }} \
-n production
- name: Monitor metrics
run: |
./scripts/wait-for-metrics.sh \
--duration=10m \
--error-rate-threshold=0.01 \
--latency-p99-threshold=500ms
deploy-full:
needs: deploy-canary
runs-on: ubuntu-latest
environment: production
steps:
- name: Promote to 100%
run: |
kubectl argo rollouts promote rollout/app -n production
Measuring Pipeline Health
Key Metrics Dashboard
# .github/workflows/metrics.yml
- name: Record pipeline metrics
if: always()
run: |
cat <
Metrics to Track
| Metric | Target | Alert Threshold |
|---|---|---|
| Build success rate | > 95% | < 90% |
| Median build time | < 10 min | > 15 min |
| P95 build time | < 20 min | > 30 min |
| Queue time | < 2 min | > 5 min |
| Flaky test rate | < 1% | > 3% |
| Time to fix broken build | < 30 min | > 1 hour |
| Deploy frequency | > 10/day | < 1/day |
| Rollback rate | < 5% | > 10% |
Weekly Pipeline Review
# scripts/pipeline-health.sh
#!/bin/bash
gh run list --workflow=ci.yml --limit=100 --json conclusion,createdAt,headBranch | \
jq -r '
group_by(.headBranch) |
map({
branch: .[0].headBranch,
total: length,
success: map(select(.conclusion=="success")) | length,
failure: map(select(.conclusion=="failure")) | length,
avg_duration: (map(.createdAt) | map(fromdateiso8601) | add/length)
}) |
.[] | "\(.branch): \(.success)/\(.total) success, avg duration: \(.avg_duration)s"
'
Self-Hosted Runners (Cost + Speed)
# .github/workflows/self-hosted.yml
jobs:
build:
runs-on: [self-hosted, linux, x64, gpu] # Custom labels
steps:
- uses: actions/checkout@v4
# ... rest of build
Runner spec for 50 builds/day:
- 8 vCPU, 32GB RAM, 500GB NVMe
- Pre-warmed with: Docker images, language toolchains, caches
- Auto-scale: 1-10 runners based on queue depth
# Terraform for runner ASG
resource "aws_autoscaling_group" "github_runners" {
desired_capacity = 3
min_size = 1
max_size = 10
target_tracking_configuration {
predefined_metric_type = "ASGAverageCPUUtilization"
target_value = 60
}
}
Pipeline as Code: Version Everything
.github/
├── workflows/
│ ├── ci.yml # Main pipeline
│ ├── release.yml # Release pipeline
│ ├── dependabot.yml # Dependency updates
│ └── security.yml # Security scans
├── actions/
│ ├── setup-node/ # Composite action
│ ├── build-docker/ # Reusable workflow
│ └── deploy-k8s/ # Reusable workflow
└── scripts/
├── affected-tests.sh
├── map_changes_to_tests.py
├── smoke-tests.sh
└── wait-for-metrics.sh
Benefits:
- Changes reviewed like code
- History of pipeline evolution
- Reusable across repos
- Testable locally
Quick Wins Checklist
- [ ] Enable BuildKit (
DOCKER_BUILDKIT=1) - [ ] Add
# syntax=docker/dockerfile:1.4to all Dockerfiles - [ ] Cache package manager directories with lock file hashes
- [ ] Split test suite into 4+ parallel shards
- [ ] Quarantine flaky tests (don't delete, isolate)
- [ ] Run lint/typecheck before tests (fail fast)
- [ ] Add failure annotations for PR feedback
- [ ] Generate SBOM on every build
- [ ] Scan container images for HIGH/CRITICAL CVEs
- [ ] Track build success rate, duration, queue time weekly
Summary
Pipeline optimization is continuous, not a one-time project. The order:
- Reliability: Quarantine flaky tests, deterministic data, content-hash caching
- Speed: Parallelize tests, selective testing, BuildKit cache, matrix builds
- Debuggability: Structured output, failure annotations, local reproduction
- Observability: Metrics dashboard, weekly reviews, alerting
A pipeline that takes 5 minutes, succeeds 98% of the time, and tells you exactly why it failed is worth more than any feature flag system.
Hi,
I just visited devstackio.com and wondered if you’d ever thought about having an engaging video to explain what you do?
Our prices start from just $195 (USD) / £145.
Let me know if you’re interested in seeing samples of our previous work.
Regards,
Joanna
Hi,
I was looking over devstackio.com and wanted to reach out.
We help brands and businesses quickly tell their story through short promotional videos for websites and social media.
I can show you some previous videos we’ve done if you’d like samples. Our videos start from just $195 for a 30 second video ($239 for 60 seconds) and include a full script, voiceover and video.
Thanks,
Jo Riggs