FDE Times dataFDE jobs open 915▼19 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 54Companies hiring 201Remote-friendly 24%Median US pay $200kTop hirer Databricks 109
中文VI

The newspaper of the Forward Deployed Engineer

Guides

The API said 202 Accepted. The report still isn't there

A 202 only promises the work will be processed; how long to wait, and when to give up, is left entirely to the client.

ShareLinkedInFacebookX

In brief

  • A 202 means only that the request was received, not that the report is ready or that the job will succeed.
  • The httpx retries option retries only connection errors; 429, 503 and the wait between polls are yours to write.
  • A read timeout does not cap total waiting time, so the polling loop needs its own deadline.
Decision tree for a single poll. The first question is the job status: if done, download the file; if failed, report the error; if still running, check for a Retry-After header. If there is one, wait as the server instructs; if not, use backoff with jitter. Both branches lead to the question of whether the deadline has passed. If it has, stop for good (highlighted in orange); if not, go back and poll again.
On each polling round, the client reads the job status in the body, gives priority to the server's Retry-After, falls back to backoff with jitter if it is missing, and always checks the overall deadline before waiting again.

Microsoft’s C# sample for the Power BI exportToFile API contains a very short note about the Retry-After header: it holds the time to wait before the next poll, but it does not always have a value.

That note says more about integration work than any architecture slide. Even a major report export API such as exportToFile runs asynchronously and makes the client poll, so your client has to behave correctly even when the server does not send everything it should.

FDEs run into this constantly. A client wants its revenue report pulled into a pipeline every night, or wants an agent to export PDFs for the operations team. The API call itself takes five lines of code. The hard part is the waiting: how often to ask, when to stop, and how to avoid accidentally creating ten identical export jobs on the client’s system.

This guide builds a Python client with httpx that does four things. It creates the export exactly once, polls according to Retry-After, falls back to backoff with jitter, and stops on its own when a deadline passes. The API in the examples is hypothetical, to keep things readable. The /exports endpoint, the status field and the succeeded/failed values will differ from client to client.

What you need before you start

You need Python 3.10 or later, the httpx library installed with pip install httpx, and an API that behaves as follows. POST /exports returns 202 Accepted with a Location header pointing to a status resource. A GET to that address returns the job’s status. When the job finishes, the server either returns the result in the body or redirects to a file.

One point to keep in mind before writing a single line. RFC 9110 defines 202 as meaning the request has been accepted for processing, but the processing has not been completed. So a 202 does not promise the report is ready, nor that the job will succeed.

Step 1: build the client with timeouts and connection retries

import random, time, uuid
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
import httpx

client = httpx.Client(
    base_url="https://api.customer.example",  # hypothetical
    transport=httpx.HTTPTransport(retries=3),
    timeout=httpx.Timeout(10.0),
    headers={"Authorization": "Bearer <token>"},
)

By default, httpx raises a TimeoutException after 5 seconds of network inactivity. Here it is raised to 10 seconds because client endpoints are often slow. The number is your choice; tune it to the real system.

Do not misread retries=3. The httpx documentation states plainly that the transport retries only on httpx.ConnectError or httpx.ConnectTimeout. A 503 response will not be retried, and the documentation points to tools such as tenacity for that case. Check: disconnect from the network and make a call. You should see a ConnectError after a few attempts, not an endless loop.

Step 2: create the export exactly once

The POST that creates the export is not idempotent. RFC 9110 advises that a client should not automatically retry such a request unless it knows the semantics are in fact idempotent or can detect that the original request was never applied.

Retrying connection errors in step 1 fits the second condition, because if the connection never opened, the request cannot have reached the server. A timeout midway through is different: you do not know whether the server created the job.

The way out is an idempotency key. According to Microsoft’s description of the Asynchronous Request-Reply pattern, an API can require the client to send a key with the first request. On receiving a duplicate key, the back end returns the existing status resource instead of queuing a second job. The header name and the status code for a duplicate key used here are assumptions; read the client’s API documentation.

def create_export(params: dict, key: str) -> str:
    r = client.post("/exports", json=params,
                    headers={"Idempotency-Key": key})
    # 202: new job; 200: duplicate key, existing job returned (assumed)
    if r.status_code in (200, 202) and "Location" in r.headers:
        return r.headers["Location"]
    r.raise_for_status()
    raise RuntimeError(f"Expected 202 or 200, got {r.status_code}")

key = str(uuid.uuid4())  # store this key with the job record

The function accepts both 200 and 202. If it accepted only 202, a repeat call with the old key could get back the very job already running and still throw, and you would lose the whole benefit of the idempotency key.

Check: call create_export twice with the same key. If the API supports keys, both calls must return the same Location. If you get two different addresses, the API does not support them, and you must not automatically resend the POST on a timeout.

Step 3: parse Retry-After in both forms

RFC 9110 allows Retry-After to be either an HTTP-date or a number of seconds. Write int(value) because you are used to the seconds form, and the function will die on precisely the day the client’s gateway sends a date.

def parse_retry_after(value: str | None) -> float | None:
    if not value:
        return None
    v = value.strip()
    if v.isdigit():
        return float(v)
    try:
        when = parsedate_to_datetime(v)
    except (TypeError, ValueError):
        return None
    return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())

The function returns None when the header is missing or malformed. That is the case the Power BI sample warns about, and the loop in step 4 will fall back to its own wait time.

Step 4: poll with backoff, jitter and a deadline

In Microsoft’s pattern, every successful call to the status endpoint returns 200 OK, even while the job is still running. A client’s API may behave differently, for instance returning 202 for as long as the job runs, so the code below does not rely on the status code to tell when the job is done. It reads the body.

RFC 6585 adds another case: a 429 Too Many Requests response may include Retry-After to say how long to wait before calling again.

def wait_for_export(status_url: str, deadline_s=900, base=2.0,
                    cap=60.0, min_wait=1.0):
    expires_at = time.monotonic() + deadline_s
    attempt = 0
    while True:
        r = client.get(status_url)
        if r.status_code == 303:
            return r.headers["Location"]          # step 5
        if r.status_code in (429, 503):
            wait = parse_retry_after(r.headers.get("Retry-After"))
        else:
            r.raise_for_status()
            body = r.json()
            if body.get("status") == "succeeded":
                return body["result_url"]          # hypothetical
            if body.get("status") == "failed":
                raise RuntimeError(f"Export failed: {body}")
            wait = parse_retry_after(r.headers.get("Retry-After"))
        if wait is None:
            wait = random.uniform(0, min(cap, base * 2 ** attempt))
        wait = max(wait, min_wait)                 # no rapid-fire polling
        attempt += 1
        if time.monotonic() + wait > expires_at:
            raise TimeoutError("Export deadline exceeded")
        time.sleep(wait)

The code rests on three choices. The server’s Retry-After always takes priority, because the server knows its own load better than you do. The fallback wait grows exponentially up to a cap, and is then picked at random between zero and that value.

The Amazon Builders’ Library calls this randomness jitter: it spreads retries out over time so that hundreds of clients do not knock on the door at once.

The third choice is expires_at. The httpx documentation defines the read timeout as the maximum time to wait for a chunk of data. It does not cap the total duration of a request, let alone the whole polling loop. Without a separate deadline, a job stuck on the client’s side will hold your worker forever.

One small detail remains: the min_wait floor. A Retry-After of 0, an HTTP-date already in the past, or a jitter draw close to zero all produce a wait of almost nothing. Without the floor, the loop would hammer the client’s endpoint with requests.

Check: stand up a fake endpoint that returns {"status": "running"} forever and set deadline_s=30. The function must raise TimeoutError before the 30-second mark, the logged waits should show visible randomness, and none should be under 1 second.

Step 5: fetch the file, even when redirected

If the status endpoint redirects when the job is done, Microsoft recommends 303 See Other. That code tells the client to send a GET to the new URL, whatever method the original request used. httpx does not follow redirects by default, and raise_for_status() raises on any non-2xx response, including an unfollowed 303. That is why step 4 catches the 303 before calling raise_for_status().

def download_result(url: str, path: str) -> None:
    r = client.get(url)
    r.raise_for_status()
    with open(path, "wb") as f:
        f.write(r.content)  # simplified: reads the whole file into RAM

loc = create_export({"report": "monthly-revenue"}, key)
download_result(wait_for_export(loc), "revenue.pdf")

For large files, stream the download instead of reading all of r.content into memory. The version above is kept short for readability.

The mistakes that break this client in production

The most common mistake is treating 202 as done and reading the file straight away. The second is wrapping the whole create_export function in a generic retry decorator, so that every timeout spawns another heavy job on the client’s data warehouse. The third is believing HTTPTransport(retries=...) takes care of everything, when 503 and 429 pass straight through.

Two more are harder to spot. One is checking only the status code while polling, when in Microsoft’s pattern the status endpoint returns 200 the whole time the job runs and the real state lives in the body. The other is parsing Retry-After with int(), which works fine while the server sends seconds and then crashes the first time it receives an HTTP-date.

On site, call it by hand before writing code

At the client’s site, the first thing to do is make one call by hand and record everything: the POST’s status code, the Location header, every polling response, and whether Retry-After is present and in which form.

Those ten minutes of notes give you enough to set base, cap, min_wait and deadline_s from real data instead of guesses. Then ask the client’s team one question: does the API accept an idempotency key, and if not, what harm does a duplicate job do?

In interviews or on a CV, do not write “integrated REST APIs”. Say specifically that you wrote a client for an asynchronous export API with an idempotency key, one that respects Retry-After and enforces an overall deadline. An FDE interviewer will know at once that you have lived with the consequences of someone else’s slow system.

The next time someone tells you “the API returns 202, so we’re fine”, ask them: and then how long does the client wait?

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
8 sources
Read next on the roadmap · Stage 1: FoundationsWhy an eval suite persuades clients better than a slick agent demoA single pass rate can hide the very failure a client's risk team fears most, and splitting the score by case type brings it into view.