# Rate limits and retries

How 429 and 5xx errors work, and how to retry without making things worse.

Two different things can stop a request: a **rate** problem (too many requests too fast, or no spare capacity on a model right now) and a **budget** problem (the key or the account has no money left). Rate problems pass if you wait. Budget problems do not.

## Limits

- **Per key:** every API key has its own limits per minute, listed in [Limits per key](#key-limits). A rate limit is not something you set in the console today. Write clients that cope with a `429` at any time.
- **Per model:** a model that is short of capacity does not show up as a `429`. You get a `502` (`model_unavailable`), which is also worth retrying. A `429` always comes from your own key: its request or token limit. It is the same for every model, so a `models` list is not tried further.
- **Size:** uploaded images can be up to 20 MB each and audio files up to 25 MB (see [Errors](https://ewest.ai/docs/errors#model-errors)).
- **Time:** a chat response has to start within about 90 seconds; image and audio models have their own limits, and the edge ends any response that has not started after 100 seconds. Use streaming for long chat answers and [jobs](https://ewest.ai/docs/video) for video and music.

## Limits per key

Limits apply to each API key separately, not to your IP address or your whole account. Counts reset every minute. A short burst at the peak can occasionally get through slightly above the stated number, so treat the numbers as a guide for sizing your client, not as an exact meter. Chat, responses, messages and embeddings calls count against the first table:

| Per API key | Limit per minute |
| --- | --- |
| Requests | 600 |
| Tokens | 2,000,000 |

Image, image edit, speech and transcription requests, job creation and job reads have their own per-key limits:

| Per API key | Limit per minute |
| --- | --- |
| Images, image edits, speech and transcription (requests) | 60 |
| Creating video, audio and 3D jobs, counted together (new jobs) | 10 |
| Reading jobs, `GET /v1/jobs` and `GET /v1/jobs/{id}` (job reads) | 600 |

Keys used in the console playground have lower limits than API keys. If you need higher limits for an API key, contact support at [support@ewest.ai](mailto:support@ewest.ai) with your use case and the expected request rate.

## What a limit response looks like

Going over a limit returns HTTP `429` with type `rate_limit_error`, code `rate_limit_exceeded` and a `retry-after` header: the number of seconds to wait. The body uses the usual [error shape](https://ewest.ai/docs/errors). On chat endpoints it is `{"error": {"message": "Rate limit reached for this API key. Retry after the time in the retry-after header.", "type": "rate_limit_error", "param": null, "code": "rate_limit_exceeded"}}`.

On image, audio, video and 3D job requests the message also names the limit, for example `Rate limit reached for this API key: 10 new jobs per minute. Try again in 23 s.` Branch on the status and the code, never on the message. Back off for the `retry-after` seconds, and poll jobs no faster than you need: a slower poll interval, or the job's event stream, keeps you well under the read limit.

## Response headers

When a key has a request or token limit, responses on the chat endpoints can carry OpenAI's header names: `x-ratelimit-limit-requests`, `x-ratelimit-remaining-requests` and the matching `-tokens` headers. Read them if they are there, but do not require them: they can be missing, for example on streamed answers. A `429` for the key's limit carries `retry-after`, in seconds; the example below honours it.

## Budget or rate? 402 versus 429

| You see | It means | Retry? |
| --- | --- | --- |
| `402 insufficient_budget` | This key's budget is used up. | No. Raise the budget or use another key. |
| `402 insufficient_balance` | The organisation's prepaid balance is too low. Only returned once prepaid billing is enforced for your account. | No. Add funds in the console. |
| `429 rate_limit_error` | The key's own request or token limit. | Yes, after the `retry-after` seconds. |

A `402` is final: retrying a budget error never succeeds. A `429` is a rate problem and passes if you wait.

To check before a large request, `GET /v1/key` returns what the calling key may still spend: its budget, spend, remaining amount and limits, and the organisation's prepaid balance. It is free and sees only the key that calls it.

## Retrying with backoff

- Retry only `429` (rate), `500`, `502`, `503`, `504` and network errors such as a dropped connection or a timeout. Never retry `400`, `401`, `402`, `403` or `404`.
- Wait longer after each failure: for example 1 s, 2 s, 4 s, 8 s, up to a ceiling of 30 s.
- Add jitter, a random part of each wait, so clients that failed together do not all come back together.
- If a `retry-after` header is present, wait at least that long.
- Stop after a few attempts (five is plenty) and report the error together with its `x-request-id`.
- Set a client timeout of about 100 seconds, and stream long answers instead of waiting on one big response.

cURL:

```bash
# curl retries 429 and 5xx on its own: it waits 1 s, 2 s, 4 s, ... and honours a retry-after
# header. It never retries a 402 (out of budget). The Python and JavaScript tabs add jitter and a time limit.
curl --retry 5 --retry-max-time 60 https://api.ewest.ai/v1/chat/completions \
  -H "Authorization: Bearer $EWEST_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "ewest/gemini-flash",
       "messages": [{"role": "user", "content": "Hello!"}]}'
```

Python:

```python
import os, random, time, requests
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime

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

def retry_after_seconds(value):  # a number of seconds, or an HTTP date
    try:
        return max(0.0, float(value))
    except (TypeError, ValueError):
        try:
            return max(0.0, (parsedate_to_datetime(value) - datetime.now(timezone.utc)).total_seconds())
        except (TypeError, ValueError):
            return 0.0

def pause(attempt, retry_after=0.0):
    cap = min(30, 2 ** attempt)  # 1 s, 2 s, 4 s, ... at most 30 s
    time.sleep(max(retry_after, random.uniform(cap / 2, cap)))

def chat(payload, max_attempts=5):
    for attempt in range(max_attempts):
        last = attempt == max_attempts - 1
        try:
            res = requests.post(
                "https://api.ewest.ai/v1/chat/completions",
                headers={"Authorization": f"Bearer {os.environ['EWEST_KEY']}"},
                json=payload,
                timeout=100,
            )
        except (requests.ConnectionError, requests.Timeout):
            if last:
                raise
            pause(attempt)
            continue
        if res.ok:
            return res.json()
        try:
            error = res.json().get("error")
        except (ValueError, AttributeError):
            error = None
        if not isinstance(error, dict):
            error = {}
        retryable = res.status_code in RETRY_STATUS
        if not retryable or last:
            raise RuntimeError(f"{res.status_code} {error.get('type')}: {error.get('message')}")
        pause(attempt, retry_after_seconds(res.headers.get("retry-after")))

answer = chat(dict(
    model="ewest/gemini-flash",
    messages=[{"role": "user", "content": "Hello!"}],
))
print(answer["choices"][0]["message"]["content"])
```

JavaScript:

```javascript
const RETRY_STATUS = new Set([429, 500, 502, 503, 504]);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// Wait 1 s, 2 s, 4 s, ... (at most 30 s) with jitter, and at least as long as retry-after says.
const pause = (attempt, retryAfter = 0) => {
  const cap = Math.min(30, 2 ** attempt);
  return sleep(Math.max(retryAfter, cap / 2 + Math.random() * (cap / 2)) * 1000);
};

async function chat(payload, maxAttempts = 5) {
  for (let attempt = 0; ; attempt++) {
    const last = attempt + 1 >= maxAttempts;
    let res;
    try {
      res = await fetch("https://api.ewest.ai/v1/chat/completions", {
        method: "POST",
        headers: { Authorization: `Bearer ${process.env.EWEST_KEY}`, "Content-Type": "application/json" },
        body: JSON.stringify(payload),
        signal: AbortSignal.timeout(100_000),
      });
    } catch (err) {
      // A dropped connection (TypeError) or the 100 s client timeout: worth another try.
      if (last || !(err instanceof TypeError || err?.name === "TimeoutError")) throw err;
      await pause(attempt);
      continue;
    }
    if (res.ok) return res.json();
    const body = await res.json().catch(() => null);
    const error = body?.error;
    const retryable = RETRY_STATUS.has(res.status);
    if (!retryable || last) throw new Error(`${res.status} ${error?.type}: ${error?.message}`);
    await pause(attempt, Number(res.headers.get("retry-after")) || 0);
  }
}

const answer = await chat({
  model: "ewest/gemini-flash",
  messages: [{ role: "user", content: "Hello!" }],
});
console.log(answer.choices[0].message.content);
```

The OpenAI and Anthropic client libraries already retry some errors with backoff, and they retry every `429`, but never a `402`. Check their retry setting before you add a second layer on top.

## Async jobs: do not submit twice

Video and music requests create a job and answer `202`. There is no idempotency key, so every accepted submit creates a new job, and a job that succeeds is billed. After an error response no billable job was started, so retrying that submit is safe (a failed, uncharged record may appear in `GET /v1/jobs`). The risky case is a lost connection or timeout after you sent the request, because you cannot tell whether it was accepted.

- Before you resubmit after a lost response, call `GET /v1/jobs` and look for a recent job with the same model and prompt.
- Keep the job `id` from the `202` response and poll or stream that job. Do not submit again just because a job is slow.
- A job that ends as `failed` is not charged, so submitting a replacement is safe.
- Retry the status call (`GET /v1/jobs/{id}`) freely, with the same backoff.

Responses: continuing a response that wasn't stored (`store: false`, or an id issued before eWest kept conversations) is a 400 with code `previous_response_not_stored`; send the full conversation in `input`. An unknown or deleted response id is a 404 with code `not_found`.

Source: https://ewest.ai/docs/rate-limits
