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
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.
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.
Pick the branching model, how artifacts reach production, and the state of the pipeline's caches and tests.
Three questions. No score is saved anywhere — this is just you against the material.
Delivery engineering grows in four levels: working on trunk, building a good pipeline, making it fast, and running promotion and gates as a platform.
At the basic level you integrate small changes often.
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.
At the intermediate level the pipeline is trustworthy.
Try it: Intermediate
A test fails one run in twenty. What do you do?
Now do it: Find your flakiest test from CI history.
At the advanced level the pipeline is fast without cutting corners.
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.
At the master level delivery is a platform capability.
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.
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.
This is a composite of a failure pattern that keeps repeating; the details are illustrative. "The same code" that was not the same artifact.
FROM base:3 and an unpinned transitive dependency.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.
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.
Type each one, read what it prints, and compare it with the note above it.
How long do branches live in a repository? List local branches by last commit date.
git for-each-ref --sort=committerdate refs/heads/ --format="%(committerdate:short) %(refname:short)"
Build the same Dockerfile twice with a floating base tag, and compare digests.
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}}"Pin the base image by digest so rebuilds start from the same bytes.
docker pull -q alpine:3 >/dev/null
docker image inspect alpine:3 --format "{{index .RepoDigests 0}}"pipeline.pyThis 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)
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
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
mkdir, echo, cd, Redirection, If...Else.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.
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?
Say 30 engineers, one monorepo with 12 services, 55-minute pipelines, 400 end-to-end tests, and monthly releases.
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.
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.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| Long-lived release branch | Hop 1: Branching model | Breaks | Each 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 production | Hop 8: Promotion | Breaks | The 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. |
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.