# Limits and retries

> The limits of an Inola plan, the 429 and 503 answers, the X-RateLimit headers, Retry-After, and ready retry code in Python and JavaScript.

This guide describes the limits that apply to requests to the Inola API, how the API answers when one is
reached, and how a client repeats a request: when, after how long, and when not at all. It needs an
[API key](https://inola.ai/docs/reference/glossary.md#api-key); the retry code needs Python 3.10 or later with `requests`, or
Node.js 18 or later.

## The limits

| limit | applies to | when reached |
|---|---|---|
| requests per minute (RPM) | the organization and the model | [`429 rate_limited`](https://inola.ai/docs/reference/errors.md#rate_limited) with `Retry-After` |
| tokens per minute (TPM) | the organization and the model | [`429 token_rate_limited`](https://inola.ai/docs/reference/errors.md#token_rate_limited) with `Retry-After` |
| monthly tokens of a model (plans that have them) | the organization and the model | [`429 monthly_token_limit`](https://inola.ai/docs/reference/errors.md#monthly_token_limit) until the next billing period |
| monthly documents of a model (plans that count documents) | the organization and the model | [`429 monthly_document_limit`](https://inola.ai/docs/reference/errors.md#monthly_document_limit) until the next billing period |
| the monthly [spend limit](https://inola.ai/docs/reference/glossary.md#spend-limit) set in the console | the organization | [`429 spend_limit_reached`](https://inola.ai/docs/reference/errors.md#spend_limit_reached) until the next period or a higher limit |
| unfinished batch work | the organization, across all models | [`429 batch_queue_limit`](https://inola.ai/docs/reference/errors.md#batch_queue_limit) on `POST /v1/batches` |
| batch work per completion window | the organization | [`429 batch_window_limit`](https://inola.ai/docs/reference/errors.md#batch_window_limit) on `POST /v1/batches` |
| balance or payment | the organization | [`402 payment_required`](https://inola.ai/docs/reference/errors.md#payment_required) until a top-up or the payment goes through |
| document length: the model's maximum in tokens | each document | [`413 too_long`](https://inola.ai/docs/reference/errors.md#too_long); split the document |
| request body size | each request | [`413 body_too_large`](https://inola.ai/docs/reference/errors.md#body_too_large) |

The values depend on your [plan](https://inola.ai/docs/reference/glossary.md#plan). They are not written on this page:

- `GET /v1/models` lists, for each model, the `limits` of your plan (`rpm`, `tpm`, `monthly_tokens`,
  `monthly_documents`; `null` when the plan has no such limit) and the maximum document length of each version
  (`context_window`);
- the console ([https://console.inola.ai](https://console.inola.ai), section **Billing**) shows what each plan includes.

Short documents usually reach the request limit first, long ones the token limit. The per-minute limits are shared by
all keys of the organization.

## Headers of every response

Every response carries the current state of the per-minute limits of its model:

| header | meaning |
|---|---|
| `X-RateLimit-Limit-Requests` | requests per minute of the plan |
| `X-RateLimit-Remaining-Requests` | requests left |
| `X-RateLimit-Reset-Requests` | time until the request limit is full again, such as `6s` |
| `X-RateLimit-Limit-Tokens` | tokens per minute of the plan |
| `X-RateLimit-Remaining-Tokens` | tokens left |
| `X-RateLimit-Reset-Tokens` | time until the token limit is full again |

```bash
curl -sS -i "https://api.inola.ai/v1/infer" \
  -H "Authorization: Bearer $INOLA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "cordon-mini", "input": {"state": "Opening hours: 9 to 17 on weekdays."}}'
```

## The `429` answer

A `429` is a limit of your plan unless its `error.code` is `overloaded` or `serverless_cold` (our capacity, see
[below](#over-capacity-429-with-its-own-code)). The body of a plan's limit says which limit was reached and, when there
is one, what the next plan allows:

| field | meaning |
|---|---|
| `error.code` | the limit code, as in the table above |
| `error.message` | the same in words, for example `<plan> plan limit reached: <value> requests/min for <model>.` followed by what the next plan allows |
| `error.limit.name` | `requests_per_minute`, `tokens_per_minute`, `monthly_tokens`, `monthly_documents`, `spend_limit`, `batch_queue_chars` or `batch_window_chars` |
| `error.limit.value` | the value of the limit on your plan |
| `error.limit.unit` | `requests`, `tokens`, `documents`, `currency` or `chars`; `currency` (the spend limit) is an amount in euros (EUR) |
| `error.limit.window` | `1m`, `month`, `completion_window`, or `null` for unfinished batch work |
| `error.limit.model` | the model the limit belongs to, for per-model limits |
| `error.limit.reset_at` | when the limit lets requests through again (ISO 8601); `null` for batch limits, which free up as batches finish |
| `error.plan` | the code of your plan |
| `error.upgrade` | the next plan: `plan`, `value` (its value of the same limit) and `url` (where to change the plan); or `contact_url` when there is no next plan; absent for `spend_limit_reached`, a limit you set yourself |
| `error.doc_url` | when present, the section of this code on [Error codes](https://inola.ai/docs/reference/errors.md) |

## `Retry-After`

`Retry-After` (seconds) is the API's estimate of when the request will pass, not a constant:

- per-minute limits (`rate_limited`, `token_rate_limited`): the time until enough capacity refills;
- monthly limits and the spend limit: the time until the next billing period (`error.limit.reset_at`);
- `429 overloaded` and `503 unavailable`: the expected time until the request can be served;
- `507 storage_full`: the time after which it is worth sending the request again (the storage is measured on every file and batch request);
- `429 serverless_cold`: only when the model is starting — the expected time until it serves real-time requests;
  without the header there is no such estimate.

## Over capacity: `429` with its own code

When the service is temporarily over capacity, the answer is
[`429 overloaded`](https://inola.ai/docs/reference/errors.md#overloaded) — not a limit of your plan: read `error.code` to tell it from
the plan's limits, which answer `429` too. A model that is
not served at the moment answers [`503 unavailable`](https://inola.ai/docs/reference/errors.md#unavailable). Both carry
`Retry-After`. A real-time request to a model that is not running now — most often one that runs on on-demand
capacity, but any model while its regular capacity is down — may be held while the model starts — the answer can then take several minutes, so give such requests a timeout of at least 11
minutes — or be answered [`429 serverless_cold`](https://inola.ai/docs/reference/errors.md#serverless_cold) (at once, or when the model
did not become ready within that wait); a key of the Free plan is never held — it gets that answer at once. That
answer carries `Retry-After` only when the model is starting; without it
send the documents through the [Batch API](https://inola.ai/docs/guides/batches.md).

## `507`: the batch storage is full

When the storage for batch files cannot take one more batch, `POST /v1/files` and `POST /v1/batches` answer
[`507 storage_full`](https://inola.ai/docs/reference/errors.md#storage_full) with `Retry-After`. It is not a limit of your plan and
nothing was stored or billed. Send the request again after `Retry-After` seconds; the service frees space on its own.
Batches already accepted keep running, and real-time requests are not affected.

## `429 unused_uploads_limit`: too many files no batch uses

Files you upload and do not use in a batch yet are bounded twice: per API key (by default two files of the maximal
size: one ready for a batch and one being prepared) and per organization, by the volume your plan gives to such files,
whatever number of API keys uploads them. Uploads in progress count with their declared size (`Content-Length`).
Over either limit, `POST /v1/files` answers
[`429 unused_uploads_limit`](https://inola.ai/docs/reference/errors.md#unused_uploads_limit); other organizations are not affected.
Create batches from the uploaded files or delete the ones you do not need (`DELETE /v1/files/{id}`), then upload
again. The volume of the plan is in the console, on the plan's page.

## When to repeat a request

| status | repeat? | how |
|---|---|---|
| `429` per-minute limits | yes | after `Retry-After` |
| `429` monthly limits, spend limit | not until the period ends | `Retry-After` is the time to the next period; a higher limit or plan in the console lifts it sooner |
| `429` batch limits | later | after earlier batches finish, or with a smaller batch |
| `429 overloaded`, `503` | yes | after `Retry-After` |
| `429 serverless_cold` without `Retry-After` | no | send the documents as a batch |
| `500` | yes | with growing pauses (exponential backoff) |
| no response (network error, timeout) | yes | with growing pauses |
| `400`, `401`, `402`, `403`, `404`, `410`, `413` | no | the same request gets the same answer; the cause is fixed first |

Rejected requests are not billed, so repeating after `Retry-After` costs nothing until the request passes.

## Retry code

The functions below send a real-time request and repeat it by the rules above. They return the last response, so the
caller sees a `429` of a monthly limit or any client error.

### Python

Save as `retry.py` and run `python retry.py`.

```python
"""POST to the Inola API with the retry rules of the API.

Python 3.10 or later, `pip install requests`, key in INOLA_API_KEY.
"""

import os
import random
import sys
import time

import requests

API_URL = "https://api.inola.ai"
API_KEY = os.environ["INOLA_API_KEY"]

def post_with_retry(path, payload, *, max_attempts=5, max_wait_s=60.0, timeout_s=30.0):
    """Send the request; repeat it only when the API says that repeating can succeed.

    429 and 503: wait Retry-After seconds, if that is at most max_wait_s; without Retry-After, return at once.
    500 and network errors: wait with growing pauses (1, 2, 4 s, with jitter).
    Any other status is returned at once: repeating the same request gives the same answer.
    """
    for attempt in range(1, max_attempts + 1):
        backoff = min(2 ** (attempt - 1), max_wait_s) * random.uniform(0.8, 1.2)
        try:
            r = requests.post(f"{API_URL}{path}", json=payload, timeout=timeout_s,
                              headers={"Authorization": f"Bearer {API_KEY}"})
        except requests.RequestException:
            if attempt == max_attempts:
                raise
            time.sleep(backoff)
            continue
        if r.status_code in (429, 503):
            if "Retry-After" not in r.headers:
                return r  # no estimate (429 serverless_cold): the caller sends a batch instead
            wait = float(r.headers["Retry-After"])
            if wait > max_wait_s or attempt == max_attempts:
                return r  # a monthly limit or the spend limit: the caller decides
            time.sleep(wait)
        elif r.status_code >= 500 and attempt < max_attempts:
            time.sleep(backoff)
        else:
            return r
    return r

if __name__ == "__main__":
    r = post_with_retry("/v1/infer", {"model": "cordon-mini", "input": {"state": "Opening hours: 9 to 17 on weekdays."}})
    print(r.status_code, "requests left this minute:", r.headers.get("X-RateLimit-Remaining-Requests"))
    if r.status_code != 200:
        error = r.json()["error"]
        sys.exit(f"{error['code']}: {error['message']}")
    print("injection" if r.json()["output"]["answers"]["injection"]["verdict"] else "clean")
```

### JavaScript

Save as `retry.mjs` and run `node retry.mjs`.

```javascript
// POST to the Inola API with the retry rules of the API.
// Node.js 18 or later, key in INOLA_API_KEY. Run: node retry.mjs
const API_URL = "https://api.inola.ai";
const API_KEY = process.env.INOLA_API_KEY;
const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));

// Send the request; repeat it only when the API says that repeating can succeed.
// 429 and 503: wait Retry-After seconds, if that is at most maxWaitS; without Retry-After, return at once.
// 500 and network errors: wait with growing pauses (1, 2, 4 s, with jitter).
// Any other status is returned at once: repeating the same request gives the same answer.
export async function postWithRetry(path, payload, { maxAttempts = 5, maxWaitS = 60, timeoutS = 30 } = {}) {
  let response;
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    const backoff = Math.min(2 ** (attempt - 1), maxWaitS) * (0.8 + Math.random() * 0.4);
    try {
      response = await fetch(`${API_URL}${path}`, {
        method: "POST",
        headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json" },
        body: JSON.stringify(payload),
        signal: AbortSignal.timeout(timeoutS * 1000),
      });
    } catch (err) {
      if (attempt === maxAttempts) throw err;
      await sleep(backoff);
      continue;
    }
    if (response.status === 429 || response.status === 503) {
      const header = response.headers.get("Retry-After");
      if (header === null) return response; // no estimate (429 serverless_cold): the caller sends a batch instead
      const wait = Number(header) || 1;
      if (wait > maxWaitS || attempt === maxAttempts) return response; // a monthly limit or the spend limit
      await sleep(wait);
    } else if (response.status >= 500 && attempt < maxAttempts) {
      await sleep(backoff);
    } else {
      return response;
    }
  }
  return response;
}

const response = await postWithRetry("/v1/infer", { model: "cordon-mini", input: { state: "Opening hours: 9 to 17 on weekdays." } });
console.log(response.status, "requests left this minute:", response.headers.get("X-RateLimit-Remaining-Requests"));
const body = await response.json();
if (!response.ok) {
  console.error(`${body.error.code}: ${body.error.message}`);
  process.exit(1);
}
console.log(body.output.answers.injection.verdict ? "injection" : "clean");
```

Both scripts print, for example:

```text
200 requests left this minute: <the value of X-RateLimit-Remaining-Requests>
clean
```

## Next steps

- [Protect a RAG pipeline](https://inola.ai/docs/guides/protect-a-rag-pipeline.md) — a wrapper with these rules and a fail-closed default.
- [Error codes](https://inola.ai/docs/reference/errors.md) — every code and what to do.
- [Tokens and billing](https://inola.ai/docs/concepts/tokens-and-billing.md) — what is billed.
