Hunting a flaky test and a slow step
Find and fix flaky tests, measure where pipeline time goes, and use timings to check whether a dependency cache and parallel tests really make the build faster.
Contentsand lesson path
On this page
- What flaky tests cost and where they come from
- Profiling Techniques: Stress Testing and Bottleneck Analysis
- Caching dependencies, build outputs and image layers
- Worked Example: Measure a Change Before You Keep It
- Check your understanding
- Apply it
- Review prompt
Lessons of Build & Test Pipeline
- What makes a build reproducible Concept · 15 min
- One entry point: wrapping your toolchain in Make or a task runner Worked example · 20 min
- Ordering checks from cheapest to most expensive Concept · 15 min
- Lab: lint, test and package a service with reports Lab · 30 min
- Hunting a flaky test and a slow step Worked example · 20 min
- Check: build pipeline review Knowledge check · 6 questions
What you will learn
- Diagnose slow or flaky builds and fix them with caching, test isolation and parallelism, measuring the effect.
01. What flaky tests cost and where they come from
A flaky test is a test that sometimes passes and sometimes fails on the same commit with the same configuration. Flaky tests are costly because they erode trust: when failures appear without code changes, engineers start clicking "Re-run all jobs" instead of investigating real failures.
A flaky test usually has a cause you can find: a bug in the test or the code that shows up only under some conditions, such as timing, ordering or the machine it runs on:
-
Hardcoded Timing Assumptions and Sleep Calls: Tests that rely on
time.sleep(1.0)to wait for asynchronous background tasks or database writes. A one-second pause may be enough on an idle laptop and too short on a busy shared CI runner. Poll for the condition instead, with a timeout (wait_until(predicate, timeout=10)). -
Shared State and Test Pollution: A test leaves rows, globals or temporary files behind, and a later test fails only when it runs after that one. Give each test its own fixtures and clean up after
yield. -
Unmocked External Network Services: Tests that call live third-party APIs or public mirrors fail whenever the network, a rate limit or the remote service has a bad moment. Replace those calls with mocks or a local fake server.
-
Concurrency Races and Deadlocks: Threaded code with a missing lock fails only when threads happen to run in one particular order.
02. Profiling Techniques: Stress Testing and Bottleneck Analysis
To find the cause, measure and stress the suite:
-
Automated Repetition Stress Loops: When an intermittent failure occurs in CI, run the suspect test locally in a loop under simulated CPU and I/O load (using
stressor Docker resource limits). Running a test 100 times in succession (for i in {1..100}; do pytest tests/test_payment.py || break; done) is very likely to expose a race that fails once in twenty runs: the chance that all 100 runs pass is below 1%. -
Test Order Randomization: Use tools like
pytest-randomlyto shuffle test execution order on every run. If test B passes when it runs after test A but fails when it runs first, B depends on state that A leaves behind. -
Profiling Step Durations with Timing Reports: Find slow tests with the runner's timing option (such as
pytest --durations=10), which lists the ten slowest test phases. Look there for unneeded network round trips, unindexed database queries or expensive setup fixtures. -
Timing Across Many Builds: Keep job and test durations from many CI runs, for example from the JUnit reports, and watch the median and the slowest runs rather than single values.
#!/usr/bin/env bash
set -euo pipefail
echo "==> Profiling test suite execution durations..."
# "|| true": a flaky failure here must not stop the script before the loop
pytest --durations=5 tests/ || true
echo "==> Stress-testing suspected concurrency race (50 iterations)..."
PASS_COUNT=0
FAIL_COUNT=0
for i in $(seq 1 50); do
if pytest -q tests/test_concurrency.py > /dev/null 2>&1; then
PASS_COUNT=$((PASS_COUNT + 1))
else
FAIL_COUNT=$((FAIL_COUNT + 1))
echo "[FAIL] Iteration ${i} failed"
fi
done
echo "Stress test complete: ${PASS_COUNT} passed, ${FAIL_COUNT} failed"03. Caching dependencies, build outputs and image layers
Once flaky tests are quarantined, look at speed. Caching avoids repeating work whose inputs have not changed:
-
Package Manager Store Caching: Cache global package directories (such as
~/.npm,~/.cache/pnpm, or~/.cache/pip) keyed on the hash of the lock file (hashFiles('**/pnpm-lock.yaml')), so an unchanged lock reuses earlier downloads. -
Compiler and Build Artifact Caching: Tools like
ccache(for C/C++) and Go's build cache save compiled object files and recompile only what changed. -
Container Layer Caching: Use BuildKit's
--cache-fromso that base and dependency layers are pulled from a registry instead of rebuilt on every commit. -
Cache Scoping and Poisoning Defenses: Keep caches scoped by branch: on GitHub a pull request can read the cache of
mainbut cannot write to it. That stops a pull request from planting a poisoned entry that a latermainbuild restores; it does not help if a workflow onmainitself is compromised.
Build tools with a remote cache (for example Bazel or Turborepo) go further. When remote caching is enabled and another engineer or CI worker has already built a target with exactly the same inputs, later workers download that output instead of building it again. Whether any of this pays off on your pipeline is something to measure, as the worked example below shows.
04. Worked Example: Measure a Change Before You Keep It
A speed-up that nobody measured is a guess. Two things make build timings hard to read: run-to-run noise (other jobs on the same host, network, disk) and the difference between a cold cache and a warm one. The routine is the same for any change: time the current state several times, make one change, time it again the same way, and keep the change only if the difference is larger than the noise. Here you measure two common changes: running tests in parallel with pytest-xdist, and a dependency cache. You need uv, as in the lesson 04 lab.
- Create a CPU-bound suite and lock the tools. pytest-xdist adds the
-noption, which starts worker processes and gives each a share of the tests;-n autostarts one worker per CPU.measure.pyruns a command several times and prints the spread, because one run of each tells you little.
mkdir -p speed-lab/tests && cd speed-lab
uv python pin 3.13
printf 'pytest==9.1.1\npytest-xdist==3.8.0\n' > requirements-dev.in
uv pip compile -q --generate-hashes requirements-dev.in -o requirements-dev.txtimport pytest
def busy(n: int) -> int:
"""CPU-bound work: a sum of squares that takes a noticeable time."""
return sum(i * i for i in range(n))
@pytest.mark.parametrize("case", range(8))
def test_busy(case):
assert busy(12_000_000) > 0"""Run a command several times; print the min, median and max wall-clock time."""
import statistics
import subprocess
import sys
import time
label, runs, cmd = sys.argv[1], int(sys.argv[2]), sys.argv[3:]
times = []
for _ in range(runs):
start = time.perf_counter()
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL)
times.append(time.perf_counter() - start)
print(f"{label}: min {min(times):.2f}s, median {statistics.median(times):.2f}s,"
f" max {max(times):.2f}s over {runs} runs")- Time a cold and a warm install. The loop points uv at an empty cache of its own, installs into a fresh virtual environment, then does the same again. The first install downloads every wheel; the second finds them in the cache.
export UV_CACHE_DIR="$PWD/.uv-cache" # a cache of our own, empty at first
for run in cold warm; do
rm -rf .venv && uv venv -q .venv
TIMEFORMAT="$run install: %Rs"
time uv pip install -q --python .venv/bin/python --require-hashes \
-r requirements-dev.txt
donecold install: 76.852s
warm install: 7.966s- Time the suite serially and in parallel, five runs each.
.venv/bin/python measure.py serial 5 .venv/bin/python -m pytest -q tests
.venv/bin/python measure.py xdist 5 .venv/bin/python -m pytest -q -n auto testsserial: min 10.86s, median 12.04s, max 14.23s over 5 runs
xdist: min 7.93s, median 9.49s, max 10.54s over 5 runsRead the spread, not one number. In the run above, the slowest parallel run was still faster than the fastest serial run, so the difference is larger than the noise. In an earlier run on the same machine, while other jobs kept it busier, the two ranges overlapped and the medians were almost equal: extra workers help only when there are idle CPUs, and starting them takes time. Your numbers will differ; keep -n auto when your own measurements show a clear gap.
Parallel runs can also make tests fail that never failed serially, when two tests write the same file, port or database row at the same time. That is a test isolation bug: give each test its own resources, for example pytest's tmp_path fixture, instead of turning parallelism off. When one machine is not enough, split the suite across several CI jobs (shards), balanced by the durations recorded in earlier JUnit reports so that no shard waits on one slow file.
- Carry the change into CI and read cache results correctly. The workflow below installs from the same hashed lock with pip, caches pip's download directory and runs the suite in parallel. Its cache key contains the hash of
requirements-dev.txt. The first run after any change to the lock computes a new key and finds no entry under it, socache-hitisfalse:restore-keysrestores the newest older entry if one exists, pip downloads whatever is missing, and the job saves a new entry under the new key at the end. Later runs with the same lock get an exact hit. Record the step durations from the run summary for several runs, cold ones included, before you decide the cache helped.
name: tests
on: [pull_request]
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version-file: .python-version
- id: pip-cache
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ~/.cache/pip
key: pip-${{ runner.os }}-${{ hashFiles('requirements-dev.txt') }}
restore-keys: pip-${{ runner.os }}-
- env:
CACHE_HIT: ${{ steps.pip-cache.outputs.cache-hit }}
run: echo "exact cache hit = $CACHE_HIT"
- run: python -m pip install --require-hashes -r requirements-dev.txt
- run: python -m pytest -n auto --durations=5 tests05. Check your understanding
06. Apply it
In your own pipelines:
- Replace Sleeps with Polling Conditions: Instead of a fixed
sleep(2.0), poll for the condition you are waiting for, with an explicit timeout (wait_for(condition, timeout=10)). - Quarantine Flaky Tests Quickly: Register a custom
quarantinemarker inpytest.ini(markers = quarantine: known flaky, tracked in a ticket), mark known flaky tests with@pytest.mark.quarantine, runpytest -m "not quarantine"in the blocking job andpytest -m quarantinein a separate non-blocking job. Do not use@pytest.mark.flakyfor this: that marker comes from the pytest-rerunfailures and flaky plugins and makes the test retry automatically, which is the blanket-retry pattern this lesson warns against. - Run Order Randomization in CI: Enable randomized test ordering (
pytest-randomly) to surface hidden state pollution and test interdependencies early. - Measure Before You Keep a Speed-Up: Time the job several times before and after each change (a cache,
-n auto, shards), cold-cache runs included, and keep the change only when the gap is larger than the spread. - Cache Dependency Directories by Lockfile Hash: Key the cache on
hashFiles()of the lock file, so a dependency change starts a new entry instead of reusing a stale one.
07. Review prompt
Define a flaky test and name four common causes. Explain why blanket retries are harmful. Then describe how you would show that -n auto or a dependency cache really made a job faster, and why the first run after a lock change is a cache miss.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.