Skip to content
Index Ai Academy
Phase 11 · Shipping

CI/CD pipelines

Test every change automatically, and ship with gates, flags and rollbacks.

About 40 minutes · Versions checked November 2026 · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers9

First principles

How can a test result tell you exactly what is being deployed?

CI checks a particular revision and can produce an immutable artifact. CD promotes that artifact through release gates so the deployed copy matches what was checked.

  1. Starting point

    Revision R passes tests and produces image I

  2. What changes

    Promote the exact image digest through staging

  3. Result

    Production runs the artifact tied to R

Compare all three steps
  1. Starting point

    Revision R passes tests and produces image I

  2. What changes

    Promote the exact image digest through staging

  3. Result

    Production runs the artifact tied to R

Complete and reverse the trace

Given Revision R passes tests and produces image I and Production runs the artifact tied to R, write down the missing step that connects them.

Compare with the worked step

Promote the exact image digest through staging

Now take Promote the exact image digest through staging and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Revision R passes tests and produces image I. Check that your implementation produces the result shown above.

Try it on a new case

What should a rollback pick if the new revision causes errors?

Show worked reasoning

Use the digest of a previously healthy artifact and verify recovery. Rebuilding the old source may pick up different dependencies or configuration.

Run, change, and build

Check this when debugging. Rebuilding the artifact for production after testing another build.

Trace the cause · Release, metrics, and recovery
  1. Mark the baseline revision, affected population, and metric that would justify intervening.
  2. Change a release or operating condition. Compare the observed metric to the baseline and identify a check that proves recovery.
  3. Try the same reasoning on this case. What should a rollback pick if the new revision causes errors?

Why it matters

On a professional team, nobody's change reaches users until a machine has built it, tested it and checked it, every time. That machine is the CI/CD pipeline. It catches mistakes in minutes instead of in production, lets many people change one codebase safely, and makes shipping routine rather than scary. Teams that deploy many times a day aren't braver; they have better pipelines.

What you'll be able to do

  • Explain continuous integration, delivery and deployment, and what each one guarantees
  • Read and write a GitHub Actions workflow with jobs, dependencies, a matrix and secrets
  • Plan a pipeline as stages of jobs from their dependencies, and skip jobs whose inputs failed
  • Separate deploying from releasing with feature flags and stable percentage rollouts
Quick check
A teammate's change breaks a test. On a team with CI, when do they find out?
  1. Never, unless they happen to run the tests themselves
  2. Within minutes, when the pipeline runs the tests on their change
  3. When a customer reports the bug weeks later
  4. At the end of the month, in a review meeting
Show the answer

Within minutes, when the pipeline runs the tests on their change

CI builds and tests every change automatically before it can merge, so problems surface while the change is fresh in the author's mind. CD then ships what passes.

The idea: a commit becomes a tested image, then a release

This lesson rests on Testing with pytest (a test is a check that fails loudly) and Containers and deployment (the image a pipeline builds and ships). A pipeline is those two ideas run by a machine on every change.

Three terms

Picture a car factory. Each part gets checked as it's fitted, finished cars wait in the lot until someone orders them released, and at some factories they roll straight out to dealers. Software has the same three stages:

  • Continuous integration (CI): every push and pull request runs the checks: formatting, linting (automatic checks for suspicious code), type checks, tests, a build. A change merges only when they pass.
  • Continuous delivery: every merged change is ready to deploy; a person clicks to release.
  • Continuous deployment: every merged change deploys automatically, if all checks pass.

Branch protection makes it binding: the main branch only accepts pull requests whose required checks pass, and often a review too.

Quick check
From the lesson on pytest: one test can run once for each row of cases, and the boundary row is the one that matters. A teammate changed >= to >. What does this print when CI runs the cases?
def discount(subtotal):
    return 0.1 if subtotal > 100 else 0.0

cases = [(99, 0.0), (100, 0.1), (150, 0.1)]
failed = [subtotal for subtotal, expected in cases if discount(subtotal) != expected]
print(failed, "merge" if not failed else "blocked")
  1. [] merge
  2. [100] blocked
  3. [100] merge
  4. [99, 100] blocked
Show the answer

[100] blocked

Only the row at exactly 100 fails, and that is enough to block the merge. The other rows would never have noticed the change. Tests protect the main branch only if something runs them on every push, which is the first of this lesson's three terms.

Quick check
In the workflow above, the lint job fails. What happens to test and deploy?
  1. They're skipped, because they need lint (directly or through test)
  2. Only deploy runs, since it doesn't depend on the lint job
  3. The workflow retries the lint job until it finally passes
  4. They run anyway, since each job in a workflow is independent
Show the answer

They're skipped, because they need lint (directly or through test)

needs builds a dependency graph. A failure skips everything downstream.

Try it now

Pick a case and step. In the first, one image travels from build to production. In the third, a rollback is the same deploy with the previous tag.

Designing a good pipeline

  • Fast first. You check that a lamp is plugged in before you take it apart. Run quick checks (lint, types) before slow ones, so obvious mistakes fail in a minute.
  • Parallel where possible. Jobs with no dependency between them run at the same time.
  • Cache dependencies, so each run doesn't download the world.
  • Build once, promote. Build one image, test it, then deploy that same image to staging and production. Rebuilding for production means shipping something you didn't test.
  • Treat flaky tests as bugs. A smoke alarm that goes off at random soon gets ignored, and a test that fails at random teaches people to ignore red builds. Find the cause, often timing or shared state, and fix it.
  • Keep secrets scoped. Give each job only the secrets it needs, and never print them.

For AI features, add an eval job when prompts or models change: run the eval set and fail if scores drop below a threshold. Keep it small enough to be cheap, and run the full suite before releases.

In your own words
What do continuous integration, delivery and deployment each guarantee, and why does a failed job skip the ones after it?

Write a sentence or two, then compare it with a good answer in the lesson.

In code: stage planning, path filters and stable rollouts

A pipeline is a few small pieces of logic: the order jobs can run in, the jobs a change needs, and the answer a flag gives one user. Each is a few lines of Python.

Worked example

Why fast checks go first

Say most failures are caught by lint or types. Compare the wait before you hear about a broken change, with slow jobs first and fast jobs first.

# name, minutes, share of failures caught
jobs = [("lint", 1, 0.5), ("types", 2, 0.3), ("tests", 12, 0.2)]

def expected_wait(order):
    wait, spent = 0, 0
    for name, minutes, share in order:
        spent += minutes
        wait += spent * share
    return wait

print("fast first:", round(expected_wait(jobs), 1), "minutes")
print("slow first:", round(expected_wait(jobs[::-1]), 1), "minutes")
It runs right here in your browser, with nothing to install.

Same jobs, same total time when everything passes, yet a broken change gets its answer about three times sooner. Those minutes add up across a team, and people stop context-switching while they wait.

Drill

How long will the pipeline take?

Jobs in the same stage run side by side; stages run one after another. Write pipeline_minutes(stages): stages is a list of lists of job durations in minutes. Return the total: the sum, over stages, of each stage's longest job.

def pipeline_minutes(stages):
    return sum(sum(stage) for stage in stages)


print(pipeline_minutes([[1, 2], [8, 3, 5], [4]]))
In the lesson, your code is checked as you write it.
Drill

Run only the jobs a change needs

Write jobs_to_run(changed, filters): filters maps job names to glob patterns (matched with fnmatch.fnmatch). Return the sorted names of jobs with at least one pattern that matches at least one changed path.

from fnmatch import fnmatch

FILTERS = {
    "docs": ["docs/*", "*.md"],
    "api-tests": ["api/*", "requirements.txt"],
    "web-tests": ["web/*", "package.json"],
}


def jobs_to_run(changed, filters):
    return sorted(filters)


print(jobs_to_run(["api/routes.py", "README.md"], FILTERS))
In the lesson, your code is checked as you write it.

Feature flags: deploy is not release

An electrician can wire a new lamp today, and you can flip the switch next week. A feature flag is that switch, in your code: if flags.enabled("new_checkout", user):. The code ships turned off, then you turn it on for staff, then 5% of users, then everyone. If something breaks, you turn it off in seconds, with no deploy.

In plain words: deploying puts the code on the servers. Releasing lets people use it. Flags let you do those at different times.

For percentage rollouts, each user must get a stable answer, like a fixed raffle number. Put the flag name and user id through a hash to get a bucket from 0 to 99, and turn the flag on when the bucket is below the percentage. Raising 5% to 20% keeps the first 5% in, and adds more. Then delete old flags: each one is a branch in your code that someone must understand.

Worked example

Stable buckets

The same user always lands in the same bucket for a given flag.

import hashlib

def bucket(flag, user_id):
    digest = hashlib.sha256(f"{flag}:{user_id}".encode()).hexdigest()
    return int(digest, 16) % 100

for user in ["ana", "bo", "chen", "dev"]:
    b = bucket("new_checkout", user)
    print(user, b, "on at 25%" if b < 25 else "off at 25%")
print(bucket("new_checkout", "ana") == bucket("new_checkout", "ana"))
In the lesson you can change this and run it.

Including the flag name means each flag gets its own mix of users, so the same people aren't always first.

Quick check
A user's bucket is 37. As the rollout grows, when is the flag on for them? What does this print?
bucket = 37
print([bucket < pct for pct in (10, 25, 50, 100)])
  1. [True, False, True, False]
  2. [False, False, False, True]
  3. [False, False, True, True]
  4. [True, True, True, True]
Show the answer

[False, False, True, True]

bucket < pct is False at 10 and 25, and True at 50 and 100, which gives [False, False, True, True]. They join once the rollout passes 37% and stay in as it grows, because the bucket never changes.

In your own words
What's the difference between deploying and releasing, and what does a stable bucket buy?

Write a sentence or two, then compare it with a good answer in the lesson.

On the job: read, write and review a real workflow

Workflows live in .github/workflows/ as YAML:

name: ci
on:
  pull_request:
  push:
    branches: [main]
permissions:
  contents: read

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with: { python-version: "3.12", cache: pip }
      - run: pip install -r requirements-dev.txt
      - run: ruff check . && mypy src

  test:
    needs: lint
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python: ["3.11", "3.12"]
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with: { python-version: "${{ matrix.python }}", cache: pip }
      - run: pip install -r requirements-dev.txt
      - run: pytest -q

  deploy:
    needs: test
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v7
      - run: ./deploy.sh
        env:
          DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}

The parts: triggers (on), jobs that run on fresh machines, steps inside each job, needs for order, a matrix that runs a job once per Python version, caching of installed packages, permissions that let the workflow's token read the code and nothing more, and secrets injected only where needed. The production environment can require a person's approval.

What a workflow can leak

Three habits keep a workflow safe. Give the workflow token only the permissions it needs, with a permissions: block, as above. Pin third-party actions to a full commit SHA, since a tag or a branch can move. And never print a secret: use it only in the step that needs it.

Quick check
A test fails about one run in twenty, and finding its cause will take a few days. What happens to the test until then?
  1. Rerun the pipeline until it goes green
  2. Delete it right away
  3. Quarantine it and give its fix an owner
  4. Ignore it: one in twenty is rare
Show the answer

Quarantine it and give its fix an owner

The fix is still to find and remove the cause. Until that lands, quarantine takes the test out of the required checks, so a red build keeps meaning something, and the owner makes sure the fix isn't forgotten.

Rollouts need stable users

If you pick users at random on each request, someone may see the new checkout, then the old one, then the new one again. That's confusing for them, and it makes your data useless, since nobody had a consistent experience. Hashing the user id with the flag name, as this lesson's example does, gives each person the same answer every time. Their bucket stays the same as you widen the rollout, so people who already have the feature keep it.

Flags have a cost

Every flag adds a branch to your code, and old flags pile up. After a while, nobody knows what happens if an old one is turned off, and a stale flag has caused serious outages when someone flipped it years later. So when a rollout finishes, delete the flag and the old path. Give each flag an owner and an expected end date when you create it. Some teams add a test that fails if a flag is past its date, which keeps the cleanup from being forgotten.

Portfolio brief

Do it for real: a GitHub Actions workflow that runs pytest

Add continuous integration to one of your own repositories: a workflow file that runs your tests on every push and pull request, so a broken change shows a red cross before anyone merges it.

Write it at .github/workflows/tests.yml, push, and watch the run on GitHub's Actions tab. Paste the file into the starter for a quick check, then ask the tutor to review it.

It must

  • Trigger on push and on pull requests to main
  • Check out the code, set up a pinned Python version and install your dependencies
  • Run pytest, and make the job fail when a test fails
  • Show a green run on GitHub, then a red one from a deliberately broken test, then green again
  • Sets permissions to the least the workflow needs

Go further

  • Cache pip's downloads to make runs faster
  • Run the tests on two Python versions with a matrix
  • Add a status badge to the README
WORKFLOW = '''name: tests
on:
  push:
    branches: [main]
  pull_request:
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.12"
      - run: pip install -r requirements.txt
      - run: pytest -q
'''


def check(text):
    problems = []
    if "pull_request" not in text:
        problems.append("Run on pull requests too, so problems show before merging")
    if "push" not in text:
        problems.append("Run on pushes")
    if "actions/checkout" not in text:
        problems.append("Check out the code first (actions/checkout)")
    if "setup-python" not in text or "python-version" not in text:
        problems.append("Set up a pinned Python version "
                        "(actions/setup-python with python-version)")
    if "pytest" not in text:
        problems.append("Run pytest")
    if "|| true" in text:
        problems.append("'|| true' hides failures: let a failing test fail the job")
    return problems


DONE = "Looks right. Push it, break a test on purpose, and watch it go red, then green."
for p in check(WORKFLOW) or [DONE]:
    print("-", p)
In the lesson, you build it here and the tutor can review it.
Quick check
A pipeline runs lint, test, build and deploy, and a change touches only the docs/ folder. What does a path filter buy?
  1. The pipeline skips the jobs the change can't affect
  2. The tests run on every branch at the same moment
  3. The build job runs twice to make sure nothing broke
  4. The docs are deployed without any review at all
Show the answer

The pipeline skips the jobs the change can't affect

A path filter starts a job only when files it depends on changed. A docs-only change doesn't need the ten-minute build, so the pipeline answers sooner and costs less.

In your own words
Why are flaky tests bugs, and what do flags cost?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 2 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 9 review cards for spaced repetition

Try a quiz question

What's the difference between continuous delivery and continuous deployment?

  1. Delivery keeps every change ready and a person releases; deployment releases automatically
  2. They're the same practice, and the two names only differ between companies and tools
  3. Delivery has no tests, since a person checks each release; deployment runs them all
  4. Deployment only runs on weekends, when traffic is low; delivery can go out at any time

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 11 · about 34 hours of study

Professional practice

Design, ship and run real systems, work well in a team, and get hired 43 lessons 1 free
  1. System design fundamentals FreeRequirements, rough numbers, the standard parts and where systems break.40 min
  2. Caches, queues and background jobsSpeed reads with caches, and move slow work to queues that retry safely.40 min
  3. Designing AI systemsLatency, cost, routing, fallbacks and guardrails for features built on models.40 min
  4. Containers and deploymentPackage an app as an image, configure it with the environment, and roll out safely.45 min
  5. CI/CD pipelinesTest every change automatically, and ship with gates, flags and rollbacks.40 min
  6. Docker ComposeSeveral containers together: service names, volumes, secrets and start order.40 min
  7. Kubernetes basicsDesired state, Deployments and Services, labels, probes and rolling updates.40 min
  8. Cloud for AI engineersAccess policies and least privilege, storage, compute choices, managed model endpoints, secrets and budgets.30 min
  9. Metrics, dashboards and alert rulesCounters, gauges and histograms, a rate from a counter, a percentile from buckets, a dashboard panel and an alert rule that fires on a sustained condition.40 min
  10. Reliability and incidentsSLOs, error budgets, alerts, on-call and blameless postmortems.40 min
  11. Incident lab: from the page to the postmortemOne incident run from the page to the all-clear: decide the mitigation, work out the impact in failed requests and error budget, and write a blameless postmortem, a status update and a runbook entry.40 min
  12. Measuring an AI feature from its logsTyped views over event logs, metric specs, cost from a price table, and rollups you can rerun.40 min
  13. A/B testing a model changeHash assignment, per-user results from raw logs, sample ratio checks, guardrails and a decision rule.40 min
  14. Columnar files and a local warehouseRows against columns, the encodings that shrink a column, Parquet's row groups and the ranges that let a query skip them, and SQL over files with DuckDB.40 min
  15. Data quality checks and contractsSix properties of a delivery you can test, each as a count of rows that break it, a contract with the producer, and when to block, quarantine or warn.40 min
  16. Transformations: staging, models and testsRaw, staging, facts and marts as SQL models run in dependency order in DuckDB, tests as queries that count the rows that break a rule, an incremental load that is safe to rerun, and the same models as dbt files.45 min
  17. Streams and windowsEvents that never stop arriving: event time against arrival time, tumbling, sliding and session windows, a watermark for late events, and counting each event once.40 min
  18. Labels and annotator agreementLabels as measurements: agreement and Cohen's kappa, the pair of classes annotators confuse, votes and gold questions, and what wrong labels do to a model and a test score.45 min
  19. Experiment tracking and reproducible runsA run record of settings, seed, data and code behind every score, a run log in a dozen lines, and comparing settings across seeds.40 min
  20. Hyperparameter searchWhat a grid costs, random search on a log scale, stopping weak settings early, and why the winner's validation score flatters it.40 min
  21. Versioning data and modelsFiles stored under the hash of their contents, a manifest that names a whole dataset, and lineage from data and code to each model.35 min
  22. A model registry and promotionVersions under one name, an alias for the live one, gates a candidate must pass, group by group, and a rollback that moves a pointer.40 min
  23. Feature pipelines and training-serving skewWhy a model that passes offline fails live: statistics refit at serving, two code paths, and features from the future, with the fix for each.40 min
  24. Batch and online inferencePredict ahead of time or on request: when the inputs exist, latency near a server's limit, batching what waits, cost, and a hybrid with a freshness limit.40 min
  25. Monitoring a model: drift and decayWhy a model worsens with no code change: data drift and concept drift, a measure of how far inputs have moved, thresholds set from noise, and labels that arrive late.45 min
  26. Retraining and pipelinesWhen to retrain and on which weeks, training as steps in dependency order, a cache that reruns only what changed, and guards before and after.45 min
  27. Designing ML systemsOne method for an ML design, goal and metric to retraining, with the sums that size it: requests a second at peak, a year of feature storage, a label delay and a latency budget.45 min
  28. Datasheets: documenting a datasetThe document that travels with a dataset: a profile by column and by group, claims a program can check, splits that don't leak, a scan for personal data, and the license and limits only people can write.45 min
  29. Curation, active learning and synthetic dataThree levers on a training set: removing copies and broken rows, letting a model choose which rows to label, and manufacturing rows, which helps only when their source knows more than you do.45 min
  30. Measuring fairnessBreak a model's results down by group: selection rate, true and false positive rates and precision, why they can't all be equal, what each fix costs, and when a group is too small to judge.40 min
  31. Privacy engineeringWhy removing names isn't anonymity, how to hold less (minimization, retention, keyed pseudonyms), the idea behind differential privacy and its budget, what a model remembers, and a deletion that reaches every store.40 min
  32. A red-team labAttack a simulated assistant methodically: eight kinds of attack run as a suite, success rates beside ordinary requests blocked, fresh attacks to test the fixes, where a defense belongs, and findings kept as release tests.45 min
  33. What regulation asks of an engineerRisk tiers that follow a system's use, the requirements for high-risk systems as artifacts an engineer builds, evidence tied to a model version, a model card a program can check, and legal dates kept as data.35 min
  34. Git for teamsBranches, pull requests, rebasing and how a three-way merge finds conflicts.40 min
  35. Writing for engineersREADMEs, design docs, commit messages and bug reports people can act on.35 min
  36. Scoping and estimating workA vague request cut into tickets with acceptance criteria and a first shippable slice, estimates as ranges, an honest update for a slip, and a ticket linked to its pull request.30 min
  37. Roles, résumé and the searchWhat AI, ML and data engineering postings ask for, résumé bullets that carry a number, a 100-word project summary, a take-home as a portfolio piece and how to read an offer.35 min
  38. Interviews and your portfolioShow your work, and solve interview problems the way professionals do.40 min
  39. Code reviewWhat to look for, how to give and take feedback, and automating the routine checks.35 min
  40. Reading unfamiliar codeFind your way around a big codebase fast, with tools that map it for you.35 min
  41. Working with AI coding toolsGive agents good context, keep tasks small, and check every change they make.35 min
  42. Capstone: ship a production AI serviceAn AI-backed service with validation, caching, rate limits, fallbacks, logging and evals.45 min
  43. Capstone: take a model to productionA churn model through a data contract, a tracked run, a registry gate by slice, hybrid serving, a PSI monitor and one retrain, shipped with a datasheet, a model card, a fairness audit, a design doc and a runbook.45 min
Part of a free course 127 lessons

Free Python developer course

Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.

Part of a free course 20 lessons

Build and Operate HTTP APIs

Design, test, deploy, and operate an HTTP API that another engineer can use.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write