Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Worked example · 20 min · revision 3

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

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 stress or 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-randomly to 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.

Bash · Stress-testing suspected flaky tests and profiling slow test fixtures
#!/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-from so 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 main but cannot write to it. That stops a pull request from planting a poisoned entry that a later main build restores; it does not help if a workflow on main itself 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.

  1. Create a CPU-bound suite and lock the tools. pytest-xdist adds the -n option, which starts worker processes and gives each a share of the tests; -n auto starts one worker per CPU. measure.py runs a command several times and prints the spread, because one run of each tells you little.
Bash · Step 1: a project with a hashed lock
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.txt
Python · tests/test_work.py
import 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
Python · measure.py
"""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")
  1. 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.
Bash · Step 2: cold and warm dependency install
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
done
Illustrative output (times depend on your network, disk and CPU)
cold install: 76.852s
warm install: 7.966s
  1. Time the suite serially and in parallel, five runs each.
Bash · Step 3: before and after -n auto
.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 tests
Illustrative output (an 8-CPU machine that other jobs were also using)
serial: min 10.86s, median 12.04s, max 14.23s over 5 runs
xdist: min 7.93s, median 9.49s, max 10.54s over 5 runs

Read 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.

  1. 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, so cache-hit is false: restore-keys restores 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.
YAML · .github/workflows/tests.yml
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 tests

05. Check your understanding

Practice check · 3 questions

Fixed sleeps, retries and cache keys

Three questions on flaky tests, retries and caches.

Q1. An integration test that waits for an asynchronous worker using `time.sleep(1.0)` passes consistently on a developer's local 16-core laptop but fails 15% of the time on shared CI runners. What is the fundamental cause?
Q2. Why are automatic test retries (`--reruns 3`) a poor permanent fix for flaky tests in CI?
Q3. A workflow caches pip's download directory with `key: pip-${{ hashFiles('requirements-dev.txt') }}` and no `restore-keys`. A pull request adds one package to the lock. On its first run `cache-hit` is `false` and the install takes as long as with an empty cache. Why?
Practice only: not graded, not saved, not evidence.

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 quarantine marker in pytest.ini (markers = quarantine: known flaky, tracked in a ticket), mark known flaky tests with @pytest.mark.quarantine, run pytest -m "not quarantine" in the blocking job and pytest -m quarantine in a separate non-blocking job. Do not use @pytest.mark.flaky for 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.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check