How to Achieve High-Concurrency LLM API Calls? A Practical Python Guide to Concurrency, Rate Limiting, and Retries

In batch content generation, AI agent, and enterprise automation scenarios, LLM API calls must balance processing efficiency, service stability, and call costs. This article uses Python code examples to introduce asynchronous concurrency, rate limiting, failure retries, and production environment optimization methods.

llm-api-concurrency-rate-limit-retry

Key takeaways

  • Asynchronous concurrent calls: Use Python asyncio and AsyncOpenAI to process multiple LLM API requests in parallel, improving batch task processing efficiency through concurrency control.
  • API rate limiting and retries: Understand limits such as RPM, TPM, and concurrent connections, and handle 429 errors and temporary service exceptions with request frequency control, exponential backoff, and random jitter.

How to Achieve High-Concurrency LLM API Calls? A Practical Python Guide to Concurrency, Rate Limiting, and Retries

When LLM applications move from single-turn conversations to batch content generation, automated data processing, and enterprise AI applications, the problem developers face is often no longer how to successfully send one API request, but how to reliably complete a large number of requests.

For example, an AI content production system may need to generate thousands of pieces of content every day, an intelligent customer service system may need to handle questions from multiple users at the same time, and an AI agent workflow may initiate multiple model calls within a short period.

If all requests are executed serially, task processing efficiency may be low; if a large number of concurrent requests are enabled directly, API rate limiting, request timeouts, or service exceptions may be triggered.

Therefore, the core of high-concurrency LLM API calls is not to increase the number of requests indefinitely, but to find a balance among service limits, response speed, task success rate, and call costs.

This article uses Python code examples to introduce concurrent LLM API calls, rate limiting, failure retries, and production environment optimization methods.

01 What Are Concurrent LLM API Calls?

Concurrent LLM API calls mean that an application processes multiple model API requests within the same period, instead of waiting for the previous request to complete before sending the next one.

Assume a content generation system needs to process 100 tasks, and each task takes an average of 5 seconds to complete.

In an ideal scenario, without considering factors such as network fluctuations, server-side queuing, and rate limiting, the task processing times corresponding to different concurrency levels are as follows:

Invocation method

Concurrency

Theoretical completion time

Serial invocation

1

500 seconds

Low-concurrency invocation

5

100 seconds

Moderate-concurrency invocation

10

50 seconds

High-concurrency invocation

20

25 seconds

High-concurrency invocation

50

10 seconds

The above is a theoretical calculation under ideal conditions, not actual model API performance test results.

In real-world use, as concurrency increases, server-side queuing, network connections, token throughput, and rate limiting rules may all affect task processing efficiency.

Therefore, an increase in concurrency does not necessarily mean that task processing speed will improve proportionally.

02 Why Do LLM APIs Have Rate Limits?

API rate limiting refers to a service platform restricting the number of requests, token consumption, or concurrently executing tasks within a certain period.

Rate limiting mechanisms are usually used to protect service resources, control system load, ensure service stability, and manage usage quotas for different accounts.

Common limit metrics for LLM APIs include:

Rate limit metric

Full English name

Meaning

RPM

Requests Per Minute

Allowed requests per minute

TPM

Tokens Per Minute

Allowed tokens per minute

RPS

Requests Per Second

Allowed requests per second

RPD

Requests Per Day

Allowed requests per day

TPD

Tokens Per Day

Allowed tokens per day

Concurrency

Concurrent Requests

Number of concurrently executing requests

Different model service platforms may use different rate limiting rules.

Some platforms rate limit by account, while others rate limit by model, API Key, project, or service tier; multiple limits may also exist at the same time.

Developers should determine the calling strategy based on the actual service documentation and account configuration.

03 What are the differences among RPM, TPM, and concurrency?

RPM, TPM, and concurrency are three easily confused concepts in large model API performance management.

RPM limits the number of requests per unit time, TPM limits Token usage per unit time, and concurrency limits the number of requests being executed at the same moment.

Assume a model has the following limits:

  • RPM: 600

  • TPM: 120,000

  • Average consumption per request: 2,000 Tokens

Based on the RPM limit, 600 requests can theoretically be sent per minute.

But based on the TPM limit, only the following can theoretically be processed per minute:

120,000 ÷ 2,000 = 60 requests

In this scenario, TPM is the factor that truly limits task processing efficiency.

If the average time per request is 5 seconds, then under stable and uniform request traffic, maintaining 60 requests per minute requires approximately 5 concurrent requests.

Further increasing concurrency does not necessarily improve effective throughput.

Note that some service platforms may calculate rate-limit usage based on estimated Tokens, maximum output length, or other rules, rather than solely on actual Token consumption after the request ends.

The above calculation is only for illustrating the relationship among different limits.

04 Preparing a Python concurrent calling environment

For network I/O-intensive tasks such as large model APIs, Python asyncio is a common asynchronous concurrency implementation.

First install the relevant dependencies:

pip install -U openai python-dotenv

Create the in the project root .env file:

LLM_API_KEY=your_api_key
LLM_BASE_URL=https://your-provider.example/v1
LLM_MODEL=your_model_id

The above content is a configuration example and needs to be replaced with the information provided by the actual model service platform.

If you use the OpenAI-compatible interface provided by AGTCloud, configure the corresponding API Key, Base URL, and Model ID according to the current development documentation.

Also, add the .env file to .gitignore, to avoid API Key leakage.

05 Implementing asynchronous API calls with AsyncOpenAI

The OpenAI Python SDK provides the asynchronous client AsyncOpenAI, which can be used with asyncio to implement asynchronous requests.

Create the async_api.py file:

import os
import asyncio

from dotenv import load_dotenv
from openai import AsyncOpenAI

load_dotenv()

async def main():
    async with AsyncOpenAI(
        api_key=os.environ["LLM_API_KEY"],
        base_url=os.environ["LLM_BASE_URL"],
        timeout=60.0
    ) as client:

        response = await client.chat.completions.create(
            model=os.environ["LLM_MODEL"],
            messages=[
                {
                    "role": "user",
                    "content": "请介绍什么是 MaaS。"
                }
            ]
        )

        print(response.choices[0].message.content)

if __name__ == "__main__":
    asyncio.run(main())

Compared with synchronous calls, asynchronous calls mainly use the following two keywords:

  • async: Defines an asynchronous function.

  • await: Waits for an asynchronous operation to complete and allows the event loop to schedule other tasks.

The asynchronous mechanism allows the program to continue processing other requests while waiting for network responses, thereby improving the utilization efficiency of network I/O resources.

However, a single asynchronous request itself does not mean that model inference will be faster.

06 How to call multiple large model API requests at the same time?

By using asyncio.gather(), developers can schedule multiple asynchronous tasks at the same time.

async def ask_model(client, prompt):
    response = await client.chat.completions.create(
        model=os.environ["LLM_MODEL"],
        messages=[
            {
                "role": "user",
                "content": prompt
            }
        ]
    )

    return response.choices[0].message.content

Create multiple tasks:

async def main():
    prompts = [
        "介绍什么是 RAG。",
        "介绍什么是 AI Agent。",
        "介绍什么是 Embedding。",
        "介绍什么是 MaaS。",
        "介绍什么是 Token。"
    ]

    async with AsyncOpenAI(
        api_key=os.environ["LLM_API_KEY"],
        base_url=os.environ["LLM_BASE_URL"]
    ) as client:

        results = await asyncio.gather(
            *[
                ask_model(client, prompt)
                for prompt in prompts
            ],
            return_exceptions=True
        )

        for prompt, result in zip(prompts, results):
            print("任务:", prompt)

            if isinstance(result, Exception):
                print("调用失败:", str(result))
            else:
                print("结果:", result)

            print()

In this mode, multiple tasks can execute within the same time period.

asyncio.gather() The order of returned results matches the order of the input tasks, not necessarily the order in which tasks actually complete.

For a small number of concurrent tasks, this approach is relatively simple.

But if tens of thousands of tasks are created at once, it may generate too many pending coroutines and memory overhead. Therefore, large-scale batch processing also requires introducing task queues and concurrency control mechanisms.

07 How to use Semaphore to control API concurrency?

Semaphore is a concurrency control mechanism provided by asyncio that can limit the number of tasks simultaneously entering a certain code region.

For example, set the maximum number of concurrent requests to 5:

async def main():
    semaphore = asyncio.Semaphore(5)

    async with AsyncOpenAI(
        api_key=os.environ["LLM_API_KEY"],
        base_url=os.environ["LLM_BASE_URL"],
        timeout=60.0
    ) as client:

        async def limited_request(prompt):
            async with semaphore:
                return await ask_model(client, prompt)

        prompts = [
            f"请生成第 {i} 条 AI 技术知识介绍。"
            for i in range(100)
        ]

        results = await asyncio.gather(
            *[
                limited_request(prompt)
                for prompt in prompts
            ],
            return_exceptions=True
        )

        print("任务数量:", len(results))

Although the program creates 100 tasks, at most 5 tasks execute API calls simultaneously.

Note that Semaphore can only limit concurrency; it cannot directly limit the number of requests per minute.

If the model responds very quickly, even with low concurrency, a large number of requests may still be sent in a short period, thereby triggering RPM or TPM limits.

Therefore, concurrency control and request frequency control need to be used together.

08 How to control API request frequency?

For model services with RPM limits, you can control the request sending interval to avoid generating a large number of requests in a short period.

For example, if the target request frequency is 60 requests per minute, one request can be sent on average per second.

You can install an asynchronous rate-limiting tool:

pip install aiolimiter

Usage example:

from aiolimiter import AsyncLimiter

async def main():
    semaphore = asyncio.Semaphore(5)

    # 平均每秒允许一次请求
    limiter = AsyncLimiter(1, 1)

    async with AsyncOpenAI(
        api_key=os.environ["LLM_API_KEY"],
        base_url=os.environ["LLM_BASE_URL"],
        timeout=60.0,
        max_retries=0
    ) as client:

        async def limited_request(prompt):
            async with semaphore:
                async with limiter:
                    return await ask_model(client, prompt)

        prompts = [
            f"生成第 {i} 条产品介绍。"
            for i in range(100)
        ]

        results = await asyncio.gather(
            *[
                limited_request(prompt)
                for prompt in prompts
            ],
            return_exceptions=True
        )

This code uses two control mechanisms at the same time:

  • Semaphore: Limits the number of requests executing simultaneously.

  • AsyncLimiter: Limits the request sending frequency.

The example disables the SDK's built-in retry to avoid automatic retries generating additional requests that bypass the application-layer rate limiter.

For services with TPM limits, you also need to establish an independent Token budget control mechanism based on input Tokens, estimated output Tokens, and platform metering rules.

If the application is deployed across multiple processes or multiple server instances, a rate limiter within a single process cannot control the total request volume of the entire system; in this case, you can consider using shared storage such as Redis to implement distributed rate limiting.

09 What to do when a large model API returns a 429 error?

HTTP 429 (Too Many Requests) usually indicates that requests have exceeded the calling limits allowed by the service platform.

Common causes include:

  • The number of requests per minute exceeds the RPM limit.

  • Token consumption per minute exceeds the TPM limit.

  • The number of concurrently executing requests exceeds the concurrency limit.

  • A burst of requests is generated in a short period.

  • Account quota is insufficient or other platform usage limits are triggered.

After receiving a 429 error, it is not recommended to immediately make a large number of repeated requests.

If the error is caused by temporary rate limiting, immediate retries may further increase service pressure and cause more request failures.

If the error is caused by insufficient account balance or long-term quota limits, repeated requests usually cannot resolve the issue.

Developers should prioritize checking the error response content, account quota, rate limiting configuration, and relevant response headers returned by the service platform.

If the server provides Retry-After response header, prioritize following its wait time within a reasonable task waiting period.

10 How to implement failure retries using exponential backoff?

Exponential Backoff is an exception-handling strategy that gradually increases the wait time based on the number of retries.

For example:

Retry count

Base wait time

1st retry

1 second

2nd retry

2 seconds

3rd retry

4 seconds

4th retry

8 seconds

5th retry

16 seconds

Compared with fixed-time retries, exponential backoff can reduce the pressure of continuously sending requests to an abnormal service.

In multi-concurrency scenarios, you can also add random jitter to avoid a large number of failed tasks resending requests at the same moment.

Below is a basic retry example:

import asyncio
import random

from openai import (
    APIConnectionError,
    APITimeoutError,
    RateLimitError,
    APIStatusError
)

async def request_with_retry(
    client,
    prompt,
    semaphore,
    limiter,
    max_attempts=5
):
    for attempt in range(max_attempts):

        try:
            async with semaphore:
                async with limiter:
                    return await ask_model(client, prompt)

        except (
            RateLimitError,
            APIConnectionError,
            APITimeoutError
        ) as exc:
            error = exc

        except APIStatusError as exc:
            if exc.status_code not in (
                408, 500, 502, 503, 504
            ):
                raise

            error = exc

        if attempt == max_attempts - 1:
            raise error

        delay = random.uniform(
            0,
            min(30, 2 ** attempt)
        )

        response = getattr(error, "response", None)

        if response is not None:
            retry_after = response.headers.get(
                "Retry-After"
            )

            if retry_after:
                try:
                    delay = max(
                        delay,
                        float(retry_after)
                    )
                except ValueError:
                    pass

        # 超过任务允许的等待时间时交给上层处理
        if delay > 120:
            raise error

        print(
            f"请求失败,{delay:.2f} 秒后重试"
        )

        await asyncio.sleep(delay)

When using this function, it is recommended to set the SDK's max_retries to 0, with the retry strategy managed uniformly by the application layer.

This ensures that each retry passes through concurrency control and request rate limiting again.

At the same time, the concurrent quota of the Semaphore is not occupied during task waiting.

The above code is a basic implementation and only handles Retry-After, while production projects should also consider HTTP date format, unrecoverable quota errors, overall task deadlines, and more comprehensive logging.

11 Which API errors are suitable for automatic retry?

Not all API errors are suitable to be resolved through retries.

Error type

Common cause

Suitable for automatic retry

400

Request parameter error

Usually not suitable

401

Authentication failure

Not suitable

403

Insufficient permissions

Usually not suitable

404

Model or endpoint does not exist

Usually not suitable

408

Request timeout

Depends on business judgment

429

Temporary rate limiting

Limited retry is possible

429

Insufficient quota

Usually not suitable

500

Server internal error

Limited retry is possible

502

Gateway error

Limited retry is possible

503

Service temporarily unavailable

Limited retry is possible

504

Gateway timeout

Limited retry is possible

Network connection exception

Network fluctuation

Depends on business judgment

Even if an error is suitable for retry, a maximum retry count and overall task timeout must be set.

For requests that have already been successfully submitted but for which the client did not receive a response, resending may cause duplicate generation and additional billing.

For AI Agent applications involving tool calls, order operations, or external system writes, idempotency controls should also be established to avoid retries causing repeated execution of business operations.

12 How to handle large-scale API calls through a task queue?

When the number of tasks reaches thousands or even tens of thousands, it is not recommended to submit all tasks at once to asyncio.gather().

A more reasonable approach is to use a task queue to separate pending tasks from the worker processes that actually execute requests.

A typical architecture includes:

  1. The business system generates pending tasks.

  2. Tasks enter the message queue.

  3. Workers retrieve tasks from the queue.

  4. Requests pass through concurrency and rate limiting controls.

  5. The large model API is called.

  6. Successful results are written to the database.

  7. Temporarily failed tasks enter a delayed retry process.

  8. Tasks that exceed the retry limit enter the failed task queue.

In a single-process application, you can use asyncio.Queue to implement a basic task queue.

In distributed production environments, you can evaluate Redis, RabbitMQ, Kafka, or other message queue solutions based on business scale.

The value of a task queue lies not only in improving processing efficiency, but also in helping enterprises implement task state tracking, failure recovery, priority management, and resource scheduling.

13 How to dynamically adjust the concurrency of large model API calls?

A fixed concurrency count is suitable for basic applications, but in production environments, model response speed and service load may vary across different time periods.

Enterprises can dynamically adjust concurrency strategies based on actual runtime metrics.

For example:

Monitoring situation

Adjustment strategy

High request success rate and stable latency

Gradually increase the concurrency count

429 errors increase significantly

Reduce request frequency and concurrency count

P95 latency continues to rise

Pause increasing concurrency and investigate bottlenecks

TPM approaches the limit

Reduce the Token budget or request frequency

Server errors continue to increase

Reduce traffic or trigger circuit breaking

Service returns to stable operation

Gradually restore request traffic

A common control approach is to slowly increase the concurrency count when the system is stable, and quickly reduce the concurrency count when obvious anomalies occur.

However, dynamic concurrency strategies need to be designed in combination with statistical periods, error types, and business priorities, to avoid frequent changes in concurrency count caused by short-term fluctuations.

14 How to evaluate the performance of high-concurrency large model API calls?

Enterprises should not only focus on how many API requests are sent per minute, but should focus more on how many valid business tasks are successfully completed.

It is recommended to establish the following monitoring metrics:

Metric

Meaning

Request throughput

Number of requests sent per unit of time

Successful throughput

Number of requests successfully completed per unit of time

Request success rate

Proportion of successful requests among all requests

Task completion rate

Proportion of business tasks ultimately completed successfully

P50 latency

50% of requests complete within this time

P95 latency

95% of requests complete within this time

429 error rate

Proportion of rate-limiting errors among all requests

Retry rate

Proportion of tasks that trigger retries

Token throughput

Number of Tokens processed per unit time

Cost per effective task

Total call cost divided by the number of successfully completed business tasks

Among them, the cost per effective task is an important metric for enterprises to evaluate the usage efficiency of large model APIs.

If a concurrency strategy increases the number of requests but causes many failures, repeated calls, and extra costs, actual business efficiency may instead decline.

15 Does high-concurrency calling increase large model API costs?

Concurrent calls themselves usually do not directly change the Token unit price of the same model, but may affect actual usage costs through other factors.

Mainly including:

  • Failed retries generate additional model calls.

  • Tasks are resubmitted after request timeouts.

  • A large number of tasks simultaneously generate overly long content.

  • Concurrency exceptions cause duplicate processing of the same data.

  • Infrastructure costs of application servers and message queues.

For example, assume a system needs to complete 10,000 content generation tasks, with an average cost of 0.02 CNY per call.

Call scenario

Actual number of calls

Total cost

No extra retries

10,000

200 CNY

Extra calls increase by 5%

10,500

210 CNY

Extra calls increase by 10%

11,000

220 CNY

Extra calls increase by 20%

12,000

240 CNY

The above is a hypothetical cost example; whether failed requests incur charges depends on the billing rules of the model service platform.

Therefore, cost optimization for high-concurrency systems requires not only selecting suitable models, but also reducing invalid requests, duplicate tasks, and unnecessary retries.

16 How should enterprises choose a large model API platform suitable for high-concurrency scenarios?

For batch content generation, AI automation, intelligent customer service, and enterprise-grade AI Agent applications, model platform selection should not focus only on Token unit price.

The following capabilities should also be evaluated with emphasis:

Model coverage and interface compatibility

Whether the platform provides the models required by the business, and whether it can reduce interface migration costs among different models.

Concurrency and throughput

What RPM, TPM, and concurrency quotas the platform can provide, and whether they can meet actual business peak demand.

Service stability

Pay attention to request success rates, response latency, service exceptions, and recovery capabilities across different time periods.

Usage and cost management

Whether the platform can provide clear call records, Token usage, and billing information to help enterprises manage actual usage costs.

Technical support and service capability

When enterprises encounter rate limiting, model exceptions, or large-scale access issues, whether the platform can provide corresponding technical support.

AGTCloud provides multi-model API services for developers and enterprises, covering model capabilities such as text, image, video, speech, and 3D.

For enterprises with batch calling and multi-model access needs, they can evaluate suitable model access plans by combining AGTCloud's current model catalog, interface documentation, account quotas, and actual business testing.

Visit AGTCloud:https://agtcloud.cn/

Summary

High-concurrency large model API calls are an important technical foundation for enterprises to scale AI capabilities from single requests to large-scale business applications.

By using Python asyncio, asynchronous clients, Semaphore, request frequency control, and exponential backoff retries, developers can build a basic concurrent calling system.

For production environments, it is also necessary to further introduce task queues, distributed rate limiting, dynamic concurrency adjustment, exception monitoring, and cost management mechanisms.

A truly efficient large model API calling system is not one that can send the most requests in a short time, but one that can continuously and stably complete the most effective business tasks at a reasonable cost.


Docs ↗

Frequently asked questions

There is no fixed concurrency number suitable for all models. Developers can start testing with lower concurrency and adjust gradually based on RPM, TPM, request latency, success rate, and business requirements.

C

Chen Yizhou

API Engineering

AGTCloud technical column author for API development, focusing on large-model API access, interface compatibility, SDK integration, and application development. Content covers Python API calls, OpenAI-compatible interfaces, streaming output, error handling, concurrency optimization, and development practices, helping developers reduce model access and migration costs.