> ## 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.

# Xử lý rate limit và concurrency

> Xử lý rate limit của CometAPI bằng cách giới hạn concurrency của request, retry phản hồi 429 với jitter, và giám sát mức sử dụng theo model và route.

Xử lý rate limit bằng cách kiểm soát concurrency trước khi request rời khỏi ứng dụng của bạn. Khi CometAPI trả về `429`, hãy retry với exponential backoff và jitter, sau đó giảm lưu lượng burst nếu việc retry lặp lại tiếp tục xảy ra.

## Giới hạn concurrency

Ví dụ Python sau giới hạn các request chat đồng thời bằng một async semaphore:

```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())
```

Kết quả là một mảng chứa đầu ra của model:

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

## Retry khi gặp rate limit

Ví dụ JavaScript sau retry các phản hồi `429` với 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);
```

Phản hồi thành công chứa một chat completion thông thường:

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

## Các lỗi thường gặp

| Error                            | Fix                                                            |
| -------------------------------- | -------------------------------------------------------------- |
| Request song song không giới hạn | Thêm semaphore, hàng đợi hoặc worker pool.                     |
| Retry mọi lỗi                    | Chỉ retry `429` và các lỗi máy chủ tạm thời.                   |
| Không có metric theo từng model  | Ghi log route, model ID, trạng thái và độ trễ cho mỗi request. |
| Bão retry                        | Thêm jitter và giới hạn độ trễ retry tối đa.                   |

## Liên kết liên quan

* [Mã lỗi và chiến lược retry](/vi/guides/error-codes-and-retry-strategy)
* [Mã lỗi & cách xử lý](/vi/errors/error-codes-handling)
* [Trang Models](/vi/overview/models)
* [Danh mục model](https://www.cometapi.com/models/)
* [Bảng giá](https://www.cometapi.com/pricing/)
* [Hướng dẫn nhanh CometAPI](/vi/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": "Làm cách nào để xử lý rate limits và concurrency?",
        "description": "Xử lý rate limits của CometAPI bằng cách giới hạn concurrency, retry phản hồi 429 với jitter, và giám sát mức sử dụng theo model và 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": "Tài liệu CometAPI",
            "item": "https://apidoc.cometapi.com/"
          },
          {
            "@type": "ListItem",
            "position": 2,
            "name": "Hướng dẫn",
            "item": "https://apidoc.cometapi.com/guides/use-cometapi-with-openai-sdk"
          },
          {
            "@type": "ListItem",
            "position": 3,
            "name": "Làm cách nào để xử lý rate limits và concurrency?",
            "item": "https://apidoc.cometapi.com/guides/rate-limits-and-concurrency"
          }
        ]
      }
    ]
    }
    `}
</script>
