Python

asyncio Concurrency Limiter (Semaphore)

admin by @admin ADMIN
4d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Run hundreds of coroutines but cap how many are in-flight at any moment. asyncio.Semaphore inside the task body is the cleanest way to "do at most 10 of these at a time."
Python
Raw
import asyncio
import aiohttp

async def fetch(session, sem, url):
    async with sem:               # blocks if N tasks already inside
        async with session.get(url) as r:
            return await r.text()

async def fetch_many(urls, limit=10):
    sem = asyncio.Semaphore(limit)
    async with aiohttp.ClientSession() as session:
        return await asyncio.gather(*(fetch(session, sem, u) for u in urls))

# 1000 URLs, but never more than 10 in flight at once
urls = [f"https://api.example.com/items/{i}" for i in range(1000)]
results = asyncio.run(fetch_many(urls, limit=10))
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.