# Rate limits

Two limits apply to every request at the same time. The one that runs out first stops you.

| Scope | Limit | Window |
|---|---|---|
| Per API key | 200 requests | 10 seconds |
| Per organization, all keys combined | 1,000 requests | 60 seconds |

- Creating more keys does not raise the organization limit: all keys of an organization share it.
- Test keys have the same limits as live keys, so a load test in test mode behaves like production.
- A [batch](/docs/api-reference/batch) counts as one request, whatever the number of items in it.
- `GET /account` returns the limits that apply to you in `limits.per_key` and `limits.per_org`. Read them from there rather than hardcoding them.

## Rate limit headers

Responses carry these headers:

| Header | Meaning |
|---|---|
| `X-RateLimit-Limit` | The request limit of the tightest of your two windows |
| `X-RateLimit-Remaining` | Requests left in that window |
| `X-RateLimit-Reset` | Unix time, in seconds, when that window resets |
| `X-Credits-Remaining` | Your credit balance after this call |
| `X-Request-Id` | Identifier of this request, to quote when you contact support |

A client that watches `X-RateLimit-Remaining` can slow down before it gets refused, instead of after.

## When you go over

The API answers `429` with the error type `rate_limited` and a `Retry-After` header that says how many seconds to wait:

```http
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 3
X-RateLimit-Limit: 200
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1795442534
X-Request-Id: req_01M84BDRQQ7W02D8CWTYP4CB11
```

```json
{
  "error": {
    "type": "rate_limited",
    "message": "Rate limit exceeded. Retry in 3 seconds.",
    "docs": "https://qelka.com/docs/errors#rate_limited"
  }
}
```

A rate-limited request is not billed and has no effect. Sending it again after the wait is safe.

## Retry correctly

Retry `429` after `Retry-After` seconds. Retry `500` and `502` with exponential backoff and a little random jitter, so that many clients that failed together do not all come back at the same moment. Do not retry other errors: they fail the same way every time.

```javascript
const retryable = new Set([429, 500, 502, 503])
const sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds))

export async function callApi(path, body, maxAttempts = 5) {
  for (let attempt = 1; ; attempt += 1) {
    const response = await fetch(`https://api.qelka.com/v1${path}`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${process.env.API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(body),
    })
    if (!retryable.has(response.status) || attempt === maxAttempts) return response
    const retryAfter = Number(response.headers.get('Retry-After'))
    const backoff = Math.min(1000 * 2 ** (attempt - 1), 16000) + Math.random() * 250
    await sleep(retryAfter > 0 ? retryAfter * 1000 : backoff)
  }
}
```

The same logic in Python:

```python
import os
import random
import time

import requests

RETRYABLE = {429, 500, 502, 503}


def call_api(path, body, max_attempts=5):
    for attempt in range(1, max_attempts + 1):
        response = requests.post(
            f"https://api.qelka.com/v1{path}",
            headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
            json=body,
            timeout=15,
        )
        if response.status_code not in RETRYABLE or attempt == max_attempts:
            return response
        retry_after = response.headers.get("Retry-After", "")
        if retry_after.isdigit():
            time.sleep(int(retry_after))
        else:
            time.sleep(min(2 ** (attempt - 1), 16) + random.random() / 4)
```

The [JavaScript SDK](/docs/sdk-js) retries `429`, `502` and `503` responses on its own, so you only need this code if you call the API directly.

## Stay under the limits

- **Send work through a queue with fixed concurrency.** A worker that keeps a handful of requests in flight is easier to keep under 200 requests per 10 seconds than code that fires everything with one `Promise.all`.
- **Check many values per request.** [`POST /batch`](/docs/api-reference/batch) takes up to 100 items and counts as one request. For files, a [bulk job](/docs/api-reference/bulk) processes the rows in the background.
- **Do not check the same value twice.** Store the result with your record. A repeated check counts as a request and costs credits even when the answer comes from the [cache](/docs/caching).
- **Keep background jobs away from user-facing traffic.** All keys share the organization window, so a large import running at full speed can slow down your signup checks. Throttle batch work well below the limits, or move it to a bulk job.

If your workload needs more than these limits allow, write to support@qelka.com with the volume you expect.
