# Limits

> Key spending limits, project budgets and budget alerts, the company balance and low-balance alerts, the daily limit on free models, rate limits and concurrent requests (429) and the request body size limit; what happens when you hit each one and how to respond.

For a request to go through, several limits have to allow it at once. This page covers each of them, the response you get when you hit one, and what your application should do about it.

| Limit                           | Where it is set        | When reached             |
| ------------------------------- | ---------------------- | ------------------------ |
| Key spending limit              | The API key's settings | `402`                    |
| Project budget                  | The project's settings | `402`                    |
| Company balance                 | By topping up credits  | `402` (paid models)      |
| Daily limit on free models      | Your plan              | `429` (free models)      |
| Rate limit per key              | Lykia                  | `429` with `Retry-After` |
| Paid requests in flight at once | Lykia                  | `429`                    |
| Request body size               | Lykia                  | `413`                    |

## Key spending limit

Each API key can have a spending limit in USD and a reset window (none, daily, weekly or monthly). Windows are calculated in UTC. When spending in the current window reaches the limit, requests with that key return `402` until the next window starts. A key whose reset window is "none" has a lifetime limit: requests are only accepted again once you raise the limit or switch to a new key.

Spending cannot go past the limit. Before each request, Lykia reserves the request's maximum cost against what is left of the limit, together with the cost of requests still in flight (see [Reservations](https://www.getlykia.com/en/docs/guides/credits-and-billing#reservations)). When what is left cannot cover the model's full output, the output limit is lowered and reported in the `X-Max-Tokens-Applied` header. When it cannot cover the prompt plus a minimal completion, the request returns `402` even though the limit has not been fully used.

`GET /key` shows how much is left:

```json
{
  "data": {
    "label": "lyk-v1-3f9a…c41e",
    "limit": 50,
    "limit_reset": "monthly",
    "usage": 18.47172,
    "limit_remaining": 31.52828,
    "company": {
      "id": "6b0472819bcb6b3a1239379b",
      "name": "Acme Products"
    },
    "project": {
      "id": "6b0472819bcb6b3a1239379d",
      "name": "Support bot"
    }
  }
}
```

More in [Authentication and API keys](https://www.getlykia.com/en/docs/guides/authentication#spending-limits-and-reset-windows).

## Project budget

A project can have a budget in USD for a period: daily, weekly, monthly or the project's lifetime. When the combined spending of all the project's keys reaches the budget, requests in the project return `402` until the next period. The budget is enforced the same way as a key limit: each request reserves its maximum cost first, so spending cannot go past the budget, and a request that the rest of the budget cannot cover returns `402` early.

Lykia warns you before that happens: when spending passes 80% of the budget and when it reaches 100%, the people who manage the project and those who handle billing get a notification in the dashboard and by email, once per period. See [Projects](https://www.getlykia.com/en/docs/guides/projects#budget).

## Company balance

A request to a paid model needs a company credit balance above zero, otherwise it returns `402`. It also needs enough available balance (the balance minus what requests in flight have reserved) to cover its prompt and a minimal completion; a request that does not fit returns `402` before the balance reaches zero. A company still on the Free plan gets `402` for paid models too, with a message that asks for a top-up. Requests to free models are not subject to these checks. Requests sent with the project's own provider keys are not either, except that once the balance is at or below zero and the company's BYOK usage this month has passed the plan's allowance, they return `402` too, because they now incur a fee ([BYOK](https://www.getlykia.com/en/docs/guides/byok#billing)).

```json
{
  "error": {
    "message": "Insufficient credits. Add credits to your balance, or add your own provider key (BYOK) to this project.",
    "type": "invalid_request_error",
    "code": "insufficient_credits",
    "status": 402,
    "metadata": {
      "reason": "insufficient_credits"
    }
  }
}
```

```json
{
  "error": {
    "message": "Insufficient credits: your available balance cannot cover this request's prompt and a minimal completion. Top up, or shorten the prompt or max_tokens.",
    "type": "invalid_request_error",
    "code": "insufficient_credits",
    "status": 402,
    "metadata": {
      "reason": "insufficient_credits"
    }
  }
}
```

Set a low-balance threshold on the **Credits** page to be notified when the balance drops below it, and turn on automatic top-up to keep it from running out: [Credits and billing](https://www.getlykia.com/en/docs/guides/credits-and-billing#low-balance-alerts).

Retrying does not fix a `402`. Read the error message, then top up, raise the key limit or project budget, or wait for the next period.

## Daily limit on free models

Models Lykia has marked as free need no credits, but the number of requests made to them each day is capped. The cap depends on your plan: it is lower on the Free plan and goes up after your first top-up. The current figures are on the [pricing page](https://www.getlykia.com/en/pricing). The count is shared by all companies that have the same owner, and the cap that applies is the one of the company sending the request. A request counts once it has reached a provider, whether it was answered or the provider returned an error; requests rejected before that do not count. Once the cap is reached, requests to free models return `429` until the count resets at 00\:00 UTC; requests to paid models are unaffected.

If you rely on free models in production, plan for this limit and add a [model fallback](https://www.getlykia.com/en/docs/guides/model-fallbacks) to a paid model for when you hit it.

## Rate limits (429)

Each API key may send a limited number of requests per minute. The limit is set by Lykia and may change; above it, requests with that key return `429` with a `Retry-After` header that gives the number of seconds until the current minute's window ends. Other keys are not affected. Use several keys if separate workloads should not slow each other down.

Providers rate-limit too. Lykia deals with a provider's `429` first: the request moves on to the next suitable candidate, and usually you notice nothing. If every candidate answered `429`, you get `429` without a `Retry-After` header.

When you get a `429`:

- Wait for the number of seconds in `Retry-After` when it is present.
- Otherwise retry with exponential backoff (1, 2, 4, 8 seconds and so on, plus a little random jitter on each wait).
- Cap the number of attempts.
- Reduce how many requests you run concurrently, or put them through a queue.
- Avoid depending on a single model by using [model fallbacks](https://www.getlykia.com/en/docs/guides/model-fallbacks) and [provider routing](https://www.getlykia.com/en/docs/guides/provider-routing).

The example below retries with exponential backoff on `408`, `429`, `502` and `503`, and stops at once on any other error:

**Python**

```python
import os
import random
import time

import requests

RETRYABLE = {408, 429, 502, 503}


def chat(payload, max_attempts=5):
    for attempt in range(max_attempts):
        response = requests.post(
            "https://api.getlykia.com/v1/chat/completions",
            headers={"Authorization": f"Bearer {os.environ['LYKIA_API_KEY']}"},
            json=payload,
            timeout=120,
        )
        if response.status_code not in RETRYABLE:
            response.raise_for_status()
            return response.json()
        if attempt + 1 < max_attempts:
            # Exponential backoff with jitter: about 1s, 2s, 4s, 8s ...
            time.sleep(2**attempt + random.random())
    response.raise_for_status()


result = chat(
    {
        "model": "openai/gpt-4o-mini",
        "messages": [{"role": "user", "content": "Say hello."}],
    }
)
print(result["choices"][0]["message"]["content"])
```

**TypeScript**

```typescript
const RETRYABLE = new Set([408, 429, 502, 503]);

async function chat(payload: object, maxAttempts = 5) {
  for (let attempt = 0; ; attempt++) {
    const response = await fetch("https://api.getlykia.com/v1/chat/completions", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.LYKIA_API_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(payload),
    });
    if (response.ok) return response.json();
    if (!RETRYABLE.has(response.status) || attempt + 1 >= maxAttempts) {
      throw new Error(`Lykia returned ${response.status}: ${await response.text()}`);
    }
    // Exponential backoff with jitter: about 1s, 2s, 4s, 8s ...
    const delay = 2 ** attempt * 1000 + Math.random() * 1000;
    await new Promise((resolve) => setTimeout(resolve, delay));
  }
}

const result = await chat({
  model: "openai/gpt-4o-mini",
  messages: [{ role: "user", content: "Say hello." }],
});
console.log(result.choices[0].message.content);
```

The [Errors](https://www.getlykia.com/en/docs/guides/errors) guide lists which status codes are worth retrying.

## Concurrent requests

Lykia also limits how many paid requests can be in flight at the same time for a company, and for a key with a spending limit or a project with a budget. The limit is set by Lykia. Above it, new requests return `429` without a `Retry-After` header until some of the running requests finish. Handle it like any other `429`: back off and retry, and cap how many requests you run concurrently.

## Request body size

The JSON body of a request has a size limit, set by Lykia. A larger body returns `413` before anything is sent to a provider. Long conversations and large images sent as data URLs are what usually push a body over it; send images by URL where you can.

## Related

- [Authentication and API keys](https://www.getlykia.com/en/docs/guides/authentication)
- [Projects](https://www.getlykia.com/en/docs/guides/projects)
- [Errors](https://www.getlykia.com/en/docs/guides/errors)
