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

# 속도 제한 및 동시성 처리

> 요청 동시성을 제한하고, 지터와 함께 429 응답을 재시도하며, model 및 route별 사용량을 모니터링하여 CometAPI 속도 제한을 처리하세요.

요청이 앱을 떠나기 전에 동시성을 제어하여 속도 제한을 처리하세요. CometAPI가 `429`를 반환하면 지수 백오프와 지터를 사용해 재시도하고, 재시도가 반복해서 발생하면 버스트 트래픽을 줄이세요.

## 동시성 제한

다음 Python 예시는 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())
```

결과는 모델 출력 배열입니다:

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

## 속도 제한 재시도

다음 JavaScript 예시는 지터를 사용해 `429` 응답을 재시도합니다:

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

성공한 응답에는 일반적인 채팅 완성이 포함됩니다:

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

## 일반적인 오류

| Error         | Fix                                               |
| ------------- | ------------------------------------------------- |
| 무제한 병렬 요청     | semaphore, 큐 또는 worker pool을 추가하세요.               |
| 모든 실패 재시도     | `429` 및 일시적인 서버 실패에 대해서만 재시도하세요.                  |
| model별 메트릭 부재 | 각 요청에 대해 route, model ID, status, latency를 기록하세요. |
| 재시도 폭주        | 지터를 추가하고 최대 재시도 지연 시간을 제한하세요.                     |

## 관련 링크

* [오류 코드 및 재시도 전략](/ko/guides/error-codes-and-retry-strategy)
* [오류 코드 및 처리](/ko/errors/error-codes-handling)
* [모델 페이지](/ko/overview/models)
* [모델 디렉터리](https://www.cometapi.com/models/)
* \[요금][https://www.cometapi.com/pricing/](https://www.cometapi.com/pricing/))
* [CometAPI 빠른 시작](/ko/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": "속도 제한과 동시성을 어떻게 처리하나요?",
        "description": "동시성 상한 설정, 지터를 적용한 429 응답 재시도, 그리고 model 및 route별 사용량 모니터링을 통해 CometAPI 속도 제한을 처리합니다.",
        "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": "속도 제한과 동시성을 어떻게 처리하나요?",
            "item": "https://apidoc.cometapi.com/guides/rate-limits-and-concurrency"
          }
        ]
      }
    ]
    }
    `}
</script>
