> ## Documentation Index
> Fetch the complete documentation index at: https://apidoc.cometapi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Обработка rate limits и concurrency

> Обрабатывайте rate limits CometAPI, ограничивая concurrency, повторяя запросы с ответом 429 с jitter и отслеживая использование по model и route.

Обрабатывайте rate limits, контролируя concurrency до того, как запросы покинут ваше приложение. Когда CometAPI возвращает `429`, повторите запрос с exponential backoff и jitter, а затем снизьте всплеск трафика, если повторные попытки происходят неоднократно.

## Ограничьте concurrency

Следующий пример на Python ограничивает количество одновременных chat-запросов с помощью асинхронного семафора:

```python theme={null}
import asyncio
import os
from openai import AsyncOpenAI

client = AsyncOpenAI(
    api_key=os.environ["COMETAPI_KEY"],
    base_url="https://api.cometapi.com/v1",
)

semaphore = asyncio.Semaphore(5)

async def ask(prompt):
    async with semaphore:
        completion = await client.chat.completions.create(
            model="your-model-id",
            messages=[{"role": "user", "content": prompt}],
        )
        return completion.choices[0].message.content

async def main():
    prompts = ["Say hello.", "Write a title.", "Return one JSON key."]
    results = await asyncio.gather(*(ask(prompt) for prompt in prompts))
    print(results)

asyncio.run(main())
```

Результатом будет массив ответов модели:

```json theme={null}
[
  "Hello.",
  "A concise title",
  "{\"key\":\"value\"}"
]
```

## Повторные попытки при rate limits

Следующий пример на JavaScript повторяет запросы с ответом `429` с jitter:

```javascript theme={null}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.COMETAPI_KEY,
  baseURL: "https://api.cometapi.com/v1",
});

async function sleep(milliseconds) {
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
}

async function createCompletion() {
  for (let attempt = 0; attempt < 5; attempt += 1) {
    try {
      return await client.chat.completions.create({
        model: "your-model-id",
        messages: [{ role: "user", content: "Say hello." }],
      });
    } catch (error) {
      if (error.status !== 429 || attempt === 4) {
        throw error;
      }

      const delay = Math.min(30000, 1000 * 2 ** attempt);
      await sleep(delay + Math.random() * 1000);
    }
  }
}

const completion = await createCompletion();
console.log(completion.choices[0].message.content);
```

Успешный ответ содержит обычный chat completion:

```json theme={null}
{
  "choices": [
    {
      "message": {
        "content": "Hello."
      }
    }
  ]
}
```

## Распространённые ошибки

| Error                               | Fix                                                                            |
| ----------------------------------- | ------------------------------------------------------------------------------ |
| Неограниченные параллельные запросы | Добавьте семафор, очередь или пул воркеров.                                    |
| Повтор всех неудачных запросов      | Повторяйте только `429` и временные сбои сервера.                              |
| Нет метрик по каждой model          | Логируйте route, model ID, status и latency для каждого запроса.               |
| Шторм повторных попыток             | Добавьте jitter и ограничьте максимальную задержку между повторными попытками. |

## Связанные ссылки

* [Коды ошибок и стратегия повторных попыток](/ru/guides/error-codes-and-retry-strategy)
* [Коды ошибок и обработка](/ru/errors/error-codes-handling)
* [Страница моделей](/ru/overview/models)
* [Каталог моделей](https://www.cometapi.com/models/)
* [Цены](https://www.cometapi.com/pricing/)
* [Быстрый старт CometAPI](/ru/overview/quick-start)

<script type="application/ld+json">
  {`
    {
    "@context": "https://schema.org",
    "@graph": [
      {
        "@type": "TechArticle",
        "@id": "https://apidoc.cometapi.com/guides/rate-limits-and-concurrency",
        "headline": "Как обрабатывать rate limits и concurrency?",
        "description": "Обрабатывайте rate limits в CometAPI, ограничивая concurrency, повторяя запросы с ответом 429 с jitter и отслеживая использование по model и route.",
        "url": "https://apidoc.cometapi.com/guides/rate-limits-and-concurrency",
        "author": {
          "@type": "Organization",
          "name": "CometAPI"
        },
        "publisher": {
          "@type": "Organization",
          "name": "CometAPI",
          "url": "https://www.cometapi.com"
        }
      },
      {
        "@type": "BreadcrumbList",
        "itemListElement": [
          {
            "@type": "ListItem",
            "position": 1,
            "name": "Документация CometAPI",
            "item": "https://apidoc.cometapi.com/"
          },
          {
            "@type": "ListItem",
            "position": 2,
            "name": "Руководства",
            "item": "https://apidoc.cometapi.com/guides/use-cometapi-with-openai-sdk"
          },
          {
            "@type": "ListItem",
            "position": 3,
            "name": "Как обрабатывать rate limits и concurrency?",
            "item": "https://apidoc.cometapi.com/guides/rate-limits-and-concurrency"
          }
        ]
      }
    ]
    }
    `}
</script>
