# Retrying safely

> Which errors to retry, how to back off, and how to avoid paying twice for a request that timed out on your side.

A retry should fix a transient problem without running billed work twice. Three rules cover most cases.

## 1. Retry only transient errors

| Retry with backoff | Fix first, then send again |
|---|---|
| HTTP 429 / `40202` (wait for `Retry-After`) | `40501` Invalid Field, `40503`, `40006`, HTTP 400, 415, 422 |
| HTTP 500 / `50000`, HTTP 502 `upstream_error` | `40100`, `40101`, HTTP 401, 403 |
| Network errors and timeouts on `GET` | `40210` / HTTP 402 (top up first) |
| `40601` / `40602` on `task_get` (wait, then check again) | `40402` (the route isn't served), `40400`, `40401` |

`40102` (No Search Results) is a real answer, not a transient failure. Retrying it right away usually returns the same thing.

## 2. Back off with jitter

```python
import random
import time
import requests

RETRYABLE = {429, 500, 502, 503, 504}

def request_with_retries(method, url, *, max_attempts=5, **kwargs):
    for attempt in range(max_attempts):
        try:
            res = requests.request(method, url, timeout=120, **kwargs)
        except (requests.ConnectionError, requests.Timeout):
            if method != "GET":
                raise  # a POST may have run; see rule 3
            res = None
        if res is not None and res.status_code not in RETRYABLE:
            return res
        if attempt == max_attempts - 1:
            break
        if res is not None and res.headers.get("Retry-After"):
            delay = int(res.headers["Retry-After"])
        else:
            delay = min(60, 2 ** attempt) * random.uniform(0.5, 1.0)
        time.sleep(delay)
    if res is None:
        raise RuntimeError("no response after retries")
    return res
```

Task-level errors arrive inside an HTTP 200, so also check each `tasks[].status_code`. Re-send only the tasks that failed with `50000`, not the whole array.

```python
body = res.json()
retry = [t["data"] for t in body["tasks"] if t["status_code"] == 50000]
```

`t["data"]` is the task you sent, echoed back, so you can re-post it as is.

## 3. Don't pay twice for a timed-out POST

We don't support idempotency keys yet. If your client times out waiting for a live `POST`, the request may still have run and been billed. Before retrying:

- **Prefer `task_post` for anything you'd retry.** It answers immediately with a task id and `cost: 0`. Retrying `task_get` is free and safe.
- **Use a `tag`** with a stable value per unit of work (for example `"2026-12-03:trail running shoes:2840"`), so you can recognize a task that already ran in `tasks_ready` or your postback handler.
- **Read back instead of re-running.** On the Crawl API, `GET /v1/crawls/{id}` and the crawl list return what already ran at no cost.
- **Set a generous client timeout** for live calls: 120 seconds or more. Pages are fetched with up to a 60-second budget per task, and a live request runs its tasks one after another.

## SDK behavior

The Python and TypeScript SDKs (Crawl API only) retry 429 on any method, honoring `Retry-After` up to 60 seconds, and 5xx and network errors on `GET` with exponential backoff and full jitter. They don't retry a `POST` after a 5xx or read timeout, for the reason above. See [SDKs](https://dataforgaio.com/docs/sdks.md).
