Testing Rate-Limited APIs (and Agents) Without Tripping the Limit
Rate limiting feels invisible until a test run suddenly fails with a wall of 429 Too Many Requests, or an API key gets suspended halfway through CI. I've seen teams spend a long time chasing what looked like flaky tests, only to find that parallel workers were all hitting the same endpoint and blowing through the limit together. The tests weren't wrong. Nobody had designed the suite with the limit in mind.
AI has added new ways to hit that wall. A coding agent fixing a failing test will happily re-run the suite over and over, and every run spends quota. An agent calling your API through a tool can loop on a request much faster than a person would. And if you run evals against a model provider, you're testing a rate-limited API yourself, many times per prompt.
In this article I'll cover the approach I use: mock the 429 so the handling code is properly tested, pace the live calls you genuinely need, structure the suite so workers and agents don't collide, and make rate limits visible in results rather than disguised as failures.
Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.
Mock the 429 first
The most important rate-limit test isn't the happy path. It's what your client does when it gets a 429. Does it read Retry-After and wait? Does it give up after a sensible number of attempts? Does it crash, or quietly return nothing? You can't answer those by waiting for the live API to throttle you. Mock it.
The trick that makes this testable is injecting the sleep function, so the test records the waits instead of actually waiting:
import time
class RateLimitError(Exception):
def __init__(self, retry_after):
super().__init__(f"rate limited, retry after {retry_after}s")
self.retry_after = retry_after
def parse_retry_after(value, default):
try:
return max(0.0, float(value))
except (TypeError, ValueError):
return default
def get_with_backoff(session, url, max_retries=3, default_wait=1.0, sleep=time.sleep):
for attempt in range(max_retries + 1):
resp = session.get(url, timeout=10)
if resp.status_code != 429:
resp.raise_for_status()
return resp.json()
wait = parse_retry_after(resp.headers.get("Retry-After"), default_wait)
if attempt == max_retries:
raise RateLimitError(wait)
sleep(wait)
Retry-After can be a number of seconds or an HTTP date. This version handles seconds and falls back to the default for anything else. If your API sends dates, add that branch and a test for it. With the responses library, registering several responses for the same URL returns them in order, which is exactly what a retry test needs:
import pytest
import requests
import responses
URL = "https://api.example.com/data"
@responses.activate
def test_retries_after_429_then_succeeds():
responses.add(responses.GET, URL, status=429, headers={"Retry-After": "2"})
responses.add(responses.GET, URL, status=429, headers={"Retry-After": "2"})
responses.add(responses.GET, URL, json={"ok": True}, status=200)
waits = []
result = get_with_backoff(requests.Session(), URL, sleep=waits.append)
assert result == {"ok": True}
assert waits == [2.0, 2.0]
assert len(responses.calls) == 3
@responses.activate
def test_gives_up_when_retries_are_exhausted():
responses.add(responses.GET, URL, status=429) # no Retry-After header
waits = []
with pytest.raises(RateLimitError) as exc_info:
get_with_backoff(requests.Session(), URL, max_retries=2,
default_wait=5, sleep=waits.append)
assert exc_info.value.retry_after == 5
assert waits == [5, 5]
These run in milliseconds, never touch the network, and belong in the suite that runs on every commit. Retry logic is also a common place to hide real failures, so I keep it out of test assertions themselves. I explain why in retrying an API call in tests without hiding real failures.
Pace the live calls you actually need
Some tests have to hit the real API: contract checks, environment smoke tests, behaviour a mock can't reproduce. For those, I use one session-scoped pacer instead of scattering time.sleep(1) through the tests:
import time
import pytest
class Pacer:
def __init__(self, calls_per_second):
self.min_interval = 1.0 / calls_per_second
self._last = 0.0
def wait(self):
delay = self._last + self.min_interval - time.monotonic()
if delay > 0:
time.sleep(delay)
self._last = time.monotonic()
@pytest.fixture(scope="session")
def pacer():
return Pacer(calls_per_second=2)
Every live call goes through pacer.wait() first. Because the fixture is session-scoped, it controls the rate for the whole run, not just one test. Also cut the calls you don't need: authenticate once per session, and seed data in bulk rather than one request per test.
Keep parallel workers away from the live API
Here's the catch. With pytest-xdist, each worker is a separate process with its own session fixtures, so four workers means four pacers that know nothing about each other. Rather than build cross-process coordination, I keep live tests out of the parallel run. Register a marker:
[pytest]
markers =
live_api: calls the real rate-limited API; run serially
Then split CI into two steps:
pytest -m "not live_api" -n auto
pytest -m live_api -n 0
The first step is fast and parallel; the second is small, serial and paced. Tagging API tests so CI can run the right subset goes further into marker design, and parallelizing a Python test suite without flaky failures covers the other shared-state problems xdist exposes.
Make a 429 look like a 429 in the results
A test that fails because of a 429 should not look like a test that failed because the API returned the wrong data. In the live suite's helper, I fail with an explicit message ("RATE LIMITED: GET /orders, Retry-After 30") so anyone reading the report knows it's an infrastructure problem, not a regression. Some teams skip instead. That's fine only if somebody counts the skips, because a live suite that skips half its tests every night is not giving you the coverage it appears to.
Agents are rate-limit clients too
This is where agentic work changes things, in three places.
Coding agents running your suite. When Copilot's agent mode or a similar tool iterates on a failing test, it runs tests repeatedly. Make sure the default command it runs is the mocked suite. A line in .github/copilot-instructions.md or your agent's instruction file does it: "Run pytest -m 'not live_api'. Never run live_api tests unless asked." Without that, an agent can spend a day's quota fixing a typo.
Agents calling your API through tools. If a tool hits a rate-limited API, it should return the limit to the model as structured information, not retry forever and not raise an exception the agent can't interpret. Test that contract with the same mocks:
def fetch_data_tool(session, url):
"""Tool exposed to an agent: one attempt, structured result."""
resp = session.get(url, timeout=10)
if resp.status_code == 429:
wait = parse_retry_after(resp.headers.get("Retry-After"), 60.0)
return {"error": "rate_limited", "retry_after_seconds": wait}
resp.raise_for_status()
return {"data": resp.json()}
@responses.activate
def test_tool_reports_rate_limit_to_the_agent():
responses.add(responses.GET, URL, status=429, headers={"Retry-After": "30"})
result = fetch_data_tool(requests.Session(), URL)
assert result == {"error": "rate_limited", "retry_after_seconds": 30.0}
assert len(responses.calls) == 1 # the tool does not loop on its own
Evals against a model API. If you run each prompt many times to measure a pass rate, you're load-testing a rate-limited service. Pace those runs with the same pacer, and record a 429 as an errored run, separate from a failed one. A rate limit tells you nothing about the quality of the model's answer, so it shouldn't count toward the pass rate. But report the count, because a pass rate built on fewer runs than you think deserves less trust.
The discipline behind all of this is the same: know why every live call exists and what it costs, and have a mocked test for everything that doesn't need the network. That applies to your agents as much as to your CI. If you want to build a suite like this from scratch with Copilot in the loop, my API testing courses walk through it.