Interview Prep/Python for DevOps/Concurrency: threads, processes & asyncio

How do you run many async tasks concurrently with a limit?

IntermediateConceptConcurrency: threads, processes & asyncio
Answer
async def probe(client, sem, url):
    async with sem:
        try:
            r = await client.get(url)
            return url, r.status_code
        except httpx.HTTPError as e:
            return url, repr(e)

async def main(urls):
    sem = asyncio.Semaphore(50)
    async with httpx.AsyncClient(timeout=5) as client:
        return await asyncio.gather(*(probe(client, sem, u) for u in urls))

Without the semaphore, 10,000 URLs means 10,000 simultaneous sockets, which hits file descriptor limits and rate limits.

All Python for DevOps questions Roadmap: Python for automation

More on Concurrency: threads, processes & asyncio