Sub topic 13
Run requests in parallel without hitting limits
This chapter assumes you can write basic Python, have called an LLM API, and know what asyncio is at a high level. If you have a pile of independent requests, such as classifying 5,000 support tickets, running them one at a time wastes wall-clock time. Running them all at once triggers rate limits. The goal is bounded parallelism with safe retries.
Why parallelism helps and where it stops
A single request spends most of its time waiting on the network and the model. While one request waits, your program can start others. Total time then approaches the time of the slowest group of requests rather than the sum of all of them.
Parallelism does not reduce cost per request. It also does not reduce the latency of any single request. It raises throughput, which is the number of requests finished per unit of time.
Providers enforce limits to protect their capacity. Common limits are:
- Requests per minute (RPM).
- Tokens per minute (TPM), counting input and output tokens.
- Concurrent requests in flight.
When you exceed a limit, the API usually returns HTTP 429 (too many requests), sometimes with a Retry-After header. Server errors such as 500 or 503 can also appear under load.
Cap concurrency with a semaphore
A semaphore is a counter that lets only N tasks hold it at once. Wrapping each call in one gives you a hard cap on requests in flight.
Retry with exponential backoff and jitter
Exponential backoff waits longer after each failure: 1 second, 2 seconds, 4 seconds, and so on. Jitter adds a random amount to each wait. Without jitter, many clients that failed together retry together and collide again.
import asyncio
import random
async def call_with_retry(call_fn, item, attempts=5):
for attempt in range(attempts):
try:
return await call_fn(item)
except Exception:
if attempt == attempts - 1:
raise
await asyncio.sleep(min(30, 2 ** attempt) + random.random())
async def run_all(call_fn, items, limit=8):
sem = asyncio.Semaphore(limit)
async def one(item):
async with sem:
return await call_with_retry(call_fn, item)
return await asyncio.gather(*(one(i) for i in items))The semaphore limits parallelism to limit. The retry helper waits min(30, 2 ** attempt) seconds plus up to one second of jitter, so waits are capped at about 31 seconds. After the final attempt fails, the error is raised.
Common errors
- Retrying every exception. The code above retries on any exception for brevity. In production, retry only 429, 500, 502, 503, and timeouts. A 400 (bad request) or 401 (bad key) will fail every time, so retrying only adds delay.
- Ignoring
Retry-After. If the provider tells you how long to wait, use that value instead of your own guess. - Limiting requests but not tokens. Eight concurrent requests with very long prompts can exceed TPM even when RPM is fine. Lower
limitor shorten prompts. - Holding the semaphore during sleep. In the code above the sleep happens inside the semaphore, so a retrying task keeps its slot. This is safe but lowers throughput during failures. Moving the semaphore inside the retry loop frees the slot while waiting.
- Retrying non-idempotent work. If a call triggers side effects, such as sending an email from a tool call, a retry can repeat them. Retries are safe for plain text generation.
- Failing the whole batch.
asyncio.gatherraises the first exception and the other results are lost to the caller. Passreturn_exceptions=Trueif you want partial results.
Choosing a concurrency limit
Start low, such as 4 to 8, and raise it while watching the 429 rate and total throughput. Stop raising it when throughput stops improving or 429s become frequent. Your limit should also leave room for other services that share the same API key.
Exercise
Your job runs 200 requests with a semaphore limit of 50 and gets many 429 errors, even though retries eventually succeed. Name two changes that would reduce the 429s, and say why a fixed sleep(2) between retries is worse than exponential backoff with jitter.
Show answer
Lower the semaphore limit (for example to 10), and add a token-aware or request-rate limiter so you stay under RPM and TPM. Also honor the Retry-After header. A fixed sleep makes all failed clients retry at the same moment, so they collide again, and it does not slow down when the provider is still overloaded. Exponential backoff spreads retries out and waits longer as failures continue, and jitter keeps clients from synchronizing.