Python asyncio training exercises
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Python's asyncio module provides an event loop for writing concurrent code using async/await syntax. It is designed for I/O-bound workloads — network requests, file operations, database queries — where the program spends most of its time waiting. Learning asyncio through hands-on exercises builds intuition for how coroutines schedule, how await suspends execution, and how to structure concurrent tasks. The exercises below progress from basic coroutines to real-world patterns like concurrent HTTP requests and producer-consumer queues.
Exercise 1: Basic Coroutine
This runs two coroutines sequentially. Each await suspends main() until the coroutine completes. The total time is the sum of both delays.
Exercise 2: Concurrent Tasks with gather
asyncio.gather() runs coroutines concurrently. The total time equals the longest task, not the sum. This is the most common pattern for parallelizing I/O-bound operations.
Exercise 3: Handling Exceptions in Tasks
Without return_exceptions=True, gather raises the first exception and cancels remaining tasks. With it, exceptions are returned as results, letting you handle each task's outcome individually.
Exercise 4: Producer-Consumer with asyncio.Queue
asyncio.Queue provides backpressure — put() blocks when the queue is full, and get() blocks when empty. This is the standard pattern for coordinating async producers and consumers.
Exercise 5: Timeout and Cancellation
asyncio.wait_for() wraps a coroutine with a timeout. task.cancel() sends a CancelledError to the coroutine at its next await point. Both are essential for building resilient async applications.
Exercise 6: Semaphore for Rate Limiting
A semaphore limits how many coroutines run concurrently. This prevents overwhelming an API or database with too many simultaneous connections.
Exercise 7: Real HTTP Requests with aiohttp
aiohttp is the standard library for async HTTP in Python. Share a single ClientSession across requests for connection pooling.
Common Pitfalls
- Forgetting to await coroutines: Calling
async_func()withoutawaitreturns a coroutine object instead of executing it. You get aRuntimeWarning: coroutine was never awaitedmessage. Alwaysawaitor wrap increate_task(). - Blocking the event loop: Calling
time.sleep(),requests.get(), or any synchronous I/O inside a coroutine blocks the entire event loop. Useawait asyncio.sleep(),aiohttp, orasyncio.to_thread()for blocking calls. - Using asyncio.run() inside a running loop:
asyncio.run()creates a new event loop and fails if one is already running (common in Jupyter notebooks). Useawaitdirectly ornest_asyncioin notebooks. - Not handling CancelledError: When a task is cancelled,
CancelledErroris raised at the nextawait. If you catchExceptionbroadly, you may accidentally swallow cancellation. CatchCancelledErrorexplicitly and re-raise if needed. - Creating too many concurrent tasks: Launching 10,000 tasks with
gather()without a semaphore opens 10,000 connections simultaneously. Useasyncio.Semaphoreorasyncio.TaskGroup(Python 3.11+) with limits.
Summary
- Use
async defandawaitto define and run coroutines asyncio.gather()runs multiple coroutines concurrently — total time equals the slowest taskasyncio.Queuecoordinates producer-consumer workflows with backpressureasyncio.wait_for()adds timeouts;task.cancel()stops running tasksasyncio.Semaphorelimits concurrent execution for rate limiting- Never block the event loop — use async libraries or
asyncio.to_thread()for synchronous code
Related reading
- Python asyncio unreferenced tasks are destroyed by garbage collector?
- Python asyncio wait_for synchronous
- Python asyncio wait for threads
- python aws botocore.response.streamingbody to json
- Python Brute Force algorithm
- Python Can I use class variables as thread locks?
- python capitalize first letter only
- python Change the scripts working directory to the script's own directory
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.