Concurrency choices in Python for many model requests

Sooner or later every developer working with a model API needs to process a batch: a thousand support tickets to classify, a folder of documents to summarise, a list of prompts to evaluate. Sending them one by one is slow, so the next step is concurrency. In Python that usually means choosing between a thread pool and asyncio, and the question even comes up in technical interviews at AI companies, where a basic thread pool answer often prompts follow-up questions about rate limits and backpressure.
This comparison looks at both approaches specifically for LLM workloads. You will see working code for each, how they handle rate limits and retries, where each one shines, and the details that matter more than the choice itself. Examples use the OpenAI Python SDK against the keyless endpoint on this site, whose per-IP limits make the rate-limiting part very concrete.
Frequently asked questions
What is a thread pool?
A thread pool is a fixed set of worker threads that take tasks from a queue. In Python, concurrent.futures.ThreadPoolExecutor provides one. Each worker runs ordinary blocking code, such as a synchronous HTTP request.
What is asyncio?
Asyncio is Python's built-in framework for cooperative concurrency. Tasks run on a single thread and pause at await points while waiting for I/O, letting other tasks run. It needs async-aware libraries, such as the async client in the OpenAI SDK.
Does the GIL make threads useless for API calls?
No. The global interpreter lock limits CPU-bound parallelism, but threads release it while waiting on network I/O. For model API calls, which spend almost all their time waiting, threads work well.
Which is faster for LLM batches?
Usually neither, in practice. The bottleneck is the provider's rate limit and response time, not Python's concurrency overhead. Both reach the same throughput if they respect the same limits.
How does asyncio differ from threads in handling many requests?
Asyncio can keep thousands of pending requests cheaply, while each thread has memory and scheduling overhead. For tens of concurrent requests the difference is negligible; for thousands, asyncio scales more gracefully.
Which is better for rate limiting?
Asyncio makes precise rate limiting slightly easier, because all tasks share one event loop and a simple semaphore plus a timed gate is enough. With threads you need thread-safe primitives, which work fine but require more care.
Can I mix both?
Yes. You can run blocking code from asyncio with asyncio.to_thread, or run an event loop inside a thread. Mixing adds complexity, so do it only when a library forces you to.
What concurrency should I use with the free endpoint?
Two. The endpoint allows two parallel requests per IP and one new request per second with bursts of three. Higher concurrency only produces 429 responses.
What the workload really looks like
An LLM API call is almost pure waiting. Your program sends a few kilobytes, the provider spends seconds generating, and a response comes back. CPU usage on your side is tiny. That makes these calls ideal for concurrency: while one request waits, others can be in flight.
The ceiling on how many can be in flight is set by the provider, not by Python. Providers cap requests per second, concurrent requests and tokens per minute, and respond to excess with 429 errors. Any concurrency design for LLM work is therefore mostly a rate-limiting design.
I/O bound, not CPU bound
Because the work is waiting on the network, both threads and asyncio can overlap requests effectively. Multiprocessing adds overhead without benefit here.
The provider sets the pace
Throughput equals the number of concurrent requests divided by average response time, capped by the provider's limits. Python's choice of concurrency model barely affects it.
The thread pool approach
A thread pool is the most straightforward option if your code is already synchronous. You write a normal function that makes one request, then submit it for each item to an executor with a fixed number of workers. The number of workers acts as your concurrency limit.
On its own, a thread pool limits concurrency but not request rate. With the free endpoint's limit of one new request per second, you also need a shared gate that spaces out request starts. The example adds a simple thread-safe limiter.
Strengths
Works with any synchronous library, is easy to read and debug, and fits naturally into scripts and existing codebases.
Weaknesses
Each thread costs memory, cancellation is awkward, and coordinating shared limits needs locks. Very large concurrency levels become unwieldy.
import threading, time
from concurrent.futures import ThreadPoolExecutor
from openai import OpenAI
client = OpenAI(base_url="https://api.apiclaudekeyfree.com/v1", api_key="none", max_retries=0)
class Gate:
def __init__(self, interval):
self.interval, self.lock, self.next = interval, threading.Lock(), 0.0
def wait(self):
with self.lock:
now = time.monotonic()
start = max(now, self.next)
self.next = start + self.interval
time.sleep(max(0.0, start - now))
gate = Gate(1.05) # about one request per second
def classify(text):
for attempt in range(5):
gate.wait()
try:
r = client.chat.completions.create(model="free-ai", max_tokens=5, temperature=0,
messages=[{"role": "user", "content": "Reply positive or negative only: " + text}])
return r.choices[0].message.content.strip()
except Exception:
time.sleep(2 + attempt * 2)
return "error"
texts = ["Great service", "Never again", "Fast delivery", "Broken on arrival"]
with ThreadPoolExecutor(max_workers=2) as pool:
print(list(pool.map(classify, texts)))
The asyncio approach
With asyncio, each request is a coroutine. You create a task for every item and let the event loop interleave them. A semaphore limits how many run at once, and a small async gate spaces out starts. The OpenAI SDK ships an async client, so the request code looks almost identical to the synchronous version.
The example below does the same classification as the thread version. It uses asyncio.gather to run all tasks and collect results in order.
Strengths
Scales to thousands of pending tasks cheaply, makes cancellation and timeouts clean, and keeps shared state simple because everything runs on one thread.
Weaknesses
Requires async libraries throughout. One accidental blocking call stalls every task, and the async style is harder for newcomers to read.
import asyncio, time
from openai import AsyncOpenAI
client = AsyncOpenAI(base_url="https://api.apiclaudekeyfree.com/v1", api_key="none", max_retries=0)
sem = asyncio.Semaphore(2) # two in parallel
lock = asyncio.Lock()
next_start = 0.0
async def gate(interval=1.05):
global next_start
async with lock:
now = time.monotonic()
start = max(now, next_start)
next_start = start + interval
await asyncio.sleep(max(0.0, start - now))
async def classify(text):
async with sem:
for attempt in range(5):
await gate()
try:
r = await client.chat.completions.create(model="free-ai", max_tokens=5, temperature=0,
messages=[{"role": "user", "content": "Reply positive or negative only: " + text}])
return r.choices[0].message.content.strip()
except Exception:
await asyncio.sleep(2 + attempt * 2)
return "error"
async def main():
texts = ["Great service", "Never again", "Fast delivery", "Broken on arrival"]
print(await asyncio.gather(*(classify(t) for t in texts)))
asyncio.run(main())Head-to-head comparison
For typical LLM batch jobs of hundreds to a few thousand items, both approaches reach the same throughput when configured with the same limits. The choice comes down to the surrounding code and the team's familiarity. The list below summarises the practical differences.
A useful rule of thumb: pick the model your codebase already uses. Converting a synchronous project to asyncio just for a batch job rarely pays off, and dropping threads into an async web server is equally awkward.
When threads win
Quick scripts, notebooks, codebases built on synchronous libraries, and teams less familiar with async code.
When asyncio wins
Services that already use an async framework, pipelines with many thousands of tasks, and workloads that need fine-grained cancellation.
- Throughput: equal in practice, limited by the provider.
- Code fit: threads for synchronous scripts, asyncio for async frameworks such as FastAPI.
- Scale of pending work: asyncio handles very large numbers of queued tasks more cheaply.
- Rate limiting: both need a shared gate; asyncio's is slightly simpler.
- Cancellation and timeouts: cleaner in asyncio.
- Debugging: threads are often easier to step through for beginners.

Retries and backoff done right
Whichever approach you choose, retries decide whether a batch finishes cleanly. Retry on 429, 503 and network errors, never on 400-type errors caused by bad input. When a 429 response includes a Retry-After header, wait at least that long. On the free endpoint, 503 means busy and a retry after two to five seconds usually succeeds.
Add jitter, a small random component to the wait, so that many workers do not retry at exactly the same moment. Cap the number of attempts and record failures rather than retrying forever.
Turn off hidden retries
The OpenAI SDK retries some errors by default. Setting max_retries=0, as in the examples, keeps retry logic in one visible place where it can respect your gate.
Separate the failures
Write failed items to a file with the error reason. Re-running only the failures is faster and cheaper than re-running the whole batch.
Budgets and token limits
Rate limits are not the only constraint. Providers also cap tokens per minute or per day, and your own budget may matter more than either. The free endpoint allows 10,000 requests or 10,000,000 tokens per IP per day, reset at 00:00 UTC. A batch of long documents can reach the token limit well before the request limit.
Estimate total tokens before starting a large batch, and stop gracefully when a budget is reached. The patterns in per-user token budgets apply to batch jobs too: treat the job as a user with its own limit.
Keep outputs short
For classification and extraction, a small max_tokens keeps each call fast and cheap, and it increases how many items fit in a daily allowance.

Interview-style follow-ups
Questions about concurrent API calls often continue past the first working answer. Interviewers tend to ask how the solution behaves when the API starts returning 429s, how you would avoid overwhelming the service, how you would preserve output order, how you would handle partial failures, and how you would stop cleanly on a keyboard interrupt.
Good answers cover the ideas in this article rather than one specific library: bounded concurrency, a shared rate gate, backoff with jitter, idempotent retries and clear separation of successes and failures. Mentioning that throughput is limited by the provider, not by Python, shows you understand the real bottleneck.
Bounded queues
For very large or streaming inputs, use a bounded queue between a producer and the workers, so memory use stays flat no matter how many items arrive.
Order and identity
Attach an ID to every item and return it with the result. It makes reordering, deduplication and retrying individual failures straightforward.
Common mistakes in concurrent LLM code
Most problems with concurrent batch code are not about threads or coroutines at all. They come from small oversights that only show up under load: a client created inside every task, a retry loop that ignores the rate gate, or results collected in a way that loses track of which input produced which output.
Reviewing a batch script against a short list of known pitfalls before running it on a large dataset saves both time and quota. Running it first on ten items, then on a hundred, catches most of these before they matter.
Write results incrementally
Append each result to a file or database as soon as it arrives. If the job stops, you can resume from where it left off instead of starting again.
Start with a dry run
Run the batch on a handful of items with logging turned up. Watching the timing of each request shows quickly whether the gate and the concurrency limit behave as intended.
- Creating a new API client for every request instead of sharing one, which wastes connections.
- Retrying immediately without waiting, which turns a brief 429 into a storm of them.
- Calling a blocking function inside async code, which freezes every other task.
- Ignoring the finish reason, so truncated answers are stored as if complete.
- Writing results only at the end, so a crash loses all the work done so far.

Choosing a backend for batch work
The backend matters more than the concurrency model. Commercial providers offer far higher rate limits and, often, dedicated batch interfaces that process large jobs asynchronously at a discount; check your provider's current documentation for options and prices. For large production batches, those features usually make a paid provider the better choice.
The keyless endpoint here suits prototyping, small batches and testing your concurrency code safely. It serves free-ai, an independent open-weight model of about 35B parameters; it is not Claude, and this site is not affiliated with Anthropic. If response speed is the issue rather than limits, measuring slow model output helps you find out why.
Test against low limits
Developing against a strict limit, such as two concurrent requests, quickly exposes missing backoff or gating that a generous paid tier would hide until a bad day.
Send a test request to the keyless, OpenAI-compatible endpoint on the home page and see how it fits your project.