REAL-WORLD SCENARIOS

Debugging a Flaky API Test That Only Fails in CI

There's a particular frustration reserved for the test that passes every time on your laptop and fails, sometimes, in CI. Not always and not on a schedule, just often enough to block a merge and make everyone doubt the suite. The fix is almost never "retry the test". It's working out why the two environments behave differently, because they always do in some way.

This is also one of the places where AI coding agents need the most supervision. Ask an agent to make a flaky test pass and the most likely result is a retry decorator, a longer sleep or a looser assertion. CI goes green and the underlying problem, which may be a real bug in the API, is now hidden. On the other hand, agents are genuinely good at the tedious parts of this investigation: comparing environments, reading logs from many runs and spotting what the failures have in common.

Here are the root causes I check first, how I instrument a test to see what CI actually experienced, and how to fix the flake for good, with an agent helping rather than papering over it.

Build an API Automation Framework in Python

Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.

Learn more

The usual root causes behind CI-only failures

In practice, CI-only API test failures come from a short list. I check them roughly in this order:

  1. Timing. CI runners are often slower or busier than a developer machine. A test that reads a resource immediately after creating it may work locally and lose the race in CI, especially with eventually consistent systems or async processing.
  2. Shared state and test order. Running in parallel, or in a different order, exposes tests that depend on data another test created or deleted. Locally you probably run a subset in a fixed order.
  3. Environment and configuration. A different base URL, a missing environment variable, different feature flags, a shorter token lifetime or a different timezone.
  4. Network. CI talks to the API through different routes, proxies and DNS. Timeouts that were generous locally are tight there.
  5. Data that isn't yours. A shared staging environment where other people and pipelines are creating, changing and deleting the same records.

Parallel execution deserves its own look, because it accounts for a lot of these. I cover it in parallelizing a Python test suite without flaky failures.

Reproduce it before you change anything

The first goal is to make the failure happen on demand. A few runs that try to recreate CI conditions locally:

# Run the suspect test many times (pytest-repeat)
pytest tests/api/test_orders.py::test_order_appears_in_list --count=50 -x

# Run the whole suite in parallel, as CI does (pytest-xdist)
pytest -n auto

# With pytest-randomly installed, order is shuffled on every run;
# replay a failing order with the seed it printed in the header
pytest --randomly-seed=12345

If it fails under parallel or shuffled runs, you're looking at shared state. If it only fails against the CI environment, it's configuration, network or data. If it fails at a steady low rate whatever you do, suspect timing.

Instrument the test to see what CI experienced

When you can't reproduce it, make the test explain itself next time it fails. The most useful single change is logging the full request and response at the moment of failure, plus enough context to compare runs:

import logging
import os

log = logging.getLogger("api")


def describe(response):
    req = response.request
    return (
        f"{req.method} {req.url}\n"
        f"status={response.status_code} elapsed={response.elapsed.total_seconds():.2f}s\n"
        f"request_id={response.headers.get('X-Request-Id')}\n"
        f"body={response.text[:2000]}"
    )


def test_order_appears_in_list(api, new_order):
    response = api.get("/orders", params={"customer": new_order["customer_id"]})
    ids = [o["id"] for o in response.json()["items"]]
    assert new_order["id"] in ids, (
        f"order {new_order['id']} missing from list\n"
        f"env={os.getenv('TEST_ENV')}\n{describe(response)}"
    )

Use whatever correlation header your API actually returns; X-Request-Id is just a common convention. Having it in the failure message lets you find the matching server logs. For more structure around this, see my post on debugging failed API tests faster with better logging.

Also make CI keep its evidence: write JUnit XML with --junitxml, upload logs as build artefacts, and print the environment's configuration (minus secrets) at the start of the run.

Using an agent to investigate, not to hide

This is where I find coding agents genuinely helpful. Give an agent the logs from several failing and passing runs and ask a narrow question: what do the failing runs have in common that the passing ones don't? It's quick at noticing that every failure ran on the same shard, or within a second of a related create call, or after a particular other test.

What I don't do is ask an agent to "fix the flaky test". I put the boundary in the repository instructions, such as .github/copilot-instructions.md or CLAUDE.md:

## Flaky tests
- Do not add retries, reruns, sleeps, skips or xfail to make a failing test pass.
- Do not loosen an assertion to tolerate intermittent results.
- Investigate: report the failing runs, the suspected cause and evidence.
- A fix must remove the cause (wait for a condition, isolate data, fix config)
  and be shown passing under --count and -n auto.

When I review an agent's flake fix, I look for those patterns in the diff before anything else.

Fixing the flake for good

The right fix depends on the cause:

  • Timing: replace sleeps with polling on a condition, with a clear deadline and a failure message saying what never happened.
  • Shared state: give each test its own data, with unique identifiers, and clean up in a fixture finaliser so teardown always runs.
  • Configuration: make required settings fail fast at session start rather than surfacing as odd test failures later.
  • Network: set explicit timeouts on every call and log elapsed time so you can see when the network is the issue.

A small polling helper covers most timing cases:

import time


def wait_until(check, timeout=15, interval=0.5, what="condition"):
    deadline = time.monotonic() + timeout
    last = None
    while time.monotonic() < deadline:
        last = check()
        if last:
            return last
        time.sleep(interval)
    raise AssertionError(f"timed out after {timeout}s waiting for {what}; last={last!r}")

Retries have a place, but only for the call, not the assertion, and only for failures that are genuinely transient, such as a 503 from a gateway. I set out where that line sits in retrying an API call in tests without hiding real failures.

Flaky is not the same as non-deterministic

One distinction matters more as test suites start covering LLM features. A flaky test should be deterministic and isn't, because of a fault in the test or the environment; the goal is to remove the cause. A test of a model's output is non-deterministic by nature; the goal is to measure it. If you have both kinds in one suite, keep them separate. Model-output tests should run several times and report a pass rate against a threshold, in their own job, so they never get mistaken for flakes, and flakes never get excused as "just the AI".

A flaky test that only fails in CI is a signal that your environments differ in a way you don't yet understand. Reproduce it, instrument it, find the cause and remove it, and keep the agents investigating rather than suppressing. If you want to build a suite that's reliable in CI from day one, my API testing courses walk through it with GitHub Actions and Copilot.