◢ build log

Manage Concurrency and Rate Limiting for LLM API Calls

Learn practical strategies for managing concurrency and rate limiting when integrating LLM APIs into production applications to ensure reliability.

Integrating Large Language Models (LLMs) into production applications requires careful management of API calls. LLM providers enforce limits on how many requests you can make in a given timeframe. Exceeding these limits leads to errors, throttled requests, and potentially suspended API access. You need robust strategies for concurrency and rate limiting to build reliable, cost-effective systems.

Why Concurrency and Rate Limiting Matter

Every LLM API has rate limits. These limits are often expressed as requests per minute (RPM) and tokens per minute (TPM). An API might allow 3,000 RPM but only 1,000,000 TPM. If your requests are short, you might hit RPM first. If they are long, TPM will be the bottleneck.

Ignoring these limits causes 429 Too Many Requests errors. Your application will fail. Retrying immediately often makes the problem worse, creating a retry storm that further overwhelms the API.

Concurrency is also about efficiency. You want to process as many requests as possible without hitting limits. Running tasks in parallel can speed up processing for batches or user-facing features.

Managing Concurrency

Concurrency allows your application to handle multiple LLM requests simultaneously. This is critical for performance, especially when waiting for API responses, which can be slow. You have a few options depending on your application's architecture.

Asynchronous Programming

For I/O-bound tasks like API calls, asynchronous programming is ideal. Python's asyncio library lets you run many tasks concurrently without using multiple threads or processes, which reduces overhead.

You can use a semaphore to limit the number of concurrent API calls. This prevents you from overwhelming the LLM provider or your own system resources.

import asyncio
import httpx # A modern HTTP client for Python

async def call_llm_api(prompt: str, semaphore: asyncio.Semaphore) -> str:
    async with semaphore:
        # Simulate an API call
        print(f"Sending request for: {prompt[:20]}...")
        await asyncio.sleep(1) # Replace with actual httpx.post call
        response = f"Response for {prompt[:20]}..."
        print(f"Received response for: {prompt[:20]}...")
        return response

async def main():
    prompts = [f"Generate a short story about a cat {i}" for i in range(10)]
    # Limit to 3 concurrent API calls
    concurrency_limit = 3
    semaphore = asyncio.Semaphore(concurrency_limit)

    tasks = [call_llm_api(p, semaphore) for p in prompts]
    results = await asyncio.gather(*tasks)
    for r in results:
        print(r)

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

This example uses asyncio.Semaphore to ensure only concurrency_limit tasks are actively making API calls at any given time. Adjust this limit based on your application's needs and the LLM provider's specific API rate limits.

Thread Pools or Process Pools

If your application uses blocking I/O or you are not using asyncio, thread pools or process pools are alternatives. Thread pools are good for I/O-bound tasks, while process pools are better for CPU-bound tasks or to bypass Python's Global Interpreter Lock (GIL).

from concurrent.futures import ThreadPoolExecutor
import time

def blocking_llm_call(prompt: str) -> str:
    print(f"Sending blocking request for: {prompt[:20]}...")
    time.sleep(1) # Simulate a blocking API call
    response = f"Blocking response for {prompt[:20]}..."
    print(f"Received blocking response for: {prompt[:20]}...")
    return response

def run_blocking_calls():
    prompts = [f"Analyze text {i}" for i in range(10)]
    # Limit to 5 concurrent threads
    max_workers = 5

    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        results = list(executor.map(blocking_llm_call, prompts))
        for r in results:
            print(r)

if __name__ == "__main__":
    run_blocking_calls()

This method is simpler for existing blocking codebases but introduces more overhead than asyncio.

Implementing Rate Limiting

Rate limiting ensures you do not exceed the provider's limits. This is distinct from concurrency. Concurrency limits how many requests you try to make at once. Rate limiting limits how many you actually send over a period.

Token Bucket Algorithm

The token bucket algorithm is a common way to implement rate limiting. Imagine a bucket that holds

  • LLM API concurrency
  • LLM rate limiting
  • Python API calls
  • asyncio LLM
  • production LLM
  • API error handling
  • 429 errors
  • LLM best practices
  • async API
  • Python concurrency
05 — execute

Ready to build
the future?

Join the developers learning to build with AI. New tutorials, tools and breakdowns every week — straight to your feed.

$ aidevguy --start --now_