REAL-WORLD SCENARIOS

Retrying an API Call in Tests Without Hiding Real Failures

Retry logic in an API test suite is one of those things that seems harmless until it isn't. A shared staging environment returns the odd 503, someone wraps the call in a retry, and the build goes green. A few months later the suite retries everything, a real bug that fails one request in three sails through, and nobody can say how often anything actually fails.

Retries aren't the problem. Unexamined retries are. A good retry policy handles genuine infrastructure noise, retries only what's safe to retry, and leaves a visible record of every attempt so the noise itself can be measured and fixed.

This has become more pressing with AI in the loop, in two ways. Coding agents asked to "fix the flaky test" often reach for a retry or a rerun plugin, because that's the quickest route to green. And tests that call a language model fail some of the time by nature, which tempts people to retry until the output passes. In this article I'll cover what deserves a retry, how to make retries visible, where retry logic belongs, and how to handle both of those AI cases honestly.

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

Decide what actually deserves a retry

A retry is only appropriate when the same request, sent again a little later, could reasonably succeed and the failure says nothing about the code under test. That's a short list:

  • 429 Too Many Requests: a rate limit that clears after a wait, ideally the one the Retry-After header gives you.
  • 503 Service Unavailable: a dependency temporarily unavailable.
  • 502 and 504: gateway or proxy trouble in a shared environment.
  • Connection errors and timeouts: network blips before the request reached the application.

The list of things you should never retry is longer: 400, 401, 403, 404, 409 and 422 all mean the request or the state is wrong, and sending it again changes nothing. A plain 500 is usually an application bug, so I don't retry it in tests by default. Retrying a 500 is exactly how a real defect gets hidden.

One more condition: only retry requests that are safe to repeat. A GET is fine. A POST that creates an order might have succeeded on the server before the connection dropped, and retrying it creates a second order. Unless the API supports idempotency keys, I don't retry non-idempotent calls. I cover that in testing idempotency in APIs that handle payments or orders.

Encode the policy in one place, and log every attempt

The tenacity library expresses this policy cleanly. The key settings are a hard stop, a backoff, a predicate that only matches retryable failures, and a log line before every sleep:

import logging

import requests
from tenacity import (
    before_sleep_log,
    retry,
    retry_if_exception,
    stop_after_attempt,
    wait_exponential,
)

logger = logging.getLogger("api_client")

RETRYABLE_STATUS = {429, 502, 503, 504}


class RetryableStatus(Exception):
    def __init__(self, response):
        super().__init__(f"{response.status_code} from {response.request.method} {response.url}")
        self.response = response


def _is_retryable(exc):
    return isinstance(exc, (RetryableStatus, requests.ConnectionError, requests.Timeout))


@retry(
    retry=retry_if_exception(_is_retryable),
    stop=stop_after_attempt(3),
    wait=wait_exponential(multiplier=1, min=1, max=8),
    before_sleep=before_sleep_log(logger, logging.WARNING),
    reraise=True,
)
def get_with_retry(session, url, **kwargs):
    response = session.get(url, timeout=10, **kwargs)
    if response.status_code in RETRYABLE_STATUS:
        raise RetryableStatus(response)
    return response

A few details matter here. reraise=True means that after the final attempt, the test sees the original exception rather than a generic retry error, so the failure message stays readable. Non-retryable statuses are returned normally and the test's own assertion fails on them straight away. And before_sleep_log writes a warning for every retry, so retries show up in the test output instead of vanishing.

Logging is only half of visibility. The other half is counting. I record retries in the test report, for example as a property attached to the test or a summary at the end of the run, so I can see which endpoints retry most and whether that's growing. A test that passes on its third attempt every day is telling you something about the environment, and you want that on a chart, not buried in logs. For more on this, see debugging failed API tests faster with better logging.

Keep retry logic out of the test body

Retries belong in the API client layer, not scattered through tests. A test should read as intent:

def test_order_lookup_returns_pending_order(api, created_order):
    response = api.get_order(created_order["id"])
    assert response.status_code == 200, response.text
    assert response.json()["status"] == "pending"

When retry loops appear inside tests, each one ends up with slightly different rules, some retry everything, and nobody can review the policy as a whole. In the client, there's one policy, one log format and one place to change it.

I'm also wary of whole-test reruns, such as the pytest-rerunfailures plugin's --reruns option. Rerunning a whole test repeats setup, assertions and all, so it can hide genuine logic failures as well as infrastructure noise. If you use it at all, keep it as a temporary measure, report reruns clearly, and fix the underlying cause.

When an agent "fixes" a flaky test

Coding agents are good at making a red test green, and the fastest ways to do that are adding a retry, adding a sleep, loosening an assertion or adding a rerun marker. Every one of those can be legitimate. Every one can also bury a real bug. I put the boundary in the repository instructions the agent reads, .github/copilot-instructions.md for Copilot or your agent's equivalent:

## Retries and flaky tests
- Retries live only in tests/support/api_client.py. Do not add retry loops,
  sleeps or rerun markers to tests.
- Never retry 4xx responses or non-idempotent requests.
- When a test is flaky, report the failure pattern and a suspected cause.
  Do not change retry settings without a human approving it in review.

In review, any diff that touches retry settings or adds time.sleep to a test gets a closer look, whoever wrote it.

Tests that call a model: pass rates, not retries

If your product calls a language model, some of your tests check its output. Those tests are non-deterministic by design: the same input can pass on one run and fail on the next. Wrapping them in "retry until the output passes" is the worst kind of hidden failure, because it turns a feature that works some of the time into a test that always passes.

The honest version is to run the case several times and assert a pass rate:

def test_summary_mentions_refund_amount(generate):
    prompt = "Summarise: customer was refunded $42.10 for a duplicate charge."
    runs = 10
    passes = sum("42.10" in generate(prompt) for _ in range(runs))
    assert passes / runs >= 0.9, f"{passes}/{runs} runs mentioned the amount"

Here generate is a fixture wrapping your model call. The threshold is a product decision, not a test detail, and the failure message reports the rate. Transport failures from the model provider, such as a 429 or a timeout, can still go through the normal retry policy; a wrong answer never should. Keep these tests in their own CI job, since they're slower and cost money per run.

Retry the infrastructure, never the assertion

A sound rule of thumb: retry transient infrastructure failures, in one place, with a hard limit and a log line for every attempt. Never retry a wrong answer, whether it came from your API or from a model. If you'd like to build API suites with that kind of client layer from the start, in Python or Node with VS Code and GitHub Copilot, my API testing courses walk through it.