# Fast CI/CD Pipelines: Caching, Monorepos and Test Sharding

> Make CI/CD fast and safe: caching, monorepo affected builds, test sharding, flaky tests, build-once promotion, canary and blue/green, migrations, rollbacks.

Source: https://www.derar.dev/blog/fast-ci-pipelines-caching-monorepos-deploy-strategies-2026 · Published 2026-11-11 · Updated 2026-11-14 · By Derar Sattouf

A slow pipeline is a tax on every engineer, every day. A flaky pipeline is worse: it teaches people to ignore red builds, and the day a red build is real, nobody looks. A pipeline that deploys unsafely is worst of all, because it turns every merge into a gamble with production.

Treat the pipeline as a product with measurable outcomes. Measure first: the four DORA metrics (deployment frequency, lead time for changes, change failure rate, time to restore), plus CI duration at p50 and p90, queue time and flake rate. Then optimize the slowest critical path, not the average job. Examples use GitHub Actions and GitLab CI, and the patterns transfer to any CI system. Versions and product behaviour reflect late 2026, and where a number or flag is likely to change, the text says to verify against current docs.

Most of the speed comes from three habits. Cache at every layer: dependency caches keyed by lockfile hash, build tool caches (Gradle, Cargo, Go), Docker BuildKit cache exports, and a remote task cache (Turborepo or Nx) shared between laptops and CI. In a monorepo, build and test only what changed (`turbo --affected`, `nx affected`, path filters), but run a full build on main on a schedule to catch graph errors. And shard tests across runners, balanced by historical duration, retrying only failed tests once and quarantining flaky tests with an owner instead of ignoring them.

Safety comes from how you ship. Build once, deploy many: produce one immutable, versioned artifact per commit and promote that same artifact through environments. Configuration changes between environments; the binary does not. Pick the deployment strategy by risk: rolling for low risk, blue/green for fast rollback, canary with automated analysis for high traffic services, and feature flags to decouple deploy from release. Make database changes backward compatible (expand, migrate, contract) so the previous application version still works against the new schema. That's what makes rollback possible.

Set budgets too: PR feedback in under 10 minutes, the main pipeline under 20, and a monthly CI cost per engineer that you review like any other infrastructure bill.

## Pipeline anatomy and what to measure

### The stages

Most pipelines contain the same stages, with different names:

```text
 commit
   |
   v
 [1 Validate]   lint, format, typecheck, secret scan, license check        (seconds to minutes)
   |
   v
 [2 Build]      compile, bundle, container image, generate artifacts         (minutes)
   |
   v
 [3 Test]       unit, integration, contract, end-to-end                      (minutes, parallel)
   |
   v
 [4 Package]    sign, attest, SBOM, push to registry                         (minutes)
   |
   v
 [5 Deploy]     dev -> staging -> production, with gates and verification    (minutes)
   |
   v
 [6 Verify]     smoke tests, SLO checks, automated rollback                  (minutes)
```

The **critical path** is the longest chain of dependent stages. Adding parallel jobs shortens wall-clock time only if they are on the critical path. Optimizing a job that already finishes before the slowest sibling does nothing.

### DORA metrics

The DORA research programme defines four software delivery metrics. They are useful because they measure outcomes, not activity:

| Metric | What it measures | How CI/CD influences it | Where to get the data |
| --- | --- | --- | --- |
| Deployment frequency | How often you deploy to production | Fast, safe pipelines make small deploys cheap | Deployment events from your CD tool or GitHub deployments API |
| Lead time for changes | Commit to running in production | Pipeline duration, review waiting time, approval waits | Commit timestamps and deployment timestamps |
| Change failure rate | Share of deploys causing a failure that needs remediation | Test quality, progressive delivery, feature flags | Incident tracker linked to deploys |
| Time to restore service | How long it takes to recover from a failed change | Rollback speed, observability, runbooks | Incident timestamps |

DORA's more recent reports also discuss deployment rework rate and a more nuanced split between throughput and stability; verify the latest definitions in the current DORA report before putting numbers on a dashboard. The point stands: **throughput and stability improve together** when batches are small and feedback is fast.

### Pipeline-specific metrics

DORA is coarse. Add these per repository:

| Metric | Target (starting point) | Why |
| --- | --- | --- |
| PR pipeline duration p50 and p90 | p50 under 8 min, p90 under 15 min | Developers wait on this many times per day |
| Queue time (waiting for a runner) | under 30 s at p90 | Hidden latency that no job log shows |
| Main pipeline duration to deployable artifact | under 15 min | Sets the floor for lead time |
| Flake rate (tests that failed then passed on retry) | under 1 percent of runs | Trust in red builds |
| Cache hit rate per cache | above 80 percent for dependency caches | Detects broken cache keys |
| Cost per pipeline run and per engineer per month | Tracked, reviewed monthly | Prevents silent growth |
| Re-run rate (humans pressing "re-run") | Falling | A direct proxy for flakiness |

### Find the bottleneck before optimizing

Export step timings from a representative run and sort by duration. With GitHub Actions the API returns job and step start and end times:

```bash
gh run view RUN_ID --json jobs \
  --jq '.jobs[] | {job: .name, steps: [.steps[] | {name, secs: ((.completedAt|fromdate) - (.startedAt|fromdate))}]}' \
  | jq -r '.job as $j | .steps[] | "\(.secs)\t\($j)\t\(.name)"' | sort -rn | head -20
```

The top ten lines usually show the same suspects: dependency install, a cold compile, a Docker build with no cache, a serial test suite, and a long wait for an approval. Fix them in that order.

## Caching: the layers

Caching usually saves more time than any other change, and it's also the easiest one to get subtly wrong. Think in layers, from cheapest and safest to most powerful.

### Layer table

| Layer | What is cached | Key | Typical gain | Risk |
| --- | --- | --- | --- | --- |
| 1. Dependency download | npm, pnpm, pip, Maven/Gradle, Cargo registries | Hash of the lockfile | Seconds to minutes | Low; stale keys only waste space |
| 2. Tool and toolchain | Language runtimes, compilers, CLI tools | Version string | Seconds | Low |
| 3. Build tool incremental state | Gradle build cache, Cargo target dir, Go build cache, TypeScript incremental info | Lockfile plus source hash | Minutes | Medium; non-reproducible builds cause misses or stale reuse |
| 4. Container layers | Docker layers via BuildKit cache exports | Dockerfile layer hashes | Minutes | Low when Dockerfile is ordered well |
| 5. Remote task cache | Outputs of whole tasks (build, test, lint) in a monorepo | Hash of task inputs | Minutes to tens of minutes | Medium; wrong input declarations give false hits |
| 6. Test result caching | Skip tests whose inputs did not change | Hash of test inputs | Large | High if tests depend on undeclared inputs |

### Dependency caches in GitHub Actions

Most setup actions have caching built in. Prefer that over hand-written cache steps:

```yaml
- uses: actions/setup-node@v5
  with:
    node-version: "24"
    cache: pnpm              # keyed by pnpm-lock.yaml

- uses: actions/setup-python@v6
  with:
    python-version: "3.13"
    cache: pip               # keyed by requirements*.txt

- uses: actions/setup-go@v6
  with:
    go-version-file: go.mod
    cache: true              # module and build cache, keyed by go.sum
```

Versions shown are illustrative major tags; pin the versions you have reviewed (see the hardening post linked at the end). When you need a manual cache, follow the key and restore-key pattern:

```yaml
- uses: actions/cache@v4
  with:
    path: |
      ~/.cargo/registry
      ~/.cargo/git
      target
    key: cargo-${{ runner.os }}-${{ hashFiles('**/Cargo.lock') }}
    restore-keys: |
      cargo-${{ runner.os }}-
```

The `restore-keys` fallback gives you a partial hit from the nearest previous cache, which matters for incremental compilers: a slightly stale `target` directory is far better than none.

### Cache rules that prevent pain

1. **Key by content, not by date.** A key derived from the lockfile hash is invalidated exactly when dependencies change.
2. **Cache downloads, be careful caching builds.** A cached `node_modules` can hide a broken install; a cached compiled output can hide a dependency change. Prefer caching the package manager's content-addressed store and reinstalling from it.
3. **Mind cache scope and limits.** GitHub Actions caches are scoped per branch with fallback to the default branch, and the repository has a total size limit with least-recently-used eviction. Verify the current limit in the docs. Large caches evict each other, so do not cache things that are fast to regenerate.
4. **Compress and size deliberately.** Restoring a 3 GB cache can take longer than rebuilding. Measure restore time.
5. **Only trusted refs should write.** Let the default branch populate shared caches and let pull requests read them, which both improves hit rate and reduces poisoning risk.
6. **Track hit rate.** Log a cache hit output and alert when it drops; a broken key silently makes everything slow.

### Docker BuildKit caching

Container builds are often the single slowest step. Two things matter: Dockerfile layer ordering and where the cache lives.

Order the Dockerfile from least to most frequently changing:

```dockerfile
# syntax=docker/dockerfile:1
FROM node:24-slim AS deps
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN --mount=type=cache,target=/root/.local/share/pnpm/store \
    corepack enable && pnpm install --frozen-lockfile

FROM deps AS build
COPY . .
RUN pnpm build

FROM node:24-slim AS runtime
WORKDIR /app
ENV NODE_ENV=production
COPY --from=build /app/dist ./dist
COPY --from=deps /app/node_modules ./node_modules
USER node
CMD ["node", "dist/server.js"]
```

The lockfile and manifest are copied first, so the dependency layer is reused until they change. The `--mount=type=cache` mount keeps the package manager's store between builds on the same builder.

Because CI runners are ephemeral, the local layer cache disappears with them. Export and import the cache through a backend:

```yaml
- uses: docker/setup-buildx-action@v3
- uses: docker/build-push-action@v6
  with:
    context: .
    push: true
    tags: ghcr.io/my-org/my-app:${{ github.sha }}
    cache-from: type=gha
    cache-to: type=gha,mode=max
```

| Cache backend | Where it lives | Good for | Caveats |
| --- | --- | --- | --- |
| `type=gha` | GitHub Actions cache service | Simple setups on GitHub | Subject to the repository cache size limit; verify current backend version notes in Docker docs |
| `type=registry` | A tag in a container registry | Multi-CI, large images, shared with laptops | Registry storage and pull time |
| `type=local` | A directory you persist | Self-hosted runners with persistent disks | Needs your own persistence |
| `type=s3` or `type=azblob` | Object storage | Large teams, cross-runner sharing | Needs credentials and lifecycle policy |
| Managed remote builders | Vendor-hosted BuildKit with persistent cache | Fastest cold-to-warm behaviour, multi-arch | Cost and vendor dependency |

`mode=max` exports intermediate layers as well as final ones, which improves hits for multi-stage builds at the price of a larger cache.

Also: use `.dockerignore` to keep the build context small, pin base images by digest in production, and build multi-architecture images on native runners rather than QEMU emulation when build time matters (emulation is often several times slower).

### Remote task caches for monorepos

A **remote cache** stores the outputs of tasks keyed by a hash of their inputs (source files, dependencies, environment variables, command). If any developer or CI run has already built that exact input, everyone else downloads the result instead of recomputing it.

**Turborepo** (configured through `turbo.json`) uses a remote cache with Vercel by default or a self-hosted compatible server:

```jsonc
// turbo.json
{
  "$schema": "https://turborepo.com/schema.json",
  "tasks": {
    "build": {
      "dependsOn": ["^build"],
      "inputs": ["$TURBO_DEFAULT$", "!**/*.md"],
      "outputs": ["dist/**", ".next/**", "!.next/cache/**"],
      "env": ["NODE_ENV", "API_BASE_URL"]
    },
    "test": {
      "dependsOn": ["build"],
      "inputs": ["src/**", "test/**", "package.json"],
      "outputs": ["coverage/**"]
    },
    "lint": {
      "outputs": []
    }
  }
}
```

In CI:

```yaml
env:
  TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
  TURBO_TEAM: ${{ vars.TURBO_TEAM }}

steps:
  - run: pnpm install --frozen-lockfile
  - run: pnpm turbo run build test lint --affected
```

**Nx** offers a similar remote cache through Nx Cloud or self-hosted cache plugins, and a computation cache controlled by `nx.json` named inputs and target defaults. **Bazel**, **Gradle** (build cache plus a remote cache node), and **sccache** for Rust and C++ cover other ecosystems. The mechanics are the same.

The failure mode of remote caches is **false hits**: a task reads an environment variable, a file outside the declared inputs, or the current time, and the cache serves a stale result. Declare inputs and environment variables explicitly, verify with a dry run or the tool's `--summarize` and hash inspection output, and periodically run a build with the cache disabled on main to compare results.

Treat the remote cache as a security boundary too: anything writable by a pull request from a fork can poison it. Give read-only credentials to untrusted PR jobs and let only trusted branches write. Self-hosted cache servers need authentication and signed or access-controlled writes.

## Monorepos: do less work

### The problem

In a monorepo with 40 packages and a 30-minute full build, a one-line change to a README should not cost 30 minutes. The tools exist to compute **the set of projects affected by a change** from a dependency graph and to restrict work to that set.

### Strategies, from simple to powerful

| Approach | How it works | Strengths | Weaknesses |
| --- | --- | --- | --- |
| CI path filters | Trigger workflows only when certain paths change | Trivial, no tooling | Does not understand dependencies; shared library changes can be missed |
| `git diff` plus a script | Compute changed directories manually | Flexible | You maintain the graph logic |
| Turborepo `--affected` or `--filter` | Uses the workspace graph and git diff | Great for JavaScript and TypeScript | Mostly JS-centric |
| Nx `affected` | Project graph from code analysis and config | Rich graph, supports many languages via plugins | More setup |
| Bazel, Pants, Buck2 | Fine-grained hermetic build graph | Correct and fast at large scale | High adoption cost |
| Gradle composite builds with the build cache | Task-level caching and project dependency graph | Native for JVM and Android | JVM-focused |

### Turborepo and Nx in practice

```bash
# Turborepo: run tasks only for packages affected since the base branch
pnpm turbo run build test --affected

# Older equivalent using filter syntax:
pnpm turbo run build test --filter="...[origin/main]"

# Nx: run for affected projects between two commits
pnpm nx affected -t lint test build --base=origin/main --head=HEAD
```

In GitHub Actions the **base commit** needs care. A shallow checkout cannot compute a diff, and the base for a pull request is the merge base, not necessarily the previous commit. For Nx, the `nrwl/nx-set-shas` action sets `NX_BASE` and `NX_HEAD` to the last successful run on the main branch; for Turborepo, fetch enough history:

```yaml
- uses: actions/checkout@v4
  with:
    fetch-depth: 0       # or a depth sufficient to include the merge base
- uses: nrwl/nx-set-shas@v4
- run: pnpm nx affected -t lint test build
```

Check the action and flag names against current documentation for the versions you use. Both tools have changed their affected-detection options over the last few releases.

### Dynamic matrices from the affected set

For CI systems that cannot run the tool directly per project, compute the list of affected projects in one job and fan out:

```yaml
jobs:
  plan:
    runs-on: ubuntu-latest
    outputs:
      projects: ${{ steps.affected.outputs.projects }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: pnpm/action-setup@v4
      - uses: actions/setup-node@v5
        with:
          node-version: "24"
          cache: pnpm
      - run: pnpm install --frozen-lockfile
      - id: affected
        run: |
          projects="$(pnpm nx show projects --affected --base=origin/main --json)"
          echo "projects=$projects" >> "$GITHUB_OUTPUT"

  test:
    needs: plan
    if: needs.plan.outputs.projects != '[]'
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        project: ${{ fromJSON(needs.plan.outputs.projects) }}
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v4
      - uses: actions/setup-node@v5
        with:
          node-version: "24"
          cache: pnpm
      - run: pnpm install --frozen-lockfile
      - run: pnpm nx test ${{ matrix.project }}
```

Here the matrix value comes from the repository's own tooling, not from untrusted input, so interpolating it is acceptable. If a value ever originates from a pull request title or branch name, pass it through an environment variable instead.

### Required checks with conditional jobs

Branch protection requires named status checks. If a job is skipped by a path filter, the check never reports and the pull request blocks forever. The usual fix is a final **gate job** that always runs and aggregates results:

```yaml
  ci-gate:
    if: always()
    needs: [lint, test, build]
    runs-on: ubuntu-latest
    steps:
      - name: Fail if any needed job failed or was cancelled
        run: |
          echo '${{ toJSON(needs) }}' | jq -e 'all(.[]; .result == "success" or .result == "skipped")'
```

Require only `ci-gate` in branch protection. Skipped jobs count as success; failed and cancelled ones do not.

### Keep the safety net

Affected-only builds depend on a correct dependency graph, which can drift (a script that reads a sibling package without declaring it, a config file outside any project). Run a **full build and test on main** nightly or on every merge, and treat a failure that affected-only missed as a graph bug to fix.

### Merge queues

When many pull requests land at once, each was tested against an older main. A **merge queue** (GitHub merge queue, GitLab merge trains) tests the pull request against the latest main plus the PRs ahead of it before merging, keeping main green. Costs: extra CI minutes, so keep the queue's required checks to the fast ones, and use the workflow trigger the platform requires for merge group events (on GitHub, the `merge_group` event; verify the current syntax).

## Test parallelism, sharding, and flaky tests

### Where time goes in tests

| Test layer | Share of tests | Time per test | Flake risk | Where to run |
| --- | --- | --- | --- | --- |
| Unit | 70 percent | milliseconds | Low | Every commit |
| Integration (database, queues) | 20 percent | 100 ms to seconds | Medium | Every commit, in containers |
| Contract and API | 5 percent | seconds | Medium | Every commit for affected services |
| End-to-end through UI | 5 percent | seconds to a minute | High | PR smoke subset, full suite on main |

If your end-to-end layer dominates wall-clock time, shift the balance: more unit and integration tests, fewer but more reliable end-to-end tests.

### Parallelism inside one machine

Use all cores first; it is free.

```bash
# Jest
npx jest --maxWorkers=50%

# pytest with xdist
pytest -n auto --dist loadfile

# Go
go test ./... -p 8 -count=1

# Rust: nextest runs tests in parallel processes with better isolation
cargo nextest run
```

Tests that share a database or a port will collide when parallelized. Give each worker its own schema or database (for example a suffix from the worker id) and use ephemeral ports.

### Sharding across machines

When one machine is not enough, split the suite into shards and run them as a matrix.

```yaml
jobs:
  e2e:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        shard: [1, 2, 3, 4]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v5
        with:
          node-version: "24"
          cache: npm
      - run: npm ci
      - run: npx playwright install --with-deps chromium
      - run: npx playwright test --shard=${{ matrix.shard }}/4
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: blob-report-${{ matrix.shard }}
          path: blob-report
          retention-days: 3

  merge-reports:
    needs: e2e
    if: always()
    runs-on: ubuntu-latest
    steps:
      - uses: actions/download-artifact@v4
        with:
          pattern: blob-report-*
          path: all-blob-reports
          merge-multiple: true
      - run: npx playwright merge-reports --reporter html ./all-blob-reports
```

Playwright (`--shard=x/y`) and Jest (`--shard=x/y`) have built-in sharding. For pytest, plugins such as `pytest-split` balance shards by recorded durations. Go and Rust can shard by package lists.

**Balance by duration, not by count.** Splitting 1000 tests into four groups of 250 is useless if one group has all the slow ones. Store per-test timings from the last main run and let the splitter assign by cumulative time. GitLab CI offers `parallel` plus test-splitting tooling; on GitHub you wire it with a small script or a plugin.

### Sharding in GitLab CI

```yaml
# .gitlab-ci.yml
test:
  stage: test
  image: node:24
  parallel: 4
  cache:
    key:
      files: [package-lock.json]
    paths: [.npm/]
    policy: pull
  script:
    - npm ci --cache .npm --prefer-offline
    - npx jest --shard=$CI_NODE_INDEX/$CI_NODE_TOTAL --ci --reporters=default --reporters=jest-junit
  artifacts:
    when: always
    reports:
      junit: junit.xml
```

`$CI_NODE_INDEX` and `$CI_NODE_TOTAL` are provided by GitLab for `parallel` jobs, and JUnit reports show failures in merge requests.

### Matrix builds

Use a matrix for dimensions that actually matter: supported runtime versions, operating systems for a library, database versions. Avoid the full cross product.

```yaml
strategy:
  fail-fast: false
  matrix:
    include:
      - { os: ubuntu-latest, node: "22" }
      - { os: ubuntu-latest, node: "24" }
      - { os: windows-latest, node: "24" }
```

For applications that only deploy to one runtime, a matrix of Node versions is wasted money. Reserve broad matrices for libraries and run them on main or nightly, with a single configuration on pull requests.

### Flaky tests: policy and mechanics

A flaky test is one that sometimes fails and sometimes passes against the same code. The cost is not the re-run; it is the erosion of trust.

**Policy:**

1. Define flaky operationally: a test that fails and then passes on retry, or fails intermittently on main with no code change.
2. **Detect automatically.** Record per-test results from every run (JUnit XML or the tool's JSON reporter) and compute a flake rate. Alert above a threshold such as 1 percent.
3. **Quarantine.** A flaky test moves to a non-blocking job within a day, with a ticket, an owner, and a deadline. Never leave it in the blocking path with a retry that hides it.
4. **Retry narrowly.** Retry only the failed tests, at most once, and report retried tests as warnings. A global job retry masks races and doubles cost.
5. **Fix root causes.** Common causes: shared state, time and randomness, real network dependencies, order dependence, resource limits (out-of-memory, port exhaustion), race conditions in async code, and unreliable waits (sleeps instead of conditions).

**Mechanics:**

```yaml
# Retry failed tests only, and surface retries
- run: npx playwright test --retries=1 --reporter=github,json
  env:
    PLAYWRIGHT_JSON_OUTPUT_NAME: results.json

- name: Report flaky tests
  if: always()
  run: |
    jq -r '.. | objects | select(.status? == "flaky") | .title' results.json | tee flaky.txt
    test ! -s flaky.txt || echo "::warning::Flaky tests detected, see flaky.txt"
```

Playwright marks tests that passed on retry as `flaky` in its reports; other frameworks offer similar flags. For long-term tracking, push results to a test analytics service or a simple table in your data warehouse.

### Hermetic tests

The best flake fix is removing nondeterminism: fixed clocks, seeded randomness, containerized dependencies started by the test run (Testcontainers is the common library), recorded or mocked external services, and unique resource names per test. A test that needs the public internet will eventually fail for reasons unrelated to your code.

### Fail fast, but not too fast

Put the fastest, most informative checks first: lint and typecheck, then unit tests, then slower suites. With `fail-fast: true` on a matrix, one failing shard cancels the others and you lose information; use `fail-fast: false` for test matrices and `true` for cheap gating stages.

## Build once, deploy many: artifact promotion

### The principle

```text
   commit abc123
        |
        v
   [ BUILD ONCE ]  ---> image my-app:abc123 (digest sha256:...)   one immutable artifact
        |
        +--> deploy to dev      (config: dev)
        +--> deploy to staging  (config: staging)    <- same digest
        +--> deploy to prod     (config: prod)       <- same digest
```

If you rebuild for each environment you test one binary and ship another. Differences in base image updates, dependency resolution, timestamps, or build flags can introduce bugs that no environment ever saw. A single immutable artifact, identified by content digest, is what you test and what you ship.

### Implementation rules

1. **Tag by commit SHA and refer to the digest** when deploying. Mutable tags (`latest`, `main`) are for convenience, not for deployment.
2. **No environment-specific values baked into the artifact.** Configuration comes at deploy time through environment variables, config maps, secrets managers, or Helm values per environment.
3. **Promote by reference.** Promotion is a pointer change (a manifest update, a registry retag with the same digest), not a rebuild.
4. **Sign and attest the artifact** once at build, and verify before each deploy (see the supply chain post linked at the end).
5. **Retain build metadata**: commit SHA, build time, CI run URL, SBOM, as image labels (`org.opencontainers.image.revision`, `org.opencontainers.image.source`).

### A GitHub Actions flow with promotion

```yaml
name: pipeline

on:
  push:
    branches: [main]

permissions:
  contents: read

jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
      id-token: write
      attestations: write
    outputs:
      digest: ${{ steps.push.outputs.digest }}
    steps:
      - uses: actions/checkout@v4
      - uses: docker/setup-buildx-action@v3
      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - id: push
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          tags: ghcr.io/my-org/my-app:${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          provenance: mode=max
      - uses: actions/attest-build-provenance@v2
        with:
          subject-name: ghcr.io/my-org/my-app
          subject-digest: ${{ steps.push.outputs.digest }}
          push-to-registry: true

  deploy-staging:
    needs: build
    runs-on: ubuntu-latest
    environment: staging
    steps:
      - uses: actions/checkout@v4
      - name: Deploy by digest
        env:
          IMAGE: ghcr.io/my-org/my-app@${{ needs.build.outputs.digest }}
        run: ./scripts/deploy.sh staging "$IMAGE"
      - name: Smoke test
        run: ./scripts/smoke.sh https://staging.example.com

  deploy-production:
    needs: [build, deploy-staging]
    runs-on: ubuntu-latest
    environment: production       # required reviewers configured here
    steps:
      - uses: actions/checkout@v4
      - name: Deploy the same digest
        env:
          IMAGE: ghcr.io/my-org/my-app@${{ needs.build.outputs.digest }}
        run: ./scripts/deploy.sh production "$IMAGE"
```

The production job deploys exactly the digest that staging verified. If you later need to roll back, you redeploy a previous digest, which is also an artifact you tested.

### The same idea in GitLab CI

```yaml
stages: [build, staging, production]

build:
  stage: build
  image: docker:27
  services: [docker:27-dind]
  script:
    - docker build -t "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA" .
    - docker push "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA"
    - echo "IMAGE=$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA" > build.env
  artifacts:
    reports:
      dotenv: build.env

deploy_staging:
  stage: staging
  environment:
    name: staging
    url: https://staging.example.com
  needs: [build]
  script:
    - ./scripts/deploy.sh staging "$IMAGE"

deploy_production:
  stage: production
  environment:
    name: production
    url: https://app.example.com
  needs: [deploy_staging]
  when: manual                    # approval gate
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
  script:
    - ./scripts/deploy.sh production "$IMAGE"
```

GitLab's protected environments add approval rules and restrict who may deploy. The `dotenv` report passes the image reference to later jobs.

## Environments, approvals, and gates

### Environment ladder

| Environment | Purpose | Data | Deploy trigger | Approval |
| --- | --- | --- | --- | --- |
| Preview (per PR) | Review a change in isolation | Synthetic or seeded | On pull request | None |
| Dev / integration | Integrate multiple changes | Synthetic | Every merge to main | None |
| Staging | Production-like verification | Anonymized or synthetic | After dev passes | Optional |
| Production | Real users | Real | After staging passes | Required for sensitive systems; automatic for mature teams |

Fewer environments is better. Each one needs data, configuration, and maintenance. Many teams do well with preview, staging, and production only.

### Approvals

Approvals are a control, not a ritual. Use them where human judgment adds value (customer-impacting changes, compliance-sensitive systems, changes outside business hours) and automate everything else with **machine gates**:

- Smoke tests pass on the new version.
- Error rate and latency SLOs are within bounds after a bake period.
- No open incident, and the deploy is inside an allowed window.
- Required security checks passed (provenance verified, no critical vulnerabilities).

On GitHub use **environments** with required reviewers, wait timers, and branch restrictions; on GitLab use protected environments and approval rules. Two reviewers and a prevent-self-review rule are the common baseline for production in regulated settings.

### Deployment windows and freezes

Encode freezes in the pipeline rather than in a wiki: a gate job that checks a calendar or a feature flag and fails with a clear message. Allow an audited override for emergencies, because a freeze that blocks a security fix creates a worse risk than the freeze avoids.

### Concurrency control for deploys

Never run two deploys to the same environment at once:

```yaml
concurrency:
  group: deploy-production
  cancel-in-progress: false      # queue; never cancel a deploy mid-flight
```

## Deployment strategies

A deployment strategy answers: how do we move traffic from the old version to the new, and how quickly can we reverse it?

### Comparison

| Strategy | How it works | Rollback speed | Extra capacity | Risk exposure | Complexity | Best for |
| --- | --- | --- | --- | --- | --- | --- |
| Recreate | Stop old, start new | Slow (redeploy) | None | All users see downtime | Lowest | Dev environments, batch jobs, singleton workloads |
| Rolling | Replace instances gradually | Medium | Small surge | Gradual, no clean cut | Low | Stateless services with backward-compatible changes |
| Blue/green | Run a full new stack, switch traffic at once | Fast (switch back) | Double capacity during deploy | All users at once after switch | Medium | Services needing instant rollback and clean cutover |
| Canary | Send a small percentage to the new version, increase on healthy metrics | Fast (route to 0 percent) | Small | Small slice of users | High | High traffic, critical services with good metrics |
| Feature flags | Deploy code dark, enable per user or percentage at runtime | Instant (flip a flag) | None | Controlled and targeted | Medium (flag hygiene) | Decoupling deploy from release; risky features |
| Shadow / mirror | Copy traffic to the new version without returning its responses | N/A (no user exposure) | Extra | None for users | High | Validating rewrites and migrations |

### Rolling updates on Kubernetes

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 6
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 0        # never reduce capacity during rollout
  minReadySeconds: 10
  progressDeadlineSeconds: 300
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      terminationGracePeriodSeconds: 30
      containers:
        - name: app
          image: ghcr.io/my-org/my-app@sha256:REPLACE_WITH_DIGEST
          ports:
            - containerPort: 8080
          readinessProbe:
            httpGet:
              path: /healthz/ready
              port: 8080
            periodSeconds: 5
            failureThreshold: 3
          lifecycle:
            preStop:
              exec:
                command: ["sleep", "10"]   # let load balancers drain
```

Details that make rolling updates safe: **readiness probes** that reflect real ability to serve (including dependencies you cannot work without), `maxUnavailable: 0` for capacity safety, a `preStop` delay plus graceful shutdown handling so in-flight requests finish, and `progressDeadlineSeconds` so a stuck rollout fails instead of hanging. In CI use `kubectl rollout status deployment/my-app --timeout=300s` as the gate and `kubectl rollout undo` as the rollback.

### Blue/green

Run two identical environments; only one serves production traffic. Deploy to the idle one, verify, switch the router, keep the old one for a while as instant rollback.

```text
              +--------------------+
  users ----> |  Router / LB / DNS | ----(active)----> GREEN (v42, live)
              +--------------------+
                         \--(standby)----------------> BLUE  (v43, deployed, tested, idle)

  switch:   router points to BLUE.    rollback: router points back to GREEN.
```

On Kubernetes a simple form switches a Service selector between two Deployments:

```yaml
apiVersion: v1
kind: Service
metadata:
  name: my-app
spec:
  selector:
    app: my-app
    track: green        # change to "blue" to cut over
  ports:
    - port: 80
      targetPort: 8080
```

```bash
kubectl patch service my-app -p '{"spec":{"selector":{"app":"my-app","track":"blue"}}}'
```

Considerations: **database compatibility** (both versions run against one database, so schema changes must work for both; see the database migrations section), **sessions and caches** (shared or externalized), and **cost** (double capacity for the overlap, which can be short on autoscaling platforms). Cloud load balancers (weighted target groups on AWS ALB, for example) and platforms such as AWS CodeDeploy or Azure slots implement blue/green natively.

### Canary with automated analysis

A canary sends a small share of traffic to the new version and promotes it only if metrics stay healthy. The **Argo Rollouts** controller (verify the current version and Kubernetes support matrix in its docs) is a common way to implement this on Kubernetes:

```yaml
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
  name: my-app
spec:
  replicas: 10
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
        - name: app
          image: ghcr.io/my-org/my-app@sha256:REPLACE_WITH_DIGEST
  strategy:
    canary:
      canaryService: my-app-canary
      stableService: my-app-stable
      trafficRouting:
        nginx:
          stableIngress: my-app
      steps:
        - setWeight: 5
        - pause: { duration: 5m }
        - analysis:
            templates:
              - templateName: success-rate
        - setWeight: 25
        - pause: { duration: 10m }
        - setWeight: 50
        - pause: { duration: 10m }
        - setWeight: 100
---
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
  name: success-rate
spec:
  metrics:
    - name: success-rate
      interval: 1m
      count: 5
      successCondition: result[0] >= 0.99
      failureLimit: 1
      provider:
        prometheus:
          address: http://prometheus.monitoring:9090
          query: |
            sum(rate(http_requests_total{service="my-app-canary",code!~"5.."}[2m]))
            /
            sum(rate(http_requests_total{service="my-app-canary"}[2m]))
```

If the analysis fails, the rollout aborts and shifts traffic back to the stable version automatically. The same concept is available through Flagger, service meshes (Istio, Linkerd), cloud-native options (AWS App Mesh alternatives, Cloud Run traffic splitting, Azure Container Apps revisions), and simple weighted routing at a load balancer.

**Canary prerequisites:** enough traffic for the metrics to be statistically meaningful at 5 percent, per-version metrics (label requests by version), sticky behaviour if the user experience requires it, and backward-compatible APIs and data. For low-traffic services a canary provides little signal and a blue/green with smoke tests is a better fit.

### Feature flags and progressive delivery

**Feature flags** separate deployment (code is in production) from release (users see it). Ship code dark, enable it for employees, then 1, 10, 50, 100 percent, and turn it off instantly if metrics degrade. This gives you rollback in seconds without a deploy, which matters most for mobile and for other cases where redeploying is slow.

```ts
// A minimal pattern using a provider-agnostic client (OpenFeature is a vendor-neutral standard)
import { OpenFeature } from "@openfeature/server-sdk";

const client = OpenFeature.getClient();

export async function checkout(userId: string) {
  const useNewPricing = await client.getBooleanValue(
    "new-pricing-engine",
    false,                       // safe default when the flag service is unreachable
    { targetingKey: userId }
  );
  return useNewPricing ? newPricing(userId) : legacyPricing(userId);
}
```

Flag hygiene decides whether this stays a benefit:

1. **Default to the safe value** when the flag service is unreachable.
2. **Give every flag an owner and an expiry.** Release flags should be removed after full rollout; stale flags are tech debt and untested code paths.
3. **Test both branches** in CI for important flags.
4. **Separate kinds of flags**: release flags (temporary), ops flags (kill switches, long-lived), experiment flags, and permission flags.
5. **Log flag evaluations** with the user or request identifier so incidents can be correlated with flag changes.

**Progressive delivery** is the umbrella term for combining these techniques: canary by traffic share or by cohort (internal users, then a region, then everyone), gated by automated metric analysis and flags.

### Choosing a strategy

```text
Is the service stateless and the change backward compatible?
 |-- No  --> fix compatibility first (expand/contract), or use recreate during a window
 `-- Yes
      |
      Do you need instant rollback with a clean cutover and can afford double capacity?
       |-- Yes --> blue/green
       `-- No
            |
            Is traffic high enough for per-version metrics, and do you have good SLOs?
             |-- Yes --> canary with automated analysis
             `-- No  --> rolling with strong readiness probes + feature flags for risky parts
```

Layer feature flags on top of any of them for risky behaviour changes.

### Verification after deploy

A deployment is not done when the pods are ready; it is done when the service is healthy under real traffic. Automate:

```bash
#!/usr/bin/env bash
# scripts/smoke.sh <base_url>
set -euo pipefail
base="$1"

# 1. Health endpoints
curl --fail --silent --retry 10 --retry-delay 3 --retry-all-errors "$base/healthz/ready" > /dev/null

# 2. A representative read and write path
curl --fail --silent "$base/api/v1/status" | jq -e '.version != null' > /dev/null

# 3. Version check: the running version is the one we deployed
running="$(curl --fail --silent "$base/api/v1/status" | jq -r '.commit')"
[ "$running" = "${EXPECTED_COMMIT:?}" ] || { echo "Version mismatch: $running" >&2; exit 1; }
echo "smoke ok"
```

Then wait a bake period and query your metrics system for error rate and latency before declaring success, and automatically roll back if they breach the SLO.

## Database migrations in pipelines

Schema changes are the main reason rollbacks fail. If the new code requires a column that the old code does not know about, rolling back the code leaves a database the old code may not handle; if the migration dropped a column, rolling back is impossible.

### Expand, migrate, contract

Make every change in three independently deployable steps:

```text
 Phase 1  EXPAND     add new column / table / index (nullable or with default).
                     Old code ignores it. New code may write to both old and new.
 Phase 2  MIGRATE    backfill data (in batches). Switch reads to the new structure.
                     Both versions still work.
 Phase 3  CONTRACT   after the old code is fully gone and you will not roll back,
                     drop the old column / table.
```

Each phase is a separate deployment, often days apart. At every point, the version of the code before and after the current deployment works with the current schema, which is the property that makes rollback safe.

### Safe and unsafe operations

| Operation | Safe? | Notes |
| --- | --- | --- |
| Add a nullable column | Yes | Fast in most databases |
| Add a column with a default | Depends | PostgreSQL 11 and later add constant defaults without a table rewrite; verify your engine and version |
| Add an index | Use the concurrent form | `CREATE INDEX CONCURRENTLY` in PostgreSQL; cannot run inside a transaction block |
| Add a NOT NULL constraint | Careful | Add as a `NOT VALID` check constraint, backfill, then validate, in PostgreSQL |
| Rename a column or table | No (breaking) | Add new, dual-write, backfill, switch reads, drop old |
| Drop a column | Only in contract phase | Never in the same release that stops using it |
| Change a column type | Usually rewrite | Create a new column and migrate |
| Large backfill | Batch it | Small batches with pauses; avoid long locks and replication lag |

```sql
-- Expand: safe in PostgreSQL
ALTER TABLE orders ADD COLUMN currency text;

-- Concurrent index (run outside a transaction)
CREATE INDEX CONCURRENTLY idx_orders_currency ON orders (currency);

-- Backfill in batches (repeat until no rows are updated)
UPDATE orders SET currency = 'USD'
WHERE id IN (
  SELECT id FROM orders WHERE currency IS NULL ORDER BY id LIMIT 5000
);

-- Later, add the constraint without a long lock
ALTER TABLE orders ADD CONSTRAINT orders_currency_not_null
  CHECK (currency IS NOT NULL) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_currency_not_null;
```

### Where migrations run in the pipeline

| Option | How | Pros | Cons |
| --- | --- | --- | --- |
| Separate pre-deploy job | A pipeline job runs the migration tool before the app deploy | Clear logs, explicit failure, easy to gate | Must be backward compatible with the old code |
| Kubernetes init container or Helm pre-upgrade hook | Migration runs as part of the rollout | Close coupling to the release | Every replica or hook run contends; a failure blocks pods |
| App performs migration at startup | The application migrates itself | Simple | Races between replicas, long startups, permissions too broad. Avoid in production |
| Dedicated migration job with its own credentials | A one-off job with elevated DB privileges | Least privilege for the app runtime | Extra plumbing |

Recommended: a dedicated migration job with its own credentials, run once per release before the application rollout, using the expand-only phase, with a lock so two pipelines cannot migrate simultaneously (migration tools like Flyway, Liquibase, Atlas, Alembic, golang-migrate, and Prisma Migrate use advisory locks or a migrations table for this).

```yaml
  migrate:
    needs: build
    runs-on: ubuntu-latest
    environment: production
    concurrency:
      group: migrate-production
      cancel-in-progress: false
    steps:
      - uses: actions/checkout@v4
      - name: Dry run the migration plan
        run: ./scripts/migrate.sh --env production --dry-run
      - name: Apply migrations
        run: ./scripts/migrate.sh --env production
```

### Test migrations

Run migrations against a copy of the production schema (or a recent snapshot with anonymized data) in CI, and measure duration and locks. Many outages come from a migration that was instant on a small dev database and held a lock for twenty minutes on a large table. Add a linter for dangerous operations (for example `squawk` for PostgreSQL migrations, or the safety checks in Atlas); verify current tools and rules.

## Rollbacks

### Make rollback a first-class, tested operation

An untested rollback path is a hope. Define, per service:

| Question | Answer to document |
| --- | --- |
| How do we roll back the application? | Command or workflow, and expected duration |
| What is the maximum safe rollback window? | Until contract-phase migrations or incompatible data changes |
| Who can trigger it? | On-call, any engineer with a break-glass role |
| How do we know it worked? | Metrics, smoke tests |
| What about data written by the new version? | Compatibility rules, or a forward-fix plan |

### Rollback versus roll forward

- **Roll back** when the previous artifact is known good and compatible with current data. It is the fastest way to restore service.
- **Roll forward** when rollback is unsafe (a contract migration ran, data was transformed) or when the fix is trivial and your pipeline is fast enough. A pipeline that deploys a one-line fix in 10 minutes makes roll forward a real option.
- **Feature flag off** when the change was behind a flag: the fastest of all.

### Mechanics

```bash
# Kubernetes Deployment
kubectl rollout undo deployment/my-app
kubectl rollout status deployment/my-app --timeout=180s

# Argo Rollouts
kubectl argo rollouts abort my-app
kubectl argo rollouts undo my-app

# Helm
helm history my-app
helm rollback my-app 41 --wait --timeout 5m

# By digest, with GitOps: revert the commit that updated the image reference
git revert <commit-that-bumped-the-image>
git push
```

In a GitOps flow (Argo CD or Flux) a rollback is a Git revert; the controller reconciles the cluster. That also leaves an audit trail.

### Automated rollback

Wire the deploy job to metrics: after a bake period, query error rate and latency and roll back without a human if thresholds are breached. Argo Rollouts analysis, Flagger, and cloud deploy services provide this; a simple custom version is a post-deploy job that queries Prometheus or your APM API and calls the rollback script on failure. Make the thresholds conservative at first and alert when auto-rollbacks happen so someone investigates.

### Rollback for mobile and other hard-to-recall artifacts

Mobile apps, desktop apps, and firmware cannot be recalled. Compensate with feature flags and remote config, server-side compatibility for old clients, staged rollouts, and a minimum-supported-version check. See the [mobile CI/CD post](https://www.derar.dev/blog/mobile-ci-cd-fastlane-github-actions-app-store-play-store-2026) for specifics.

## Preview environments

A **preview environment** is a temporary, isolated deployment of a pull request, so reviewers, designers, and QA can try a change without checking it out locally.

### Benefits and costs

Benefits: faster review, earlier feedback from non-engineers, safe place for end-to-end tests against a real deployment. Costs: infrastructure per PR, data seeding, secrets and third-party integrations, and cleanup of forgotten environments.

### Patterns

| Pattern | How | Good for | Watch out for |
| --- | --- | --- | --- |
| Platform previews | Vercel, Netlify, Cloudflare Pages, Render, Fly.io create URLs per PR | Frontends and simple backends | Backing service access and cost |
| Namespace per PR on Kubernetes | Create a namespace, install the Helm chart with a PR-specific host | Microservices | Resource quotas, cleanup, DNS and TLS wildcard |
| Ephemeral cloud stacks | Provision a small stack with IaC per PR | Full-stack isolation | Provisioning time and cost; use cheap tiers |
| Shared preview with feature routing | One shared environment, route to PR builds by header or subdomain | Many services, few changed | Complexity of routing; data collisions |

### A Kubernetes namespace-per-PR example

```yaml
name: preview

on:
  pull_request:
    types: [opened, synchronize, reopened, closed]

permissions:
  contents: read
  pull-requests: write
  id-token: write

concurrency:
  group: preview-${{ github.event.pull_request.number }}
  cancel-in-progress: true

jobs:
  deploy:
    if: github.event.action != 'closed'
    runs-on: ubuntu-latest
    environment:
      name: preview-pr-${{ github.event.pull_request.number }}
      url: https://pr-${{ github.event.pull_request.number }}.preview.example.com
    steps:
      - uses: actions/checkout@v4
      - name: Deploy preview
        env:
          PR: ${{ github.event.pull_request.number }}
          SHA: ${{ github.event.pull_request.head.sha }}
        run: |
          helm upgrade --install "app-pr-$PR" ./chart \
            --namespace "preview-pr-$PR" --create-namespace \
            --set image.tag="$SHA" \
            --set ingress.host="pr-$PR.preview.example.com" \
            --set resources.requests.cpu=50m --set replicaCount=1 \
            --wait --timeout 5m

  cleanup:
    if: github.event.action == 'closed'
    runs-on: ubuntu-latest
    steps:
      - name: Delete preview
        env:
          PR: ${{ github.event.pull_request.number }}
        run: kubectl delete namespace "preview-pr-$PR" --ignore-not-found
```

Notes: the workflow uses `pull_request`, so for forks it will not have cluster credentials; that is the secure default. For fork previews, build in an unprivileged workflow and deploy from a separate privileged workflow that treats the build as untrusted (see the hardening post). The PR number goes through `env:` rather than being interpolated into a script. Always add a **TTL job** that deletes previews older than a few days, because the `closed` event can be missed.

### Data in previews

Seed with synthetic data or a small anonymized snapshot, never production data. Use per-preview databases or schemas created by the same migration job as other environments, which doubles as a continuous test of your migrations from scratch.

## Budgeting speed and cost

### Set budgets and enforce them

Budgets turn "make it faster" into a decision. Example:

| Budget | Value | Enforcement |
| --- | --- | --- |
| PR feedback (lint, unit, build) | under 10 minutes at p90 | Dashboard, alert on breach for a week |
| Full PR pipeline including integration tests | under 20 minutes at p90 | Same |
| Time from merge to deployed in staging | under 15 minutes | Same |
| Flake rate | under 1 percent | Fail the quality gate |
| CI spend per engineer per month | A figure agreed with finance | Monthly review |

When a budget is breached, the default response is to remove or speed up work, not to raise the budget.

### Cost levers

1. **Cancel superseded runs** (`concurrency` with `cancel-in-progress` on PRs). Often the largest single saving.
2. **Path filters and affected-only builds.**
3. **Cache aggressively** (see the caching section), measuring hit rate.
4. **Right-size runners.** Benchmark standard versus larger runners: a runner costing twice per minute that halves the duration is cost-neutral and faster. Do the measurement; the answer varies by workload. Verify current runner pricing on the provider's page.
5. **Use Linux where possible.** macOS and Windows minutes cost more.
6. **Timeouts on every job** (`timeout-minutes`) so a hung job does not burn six hours.
7. **Artifact and cache retention.** Short retention for artifacts you do not need long-term; storage is billed.
8. **Run heavy suites at the right frequency**: full end-to-end and matrix builds on main or nightly; a smoke subset on PRs.
9. **Self-hosted or ephemeral autoscaled runners** at high volume, accepting the operational and security burden (see the hardening post).
10. **Skip CI for docs-only changes** with path filters, but keep required checks satisfied through a gate job.

### A tiny cost model

```text
monthly_cost = runs_per_month x avg_minutes_per_run x per_minute_rate

Example (illustrative numbers only):
  200 PRs x 5 pushes each = 1000 runs
  1000 runs x 12 min x 0.008 USD/min = 96 USD   (Linux)
  If 30 percent of runs also use 15 macOS minutes at 0.08 USD/min:
  300 x 15 x 0.08 = 360 USD
```

The rates above are placeholders to show the arithmetic; look up the current rates for your provider and plan.

### Make the data visible

Publish a weekly dashboard: p50 and p90 duration per workflow, queue time, cache hit rate, flake rate, minutes consumed, and cost. Review the top three slowest jobs in an engineering meeting once a month and assign one improvement to each.

## Putting it together: a reference pipeline

```text
PR opened
  |
  +--> [plan]  compute affected projects (turbo/nx), restore caches
  |      |
  |      +--> [lint+typecheck]   (affected, remote cache)       ~2 min
  |      +--> [unit tests x N]   (sharded, balanced by time)     ~4 min
  |      +--> [build image]      (BuildKit cache, push by SHA)   ~3 min
  |      +--> [integration]      (containers via compose)        ~6 min
  |
  +--> [preview deploy]  namespace per PR, smoke tests           ~3 min
  |
  +--> [ci-gate]  required check aggregating the above

Merge queue (optional)  --> re-run fast checks on merged state

main
  |
  +--> [build once]   immutable image + SBOM + provenance
  +--> [deploy staging] by digest --> [smoke + e2e shards]
  +--> [approval or automated gate]
  +--> [migrate: expand only]
  +--> [deploy production] canary 5% -> 25% -> 100% with analysis
  +--> [post-deploy verify] SLO check; auto-rollback on breach
```

A workflow skeleton for the main flow in GitHub Actions:

```yaml
name: main

on:
  push:
    branches: [main]

permissions:
  contents: read

concurrency:
  group: main-pipeline
  cancel-in-progress: false

jobs:
  build:
    uses: ./.github/workflows/build.yml          # builds once, outputs digest
    permissions:
      contents: read
      packages: write
      id-token: write
      attestations: write

  staging:
    needs: build
    uses: ./.github/workflows/deploy.yml
    with:
      environment: staging
      image-digest: ${{ needs.build.outputs.digest }}
    secrets: inherit

  e2e:
    needs: staging
    uses: ./.github/workflows/e2e.yml
    with:
      base-url: https://staging.example.com

  production:
    needs: [build, e2e]
    uses: ./.github/workflows/deploy.yml
    with:
      environment: production
      image-digest: ${{ needs.build.outputs.digest }}
    secrets: inherit
```

Reusable workflows keep each stage testable on its own. Prefer passing secrets explicitly instead of `secrets: inherit` where you can.

## Lab: cut a slow pipeline in half

Use this procedure on a real repository. Expect a first pass to take an afternoon.

1. **Baseline.** Record p50 and p90 duration, queue time, and cost for the last 50 runs of the main PR workflow.
2. **Map the critical path.** List jobs and steps with durations; mark the longest chain.
3. **Cancel superseded runs** with `concurrency`.
4. **Fix dependency installs.** Turn on the setup action's cache; make sure the lockfile is committed and installs are frozen (`npm ci`, `pnpm install --frozen-lockfile`, `pip install --require-hashes` where feasible).
5. **Fix the Docker build.** Reorder the Dockerfile, add `.dockerignore`, add `cache-from` and `cache-to`.
6. **Parallelize tests.** Use all cores locally in the job first, then shard to as many machines as pays off. Stop when per-shard setup time approaches the test time.
7. **Add affected-only execution** if you have a monorepo; add a nightly full run.
8. **Introduce a remote task cache** and verify hit rate on a second run of the same commit (it should be close to 100 percent).
9. **Quarantine flaky tests** with owners and deadlines; reduce retries to failed tests only.
10. **Re-measure** and record the savings; write down what the next bottleneck is.

Checklist for each change: Does the pipeline still fail on real bugs? (Test it by introducing a deliberate failure.) Is the cache keyed so it invalidates when it should? Does the change work for forked pull requests? Is it documented?

## Where this usually goes wrong

1. Optimizing the wrong job, shaving time off something that is not on the critical path.
2. Cache keys that never change (`key: deps`), serving stale dependencies forever, or keys that always change, so nothing ever hits.
3. Caching `node_modules` or build outputs across lockfile changes and shipping stale code.
4. Rebuilding per environment, so the tested artifact is not the shipped one.
5. Mutable image tags in deployments (`latest`), making rollbacks and audits ambiguous.
6. Running every test on every commit, or conversely running too few and finding bugs only in staging.
7. Global job retries that hide flaky tests and double the bill.
8. Sharding by test count rather than by duration, leaving one slow shard that determines the total.
9. Skipped required checks that block merges because a path filter prevented the job from reporting. Use a gate job.
10. Migrations in the same release as the code that depends on them with no backward compatibility, making rollback impossible.
11. Dropping columns in the same release that stops using them.
12. Canary releases without per-version metrics, so there is nothing to analyze.
13. Feature flags that never get removed, accumulating untested branches.
14. Approval gates with no automation behind them, where a human clicks "approve" without looking at any data.
15. Preview environments that are never garbage collected.
16. Untrusted code with write access to the remote cache, enabling cache poisoning.
17. No timeouts, so a hung job consumes hours of paid minutes.
18. No full build on main when using affected-only builds, so graph errors go unnoticed.

## When not to do this

- A small repository with a 3-minute pipeline. Remote caches, sharding, and affected-only builds add complexity for little gain. Fix flakiness and keep it simple.
- A monorepo tool for a few packages. Path filters and workspace scripts may be enough; adopt Nx, Turborepo, or Bazel when the pain is real and measured.
- Canary and service mesh for low-traffic internal tools. You will not get statistical signal; use rolling updates and feature flags.
- Blue/green for stateful systems you cannot duplicate cheaply (large databases, licensed software). Use rolling with careful compatibility, or schedule maintenance windows.
- Automatic production deploys on every merge if your tests and observability cannot be trusted yet. First raise test quality and add smoke tests and SLO checks; continuous deployment is a destination, not a starting point. Continuous delivery with a one-click, well-rehearsed release is a perfectly good place to stay.
- Aggressive test-result caching unless every test declares its inputs. A stale pass is worse than a slow run.
- Preview environments for every PR if your system needs heavy infrastructure; consider previews on demand (by label) instead.
- Over-sharded tests: if each shard spends more time on setup than on tests, reduce the shard count.

## Questions that come up

**Should I use GitHub Actions cache or a remote cache like Turborepo or Nx Cloud?**
Use both for different layers. Actions cache for dependency downloads and toolchains; a remote task cache for build and test outputs, because it is shared between CI and developer machines and keyed by task inputs.

**How many shards should I use?**
Enough that the slowest shard finishes near your target and per-shard setup stays small relative to test time. Start with four, measure, adjust. Past the point of diminishing returns you only pay more.

**Is blue/green or canary better?**
Neither universally. Blue/green gives a clean, instant switch and rollback; canary limits blast radius using real traffic and metrics. Many teams use blue/green for simplicity and add canary analysis for the services where an outage is most expensive.

**How do I make rollbacks safe with database changes?**
Use expand, migrate, contract. As long as the previous version of the code works with the current schema, rollback is a code deployment. Contract steps are the point of no return, so do them late and separately.

**Where do AI agents fit into a pipeline?**
Agents that open pull requests should go through the same pipeline gates as humans. Give them read-only access to pipeline logs and metrics so they can diagnose failures, but keep production deploys and secrets behind environment approvals. Provide structured pipeline outputs (JUnit XML, JSON summaries, clear job names) so agents and humans can both parse failures quickly.

**What about GitOps?**
GitOps (Argo CD, Flux) fits the build-once, promote-by-reference model well: CI builds the artifact and opens a commit that updates the image reference in a deployment repository, and the controller reconciles the cluster. Rollback is a revert, and the Git history is the audit log.

## Sources and docs

- DORA, the research programme behind the four key metrics: [dora.dev](https://dora.dev/)
- Google SRE book, chapter on release engineering: [sre.google/sre-book/release-engineering](https://sre.google/sre-book/release-engineering/)
- GitHub Actions caching: [docs.github.com/actions/using-workflows/caching-dependencies-to-speed-up-workflows](https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows)
- Docker build cache backends: [docs.docker.com/build/cache/backends](https://docs.docker.com/build/cache/backends/)
- Turborepo remote caching: [turborepo.com/docs/core-concepts/remote-caching](https://turborepo.com/docs/core-concepts/remote-caching)
- Nx affected and remote caching: [nx.dev/ci/features/affected](https://nx.dev/ci/features/affected)
- Playwright sharding: [playwright.dev/docs/test-sharding](https://playwright.dev/docs/test-sharding)
- GitLab CI `parallel`: [docs.gitlab.com/ee/ci/yaml](https://docs.gitlab.com/ee/ci/yaml/)
- Argo Rollouts: [argoproj.github.io/rollouts](https://argoproj.github.io/rollouts/)
- Flagger progressive delivery: [flagger.app](https://flagger.app/)
- OpenFeature, vendor-neutral feature flagging: [openfeature.dev](https://openfeature.dev/)
- Related on this site: [GitHub Actions Security Hardening in 2026](https://www.derar.dev/blog/github-actions-security-hardening-2026), [Software Supply Chain Security: SBOMs, SLSA, and Sigstore](https://www.derar.dev/blog/software-supply-chain-slsa-sigstore-sbom-2026), [Docker Complete Course](https://www.derar.dev/blog/docker-complete-course-2026), and [Mobile CI/CD with Fastlane and GitHub Actions](https://www.derar.dev/blog/mobile-ci-cd-fastlane-github-actions-app-store-play-store-2026)
