Full answer
python
import asyncio
active = 0
peak = 0
async def call_api(i, sem):
global active, peak
async with sem:
active += 1
peak = max(peak, active)
await asyncio.sleep(0.02)
active -= 1
return i * i
async def main():
sem = asyncio.Semaphore(3)
results = await asyncio.gather(*(call_api(i, sem) for i in range(10)))
print(results)
print("peak concurrency:", peak)
asyncio.run(main())Output:
text
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
peak concurrency: 3Ten calls start at once, but the semaphore lets only three proceed at a time, so peak concurrency is 3. gather still returns results in input order. The shared counters are safe without a lock here because asyncio runs on one thread and the updates happen between awaits. For very large job lists, a fixed pool of worker tasks reading from an asyncio.Queue avoids creating thousands of pending tasks at once. HTTP clients such as httpx and aiohttp also offer connection limits.
python
import asyncio
active = 0
peak = 0
async def call_api(i, sem):
global active, peak
async with sem:
active += 1
peak = max(peak, active)
await asyncio.sleep(0.02)
active -= 1
return i * i
async def main():
sem = asyncio.Semaphore(3)
results = await asyncio.gather(*(call_api(i, sem) for i in range(10)))
print(results)
print("peak concurrency:", peak)
asyncio.run(main())Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- Semaphore caps simultaneous holders
- gather keeps input order
- Worker pools with a Queue scale better
- Combine with time-based limits for rate caps
- Single-threaded asyncio avoids data races between awaits
Common mistakes
- Firing unlimited concurrent requests
- Using threading.Semaphore in async code
Follow-ups
- How would you implement 10 requests per second?
- How do you retry with backoff in asyncio?
Tips
- Measure the peak