Platform Engineering · Lesson 191

Trunk-Based Development and CI Pipeline Architecture: Fast, Cached, and Build Once

Fast, safe delivery rests on two habits. Trunk-based development: everyone integrates small changes into one main branch at least daily, behind feature flags when unfinished, instead of long-lived branches that merge painfully. And a CI pipeline built for speed and trust: a test pyramid (many fast unit tests, fewer integration tests, very few end-to-end), parallel jobs, caching of dependencies and build layers, and build once, promote many: one immutable, signed artifact moves from test to staging to production, never rebuilt. Infrastructure changes get the same treatment, with tests and policy gates. This lesson follows one change from commit to a production-ready artifact, and shows two failures: a release branch that took a week to merge, and an artifact rebuilt for production that was not the one tested.

Difficulty: Advanced · Know this first: Lesson 98, Lesson 186

What you will learn

By the end of this lesson you can work at four levels:

This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up minutes from commit to an artifact approved for production. It is a worked example, not a measurement. The branching and promotion hops are where delivery slows down or loses its guarantees.

Try it: tune the delivery path

Pick the branching model, how artifacts reach production, and the state of the pipeline's caches and tests.

11 minpipeline
2.5 hcommit to production-ready
yesproduction runs what was tested?

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Delivery engineering grows in four levels: working on trunk, building a good pipeline, making it fast, and running promotion and gates as a platform.

Basic — Work on trunk

At the basic level you integrate small changes often.

  • Branches that live hours, not weeks; small pull requests.
  • Feature flags for unfinished work.
  • Reading a pipeline result and fixing a red build first.

Where it breaks: a "quick" branch that grows for three weeks.

Try it: Basic

Your feature needs two weeks. How do you keep integrating daily?

Now do it: Wrap your next feature in a flag.

Intermediate — Build a good pipeline

At the intermediate level the pipeline is trustworthy.

  • A test pyramid; contract tests between services; Testcontainers for real dependencies.
  • Flaky tests tracked and quarantined with owners.
  • One artifact per commit, pinned inputs, signed, with an SBOM.

Try it: Intermediate

A test fails one run in twenty. What do you do?

Now do it: Find your flakiest test from CI history.

Advanced — Make it fast

At the advanced level the pipeline is fast without cutting corners.

  • Parallel stages and test sharding by timing; affected-target builds in monorepos.
  • Dependency, layer, and remote build caches keyed on every input.
  • Runner capacity and queue time monitored.

Try it: Advanced

The pipeline has 40 minutes of work but takes 40 minutes. What is the quickest win?

Now do it: Draw your pipeline's critical path.

Master — Promotion and gates as a platform

At the master level delivery is a platform capability.

  • Promotion by digest through GitOps, with environment gates and approvals as code.
  • Infrastructure tested like code (terraform test, Terratest, policy gates).
  • Signature and provenance verified at admission; DORA metrics tracked.

Trade-off: more gates add safety and wait; automate them so they cost seconds, and keep approvals for what really needs a person.

Try it: Master

How do you prove production runs the artifact that passed staging?

Now do it: Compare the digests in staging and production.

Go deeper

A CI pipeline with parallel jobs, caching, one build, and promotion by digest (GitHub Actions syntax; the same structure works in GitLab CI or Jenkins). Pin actions to versions you have reviewed.

jobs:
  lint:   {runs-on: ubuntu-latest, steps: [{uses: actions/checkout@v4}, {run: make lint}]}
  unit:
    runs-on: ubuntu-latest
    strategy: {matrix: {shard: [1, 2, 3, 4, 5, 6]}}
    steps:
      - uses: actions/checkout@v4
      - uses: actions/cache@v4
        with: {path: ~/go/pkg/mod, key: go-${{ hashFiles('go.sum') }}}
      - run: make test SHARD=${{ matrix.shard }} SHARDS=6
  build:
    needs: [lint, unit]
    runs-on: ubuntu-latest
    outputs: {digest: ${{ steps.push.outputs.digest }}}
    steps:
      - uses: actions/checkout@v4
      - uses: docker/setup-buildx-action@v3
      - id: push
        uses: docker/build-push-action@v6
        with:
          push: true
          tags: registry.example.com/payments:${{ github.sha }}
          cache-from: type=registry,ref=registry.example.com/payments:buildcache
          cache-to: type=registry,ref=registry.example.com/payments:buildcache,mode=max
      - run: cosign sign --yes registry.example.com/payments@${{ steps.push.outputs.digest }}
  promote-staging:
    needs: build
    runs-on: ubuntu-latest
    steps:   # a commit to the GitOps repository changes the digest; Argo CD or Flux deploys it
      - run: ./promote.sh staging registry.example.com/payments@${{ needs.build.outputs.digest }}

Branching models compared: trunk-based (short branches, flags, continuous delivery) suits services deployed often; GitHub flow (feature branches to main, deploy from main) is trunk-based with pull requests; GitFlow (develop, release, and hotfix branches) suits versioned products shipped to customers on a schedule, at the cost of slower integration.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. "The same code" that was not the same artifact.

Timeline

  • Monday 10:00A change is built, tested, and soaked in staging. The image uses FROM base:3 and an unpinned transitive dependency.
  • Monday 16:00The base image's floating tag moves to a new OS release; the dependency publishes a new major version.
  • Tuesday 09:00The production job rebuilds from the git tag. The new image passes smoke tests and starts failing TLS handshakes with one payment partner under real traffic.
  • Tuesday 10:05Rolled back. It takes the afternoon to find that production ran a different OS library and dependency than staging.

What changed after

Images are built once per commit from base images pinned by digest and lock files; promotion changes only the digest in each environment's GitOps configuration; admission verifies the signature; and the staging and production digests are compared in every release check.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: Linux with Git, Docker, and Python 3.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. How long do branches live in a repository? List local branches by last commit date.

    Read-only

    git for-each-ref --sort=committerdate refs/heads/ --format="%(committerdate:short)  %(refname:short)"

    Options: --sort=committerdate orders by the last commit; run it in any repository.

    Expect: Branches with their last commit date; anything weeks old is a merge waiting to hurt. Read-only.

  2. Build the same Dockerfile twice with a floating base tag, and compare digests.

    Potentially destructive

    mkdir -p ~/labs/ci && cd ~/labs/ci
    printf "FROM alpine:3\nRUN echo built > /built.txt\n" > Dockerfile
    docker build -q -t ci-demo:a . && docker build -q --no-cache -t ci-demo:b .
    docker image inspect ci-demo:a ci-demo:b --format "{{.Id}}"

    Options: --no-cache forces a real rebuild, as a production job rebuilding from source would.

    Expect: Two different IDs: even the same Dockerfile gives a different artifact when rebuilt (timestamps, and any newer base). Build once, promote the digest.

    Clean up: docker rmi ci-demo:a ci-demo:b; rm -rf ~/labs/ci.

  3. Pin the base image by digest so rebuilds start from the same bytes.

    Reversible

    docker pull -q alpine:3 >/dev/null
    docker image inspect alpine:3 --format "{{index .RepoDigests 0}}"

    Expect: A reference like alpine@sha256:…: use that in FROM so the base never changes under you.

2. Python: pipeline.py

This program models a pipeline as jobs with durations and dependencies. It compares the total work with the critical path (what you actually wait for) when jobs run serially, in parallel, and with tests sharded and caches warm. Then it shows why cache keys must include every input: a key on the package file alone serves a stale result after the lock file changes. Save it as pipeline.py, then run it.

# pipeline.py
import hashlib

JOBS = {  # name: (minutes cold, minutes warm with caches, depends on)
    "lint": (2, 1, []), "unit": (24, 9, []), "integration": (14, 8, []),
    "image": (18, 5, ["lint", "unit"]), "iac-checks": (3, 2, []), "e2e": (12, 12, ["image", "integration"]),
}

def critical_path(warm, shards=1):
    finish = {}
    def done(j):
        if j not in finish:
            cold, hot, deps = JOBS[j]
            t = hot if warm else cold
            if j in ("unit", "integration"):
                t = t / shards
            finish[j] = max((done(d) for d in deps), default=0) + t
        return finish[j]
    return max(done(j) for j in JOBS)

total_cold = sum(c for c, _, _ in JOBS.values())
print(f"serial, cold caches:            {total_cold:5.1f} min")
print(f"parallel, cold caches:          {critical_path(False):5.1f} min")
print(f"parallel, warm caches:          {critical_path(True):5.1f} min")
print(f"parallel, warm, tests 6 shards: {critical_path(True, shards=6):5.1f} min")
print()

def key(*inputs):
    return hashlib.sha256("|".join(inputs).encode()).hexdigest()[:12]
package_json = '{"deps": {"lib": "^2.1.0"}}'
lock_before = "lib 2.1.0"
lock_after = "lib 2.4.0"                      # the lock file moved; package.json did not
print("cache key on package.json only:", key(package_json), "->", key(package_json), "(same key: stale dependencies served)")
print("cache key on every input:      ", key(package_json, lock_before), "->", key(package_json, lock_after), "(new key: rebuilt)")

Run it, and you should see this output:

$ python3 pipeline.py
serial, cold caches:             73.0 min
parallel, cold caches:           54.0 min
parallel, warm caches:           26.0 min
parallel, warm, tests 6 shards:  18.5 min

cache key on package.json only: 2fe2dac209c4 -> 2fe2dac209c4 (same key: stale dependencies served)
cache key on every input:       9f794e1f48e2 -> d5f7f713a942 (new key: rebuilt)

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/trunk-based-development-and-ci-pipeline-architecture && cd ~/labs/trunk-based-development-and-ci-pipeline-architecture) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "Trunk-Based Development and CI Pipeline Architecture: Fast, Cached, and Build Once", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'How long do branches live in a repository? List local branches by last commit date.'
  'Build the same Dockerfile twice with a floating base tag, and compare digests.'
  'Pin the base image by digest so rebuilds start from the same bytes.'
)

step_1() {
git for-each-ref --sort=committerdate refs/heads/ --format="%(committerdate:short)  %(refname:short)"
}

step_2() {
mkdir -p ~/labs/ci && cd ~/labs/ci
printf "FROM alpine:3\nRUN echo built > /built.txt\n" > Dockerfile
docker build -q -t ci-demo:a . && docker build -q --no-cache -t ci-demo:b .
docker image inspect ci-demo:a ci-demo:b --format "{{.Id}}"
}

step_3() {
docker pull -q alpine:3 >/dev/null
docker image inspect alpine:3 --format "{{index .RepoDigests 0}}"
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

A team ships monthly from release branches, their pipeline takes 55 minutes, and production images are rebuilt from tags. Design their move to trunk-based development and a build-once pipeline.

Clarifying questions to ask

How do you move from release branches to trunk without a big bang? What does the test pyramid look like, and how do you handle flaky tests? How do you make the pipeline fast? How are artifacts built, stored, and promoted? What gates apply to production and to infrastructure?

Rough sizing

Say 30 engineers, one monorepo with 12 services, 55-minute pipelines, 400 end-to-end tests, and monthly releases.

Shape of the answer

Introduce feature flags, then shorten branch lifetimes to under a day with small pull requests; rebalance tests toward unit and contract tests, keep about 20 end-to-end journeys, quarantine flakes with owners; affected-target builds, parallel jobs, test sharding, and remote caches to bring the critical path near 10 minutes; one image per service per commit from digest-pinned bases and lock files, signed with SBOM and provenance, in a registry with immutable tags and public proxies; GitOps promotion by digest with staging soak and production approval as code; terraform test and policy gates for infrastructure; DORA metrics to track the change.

Trade-offs to name

Feature flags add code paths that must be cleaned up; fewer end-to-end tests need strong contract tests; caches speed things up and need careful keys; promotion by digest needs configuration kept out of images.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
Long-lived release branchHop 1: Branching modelBreaksEach feature lives on its own branch for three weeks and merges into a release branch, which then merges to main. The final merge has 140 conflicts across shared modules.
Rebuilt for productionHop 8: PromotionBreaksThe production job rebuilds the image from the git tag. Since the test build, the base image's floating tag moved to a new OS release and an unpinned transitive dependency published a new major version.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Branching model → Commit → Test pyramid → Parallel jobs → Caching → Immutable artifact → Artifact repository → Promotion → Policy gates. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.

Last updated . Next review due by November 2027. Found something out of date? Tell me.

Saved on this device, in this browser.
Next in this series · Lesson 192
Progressive Delivery, Safe Database Migrations, and DORA Metrics

Shipping safely to production is about limiting how much can go wrong at once and how fast you can undo it. Progressive delivery exposes a release gradually (blue/green switches, canary steps, feature flags, and rings of users…

Go to Lesson 192 →

Or browse the full course from the Lessons index.