# Durable requests

What a 202 means, how to choose the wait window with the Prefer header, how to poll GET /v1/requests/{id}, deadlines, and how long results are kept.

Most calls finish in a second or two. Some need longer: large scrapes, slow upstream jobs, a call that is being retried after a failed attempt. Every call is therefore **durable**: it has an id from the moment it starts, it keeps running if your connection gives up, and its result is stored so you can collect it later.

## The wait window

A call holds your HTTP request open for up to **10 seconds**. If the result is ready by then, you get `200 OK` with the envelope as usual. If not, you get `202 Accepted` and the call **keeps running**:

```http title="202 Accepted"
HTTP/1.1 202 Accepted
Location: /v1/requests/req_01JBXS6Z8B0D2F4H6K8M0P2R4T
Retry-After: 2
X-Request-Id: req_01JBXS6Z8B0D2F4H6K8M0P2R4T
Content-Type: application/json

{
  "requestId": "req_01JBXS6Z8B0D2F4H6K8M0P2R4T",
  "sku": "reddit.search",
  "status": "running",
  "createdAt": "2026-10-30T14:05:09.120Z",
  "finishedAt": null,
  "expiresAt": "2026-10-30T14:20:09.120Z",
  "retryAfterSeconds": 2
}
```

A `202` is not an error and nothing was lost. Do **not** send the call again to "check on it": that starts a second job and bills it. Poll the request instead, or retry with the same `Idempotency-Key`, which returns the running request rather than starting another one.

## Choosing the wait with Prefer

The `Prefer` request header ([RFC 7240](https://www.rfc-editor.org/rfc/rfc7240)) sets the window per call:

| Header | Behaviour |
|---|---|
| none | Wait up to 10 seconds, then `202`. |
| `Prefer: wait=30` | Wait up to 30 seconds. Values above 90 are treated as 90. |
| `Prefer: respond-async` | Answer `202` right after the call is accepted and its credits are held. |
| `Prefer: respond-async, wait=5` | Wait up to 5 seconds, then `202`. |

When we honour a preference, the `202` carries a `Preference-Applied` header with the value used, for example `Preference-Applied: wait=30`. A malformed value is ignored and the default applies. Set your HTTP client's timeout comfortably above the wait you ask for.

`respond-async` suits job queues and batch work: submit many calls quickly, keep the request ids, and collect the results afterwards.

## Polling

`GET https://api.primaryapi.com/v1/requests/{id}`

Auth: API key with run, view or full access, or a dashboard session

Poll with the id from the `202` body or the `Location` header. Wait `retryAfterSeconds` (2) between polls; for jobs that take minutes, back off further. Polling is free; it counts toward [rate limits](/docs/rate-limits) like any request.

| `status` | Meaning | What the snapshot carries |
|---|---|---|
| `queued`, `running` | Still working | `retryAfterSeconds`, and `expiresAt`: the deadline |
| `succeeded` | Done | `result` (the full envelope), `credits`, `finishedAt`, and `expiresAt`: when the stored result will be deleted |
| `failed` | Every attempt failed, or the request was refused while running | `error: { code, message }` and `credits` (always 0) |
| `expired` | Passed its deadline before finishing | `error` with code `timeout`; nothing was charged |

```json title="GET /v1/requests/req_01JBXS6Z… → 200 OK"
{
  "requestId": "req_01JBXS6Z8B0D2F4H6K8M0P2R4T",
  "sku": "reddit.search",
  "status": "succeeded",
  "createdAt": "2026-10-30T14:05:09.120Z",
  "finishedAt": "2026-10-30T14:05:21.884Z",
  "expiresAt": "2026-10-31T14:05:21.884Z",
  "credits": 2,
  "result": {
    "output": { "found": true, "data": { "posts": ["…"], "nextCursor": null } },
    "provider": "PrimaryAPI",
    "credits": 2,
    "items": 1,
    "requestId": "req_01JBXS6Z8B0D2F4H6K8M0P2R4T",
    "nextCursor": null
  }
}
```

A poll loop:

```ts tab="TypeScript"
const API = 'https://api.primaryapi.com';
const headers = { Authorization: `Bearer ${process.env.PRIMARYAPI_API_KEY}`, 'Content-Type': 'application/json' };
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

export async function runAndWait(sku: string, input: object) {
  const res = await fetch(`${API}/v1/run/${sku}`, {
    method: 'POST',
    headers: { ...headers, 'Idempotency-Key': crypto.randomUUID() },
    body: JSON.stringify(input),
  });
  const body = await res.json();
  if (res.status === 200) return body; // finished within the wait window
  if (res.status !== 202) throw new Error(`${body.code}: ${body.error}`);

  let delay = (body.retryAfterSeconds ?? 2) * 1000;
  for (;;) {
    await sleep(delay);
    const snap = await (await fetch(`${API}/v1/requests/${body.requestId}`, { headers })).json();
    if (snap.status === 'succeeded') return snap.result;
    if (snap.status === 'failed' || snap.status === 'expired') throw new Error(`${snap.error.code}: ${snap.error.message}`);
    delay = Math.min(delay * 1.5, 15_000); // back off for long jobs
  }
}
```

```python tab="Python"
import os
import time
import uuid
import requests

API = "https://api.primaryapi.com"
HEADERS = {"Authorization": f"Bearer {os.environ['PRIMARYAPI_API_KEY']}"}

def run_and_wait(sku: str, payload: dict) -> dict:
    res = requests.post(
        f"{API}/v1/run/{sku}",
        headers={**HEADERS, "Idempotency-Key": str(uuid.uuid4())},
        json=payload,
        timeout=30,
    )
    body = res.json()
    if res.status_code == 200:
        return body  # finished within the wait window
    if res.status_code != 202:
        raise RuntimeError(f"{body['code']}: {body['error']}")

    delay = body.get("retryAfterSeconds", 2)
    while True:
        time.sleep(delay)
        snap = requests.get(f"{API}/v1/requests/{body['requestId']}", headers=HEADERS, timeout=30).json()
        if snap["status"] == "succeeded":
            return snap["result"]
        if snap["status"] in ("failed", "expired"):
            raise RuntimeError(f"{snap['error']['code']}: {snap['error']['message']}")
        delay = min(delay * 1.5, 15)  # back off for long jobs
```

## Deadlines

Every request has a deadline, 15 minutes after it starts by default, shown as `expiresAt` while it runs. A request still unfinished at its deadline is marked `expired` with the error code `timeout`, and the credits held for it come back in full.

A paid upstream job is submitted **at most once**. If something on our side interrupts a request (for example a server restart), it is expired and its credits come back, rather than it being re-run silently, so you are never billed twice for the same job. If you still need the data, send the call again.

## Stored results

The full envelope of every successful call is stored after it finishes, for as long as your workspace's plan keeps results:

| Plan | Results are kept |
|---|---|
| Pay as you go | 24 hours |
| Builder | 7 days |
| Pro | 30 days |
| Scale | 90 days |
| Enterprise | 90 days, or as agreed |

The period is fixed when the request is made, from the plan in force then: changing plans later doesn't shorten or extend it. While a result is stored:

- `GET /v1/requests/{id}` includes it as `result`,
- `GET /v1/results/{id}` returns it directly, for free, and accepts the `fields`, `max_items` and `summary` [trimming parameters](/docs/making-requests#make-responses-smaller),
- an `Idempotency-Key` retry within 24 hours returns it with `replayed: true` ([Idempotency](/docs/idempotency): the key's window is 24 hours on every plan).

`GET https://api.primaryapi.com/v1/results/{id}`

Auth: API key with run, view or full access, or a dashboard session

```bash
curl -sS "https://api.primaryapi.com/v1/results/req_01JBXS6Z8B0D2F4H6K8M0P2R4T?fields=title,permalink&max_items=10" \
  -H "Authorization: Bearer $PRIMARYAPI_API_KEY"
```

After that the output is deleted. The request stays in your history with its status, cost and timing, and its snapshot reports `resultExpired: true`; `GET /v1/results/{id}` then answers `404 not_found`. It also answers `404` while the request is still running (with `retryAfterSeconds`) and for requests that failed. Requests are visible only to the account that made them.

## In the MCP server

`run_api` waits within the same window. If the call is still running, the tool result says so and gives the `requestId`; call `get_request` after the suggested delay, and `read_result` to re-read a finished result with `fields` and `max_items`. See [MCP server](/docs/mcp-server).
