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 an HTTP status code is. It also assumes you have seen async/await before. If you haven't, read the code slowly. The pattern is short.
Why parallelism helps, and where it stops
A single LLM request spends most of its time waiting. The client sends a prompt, then waits through queueing, prefill, and decoding. While it waits, your program does nothing. If you have 200 independent requests and run them one after another, total time is roughly 200 times the latency of one call.
Running requests concurrently overlaps that waiting. Total time drops toward the latency of the slowest group of calls. Concurrency does not make any single request faster. It raises throughput, which is the number of requests finished per unit of time.
Parallelism also has a ceiling. Providers enforce rate limits, and your own machine has limited sockets and memory. Past a certain point, more parallel requests only produce errors and retries, which can leave you slower than a moderate setting.
What rate limits measure
Providers usually limit you on more than one dimension at once:
| Limit | What it counts | Typical symptom when exceeded |
|---|---|---|
| Requests per minute (RPM) | Number of calls, regardless of size | HTTP 429 on many small requests |
| Tokens per minute (TPM) | Input plus output tokens, often estimated from `max_tokens` | HTTP 429 on a few large requests |
| Concurrent requests | Calls in flight at the same moment | HTTP 429 or 503 when too many are open |
| Daily or monthly quota | Total usage over a longer window | Errors that persist until the window resets |
Two details matter in practice.
- You can hit the token limit while far below the request limit. Ten requests with 50,000-token prompts can exhaust TPM even though RPM is barely touched.
- Some providers count the reserved output (
max_tokens) against your token limit when the request starts, not the tokens actually generated. An oversizedmax_tokenscan therefore cause rejections even when real outputs are short. This links back to the chapter on limiting output length.
Check your provider's documentation for the exact accounting. The numbers differ by provider, model, and account tier.
Bounded parallelism with a semaphore
The simplest safe control is a cap on how many requests are in flight at once. In asyncio, a Semaphore does this. It allows a fixed number of tasks to enter a block. Other tasks wait until one leaves.
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))Read it in two layers.
run_allcreates one task per item, but the semaphore lets onlylimitof them run the API call at a time.asyncio.gatherreturns results in the same order as the input items.call_with_retrywraps a single call. If it fails, it waits and tries again, up toattemptstimes. On the last failed attempt it re-raises the error.
The semaphore sits outside the retry loop. This means a task holds its slot while it sleeps between retries. That is a deliberate choice here: a request that is backing off still counts toward your concurrency, which prevents a burst of retries from adding to the load. The cost is that a few failing items can occupy slots and slow the rest.
Why backoff needs jitter
The wait is min(30, 2 ** attempt) + random.random(). It has three parts.
- Exponential growth. Waits go 1, 2, 4, 8, 16 seconds. Each failure signals more strongly that the service is overloaded, so you back off further.
- A cap.
min(30, ...)stops waits from growing without bound. - Jitter.
random.random()adds up to one extra second at random. Without it, 100 tasks that failed together would all retry at the same instant and fail together again. Jitter spreads them out.
If the provider returns a Retry-After header on a 429 response, prefer that value over your own calculation. It is the provider telling you exactly how long to wait.
Retry only what can succeed
The example catches every Exception to stay short. In production code, be more selective. Retrying an error that can never succeed wastes time and, for paid requests, sometimes money.
| Error type | Retry? | Reason |
|---|---|---|
| 429 rate limited | Yes, with backoff | Temporary. Honor `Retry-After` if given |
| 500, 502, 503, 504 | Yes, with backoff | Often transient server trouble |
| Network timeout or connection reset | Yes, with care | The request may or may not have been processed |
| 400 invalid request | No | The same input will fail again |
| 401 or 403 | No | Fix credentials or permissions |
| Context length exceeded | No | Shorten the prompt first |
The timeout case needs thought. If a request timed out after the provider began generating, the retry may bill you twice. Set a reasonable client timeout, and keep total retries low for expensive calls.
Choosing the concurrency limit
There is no universal right value for limit. Choose it from your numbers.
- Take your measured average latency per request, from the baseline chapter. Say it is 4 seconds.
- Take your RPM limit. Say it is 600, which is 10 requests per second.
- By Little's law, requests in flight equals arrival rate times latency. At 10 requests per second and 4 seconds each, about 40 requests are in flight.
- Set
limitsomewhat below that, such as 30, to leave headroom.
Then check the token limit the same way. If each request uses about 3,000 tokens and your TPM is 200,000, you can sustain only about 66 requests per minute, which is far below the RPM figure. In that case TPM is the binding constraint, and the concurrency limit should be much lower.
Start low, watch the rate of 429 responses, and raise the limit gradually. A healthy run has very few 429s. If more than a small share of calls need retries, you are above your sustainable rate.
Concurrency and the other levers
Parallelism interacts with earlier techniques in these ways.
- Streaming. Streamed responses hold a connection open until generation ends, so they count toward concurrent-request limits for longer. Concurrency math should use total time, not time to first token.
- Response caching. Check the cache before acquiring a semaphore slot, so cache hits do not consume capacity.
- Batch processing. If the work is not urgent, a provider batch interface can replace client-side parallelism entirely. Batch jobs usually have separate, larger limits and lower prices. Use client-side concurrency for work that must finish within seconds or minutes.
- Cost. Parallelism does not change the price per request. It does make mistakes expensive faster. A bug that loops over 10,000 items at concurrency 30 spends money quickly, so pair high concurrency with the budget alarms covered in a later chapter.
Failure modes to watch
- Partial failure with
gather. By default, if one task raises,gatherraises that exception to the caller, while the other tasks keep running in the background. For batch jobs, passreturn_exceptions=Trueso you get every result or error back, and then handle failures item by item. - Lost work on a crash. If the process dies after 900 of 1,000 calls, you pay for all of them again unless you save results as you go. Write each result to disk or a database as it completes.
- Event loop blocking. If
call_fnuses a synchronous client insideasync def, calls run one at a time and the semaphore does nothing. Use the provider's async client, or run blocking calls in a thread pool. - Shared limits. Rate limits usually apply per account or per key, not per process. Ten workers each set to 30 concurrent requests make 300 in total.
- Uneven item sizes. One item with a huge prompt can use as many tokens as dozens of small ones. If sizes vary a lot, limit by tokens, not only by request count.
A variant that collects errors
This version keeps going when individual items fail, and it returns both results and errors.
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_safe(call_fn, items, limit=8):
sem = asyncio.Semaphore(limit)
async def one(item):
async with sem:
return await call_with_retry(call_fn, item)
outcomes = await asyncio.gather(
*(one(i) for i in items), return_exceptions=True
)
results, failures = [], []
for item, outcome in zip(items, outcomes):
if isinstance(outcome, Exception):
failures.append((item, outcome))
else:
results.append((item, outcome))
return results, failures
async def fake_call(item):
await asyncio.sleep(0.1)
if item == 3:
raise ValueError("bad item")
return item * 2
async def main():
results, failures = await run_all_safe(fake_call, range(6), limit=2)
print(len(results), "ok,", len(failures), "failed")
asyncio.run(main())Item 3 raises ValueError on every attempt, so it ends up in failures after about 15 seconds of backoff. That delay is a good reason to retry only errors that can succeed, as described above.
Summary of rules
- Overlap waiting with bounded concurrency, and size the bound from latency and your provider limits.
- Check both request and token limits. The tighter one decides your rate.
- Back off exponentially with jitter, and honor
Retry-After. - Retry only errors that can succeed.
- Save results as they arrive, and collect errors instead of losing them.
Exercise
Your provider allows 300 requests per minute and 120,000 tokens per minute. Each request uses about 2,000 tokens in total and takes 5 seconds on average. What is the sustainable request rate, and roughly how many requests should be in flight? Which limit is binding?
Show answer
By requests, you could send 300 per minute. By tokens, 120,000 / 2,000 = 60 requests per minute, which is 1 per second. The token limit is binding, so the sustainable rate is about 60 requests per minute. By Little's law, in flight = 1 request per second x 5 seconds = about 5 requests. A concurrency limit of 4 to 5 is appropriate, not the 25 that the request limit alone would suggest.
Exercise
In run_all, why might a retry that sleeps while holding a semaphore slot be preferable to releasing the slot first? What is the downside?
Show answer
Holding the slot keeps the number of in-flight and backing-off tasks at the configured limit, so a wave of failures cannot trigger a larger wave of new requests on top of the retries. The downside is that a few persistently failing items occupy slots while they sleep, which lowers throughput for the healthy items.