asyncio and asyncio.gather
As a Fresher engineer, explain asyncio and asyncio.gather. What problem does it solve and how would you describe it in an interview?
Answers use simple, clear English.
Quick interview answer
At Fresher depth: start with the problem, then mechanism, then a short example. async def coroutines await non-blocking IO.
Detailed answer
At Fresher depth: start with the problem, then mechanism, then a short example. async def coroutines await non-blocking IO. asyncio.gather runs coroutines concurrently; return_exceptions=True prevents one failure cancelling others. Core: async def coroutines await non-blocking IO. asyncio.gather runs coroutines concurrently; return_exceptions=True prevents one failure cancelling others. Real-time example: FastAPI endpoint gathers user DB query + Redis cache + external HTTP in parallel. Pros: High concurrency for IO-bound workloads on single thread. Cons: CPU-bound code blocks loop — use ProcessPoolExecutor; debugging async stack traces harder. Common mistakes: Calling blocking requests.get inside async def; forgetting await on gather result. Best practices: Use httpx.AsyncClient; set timeouts; limit concurrency with Semaphore. Audience level: Fresher.
Full explanation
async def coroutines await non-blocking IO. asyncio.gather runs coroutines concurrently; return_exceptions=True prevents one failure cancelling others.
Real example & use case
FastAPI endpoint gathers user DB query + Redis cache + external HTTP in parallel.
Pros & cons
Pros: High concurrency for IO-bound workloads on single thread. Cons: CPU-bound code blocks loop — use ProcessPoolExecutor; debugging async stack traces harder.
Common mistakes
Calling blocking requests.get inside async def; forgetting await on gather result.
Best practices
Use httpx.AsyncClient; set timeouts; limit concurrency with Semaphore.
Follow-up questions
- How would you test asyncio and asyncio.gather?
- What metrics prove asyncio and asyncio.gather is healthy in prod?
- How does asyncio and asyncio.gather change at 10× traffic?