A Practical Guide To Python Asyncio
Modern software often spends more time waiting than calculating. A web application may pause for an HTTP response, a database query, a file operation, or a message from another service. If that waiting happens in a conventional sequential program, the processor can sit idle while the rest of the work remains queued.
Python’s asyncio library provides a way to run many waiting-heavy tasks cooperatively. It is especially useful for network clients, APIs, web crawlers, chat systems, real-time dashboards, and services that need to manage many connections without creating a thread for every operation.
This guide explains the event loop, coroutines, tasks, timeouts, error handling, and design choices behind asynchronous programming. The examples use modern Python syntax and focus on patterns that are practical in production, including applications serving users across Australian cities and time zones.
Understanding The Event Loop
The central object in asyncio is the event loop. It monitors asynchronous operations and resumes a coroutine when the operation can make progress. While one coroutine waits for a network response, the loop can run another coroutine that is ready to continue.
A coroutine is a function declared with async def. Calling it does not execute its body immediately; it returns a coroutine object. The coroutine starts when it is awaited by another coroutine or scheduled as a task. This distinction is important because simply creating a coroutine does not perform useful work.
import asyncio
async def greet():
print("Hello")
await asyncio.sleep(1)
print("Goodbye")
asyncio.run(greet())
asyncio.run() creates and manages an event loop for the top-level coroutine. The await expression pauses greet() during the one-second delay, allowing the loop to handle other available work. A helpful way to connect this idea with broader computational thinking is to review algorithm concepts, particularly the difference between doing work and waiting for work.
Writing Your First Coroutine
The async and await keywords define the basic control flow. An asynchronous function can call another asynchronous function with await, passing control back to the event loop whenever it reaches an operation that supports non-blocking waiting.
import asyncio
async def fetch_record(record_id):
await asyncio.sleep(0.5)
return {"id": record_id, "status": "ready"}
async def main():
record = await fetch_record(42)
print(record)
asyncio.run(main())
The call to fetch_record(42) is sequential here: main() waits until the record is available. That is often exactly what you need when the second operation depends on the result of the first. Async programming does not automatically make every line run in parallel; it gives you a mechanism for choosing where independent work can overlap.
await works with awaitable objects, such as coroutines, tasks, and futures. It cannot be used inside an ordinary synchronous function. If synchronous code needs to invoke asynchronous work, it should generally do so at a clear application boundary with asyncio.run(), rather than repeatedly creating event loops deep inside library code.
Running Independent Work Concurrently
When several operations are independent, asyncio.gather() is a convenient way to schedule them and collect their results. In this example, the total runtime is close to the longest individual delay rather than the sum of all delays.
import asyncio
async def download(name, delay):
await asyncio.sleep(delay)
return f"{name} complete"
async def main():
results = await asyncio.gather(
download("users", 2),
download("orders", 1),
download("inventory", 3),
)
print(results)
asyncio.run(main())
The functions above use sleep() to imitate network activity. In a real service, each coroutine might call an HTTP endpoint or query an asynchronous database driver. The important requirement is that the libraries involved support non-blocking operations. Calling a regular blocking function inside a coroutine still blocks the event loop.
For more control, create tasks with asyncio.create_task(). A task schedules a coroutine to run soon and lets the current coroutine continue. You can later await the task, inspect its result, or cancel it. Avoid creating thousands of tasks without a limit: a semaphore or queue can restrict concurrency and protect an external API from excessive requests.
Using Asyncio With Network Services
Asynchronous programming is a natural fit for network-heavy applications. A service in Sydney might request data from several providers, combine the responses, and return one API result. While one provider is processing the request, the event loop can make progress on the others. The same model can reduce resource usage for a monitoring tool tracking systems in Melbourne, Brisbane, and Perth.
Use an async-compatible client rather than wrapping a blocking client in an async def function. Libraries such as aiohttp and httpx provide asynchronous HTTP interfaces. A typical request should also include a timeout, because an unavailable server must not occupy a task indefinitely.
import asyncio
import httpx
async def get_json(client, url):
response = await client.get(url, timeout=5.0)
response.raise_for_status()
return response.json()
async def main():
urls = [
"https://example.com/a",
"https://example.com/b",
]
async with httpx.AsyncClient() as client:
results = await asyncio.gather(
*(get_json(client, url) for url in urls)
)
print(results)
asyncio.run(main())
The async with block ensures that connections are closed properly. Reusing one client is generally more efficient than creating a new client for every request because connection pooling can reduce repeated setup. For Australian businesses, this can matter when an application serves users across large geographic distances and communicates with cloud regions or payment providers outside the country.
Controlling Errors And Cancellation
Concurrent operations can fail independently. By default, asyncio.gather() propagates an exception from one awaitable, although other tasks may continue running depending on how they were created. Passing return_exceptions=True collects exceptions as values, which can be useful when partial results are acceptable.
async def main():
results = await asyncio.gather(
fetch_record(1),
fetch_record(2),
return_exceptions=True,
)
for result in results:
if isinstance(result, Exception):
print(f"Request failed: {result}")
else:
print(result)
Do not catch every exception and silently continue. Log enough context to diagnose the failure, and decide whether the operation should be retried. Retries need limits and backoff; otherwise, a failing dependency can create a storm of repeated requests.
Cancellation is another normal event rather than an exceptional programming mistake. A web request may be abandoned when a user closes a page, or a deployment may stop a worker. Use try and finally to release resources, and allow asyncio.CancelledError to propagate unless there is a strong reason to handle it.
async def worker():
connection = await open_connection()
try:
await process_messages(connection)
finally:
await connection.close()
Combining Asyncio With Data Work
asyncio is best for I/O-bound workloads, not for intensive CPU computation. Parsing a small JSON response is usually fine inside the event loop, but training a model, compressing a large file, or calculating a complex batch can block every other coroutine.
For blocking functions, asyncio.to_thread() can move the operation to a worker thread:
import asyncio
def read_large_file(path):
with open(path, "rb") as file:
return file.read()
async def load_data(path):
return await asyncio.to_thread(read_large_file, path)
Threads are useful for making existing synchronous libraries coexist with an async application, although they do not remove the cost of the operation. For genuinely CPU-bound work, a process pool or a separate worker service is often more appropriate. This separation is useful in machine learning systems where an async API accepts requests while a different component performs feature extraction or model inference.
Async pipelines can also coordinate data arriving from multiple sources. For example, a monitoring service might asynchronously collect sensor data, then pass batches to a synchronous analytics function. Clustering choices should remain separate from transport concerns; an explanation of Gaussian mixture models illustrates how statistical processing can be treated as its own clear computational stage.
Applying Asyncio In Real Applications
Asyncio applications benefit from explicit boundaries. Keep networking, scheduling, and business logic in separate functions so that each part can be tested independently. A coroutine that fetches data should not also decide how a web page is rendered, write unrelated files, and manage application shutdown.
Be aware of framework behaviour. ASGI frameworks such as FastAPI, Starlette, and Django’s asynchronous features can run coroutine-based handlers, but a synchronous database driver inside an async handler still blocks the server worker. Check the documentation for every dependency, especially authentication, cache, database, and message-queue clients.
Australian operational details can influence design. An online retailer may need to account for Australian Eastern, Central, and Western time zones when scheduling tasks, rather than assuming one local clock. Services handling personal information should also consider the Privacy Act 1988 and the Australian Privacy Principles when collecting, transmitting, and logging customer data. Async concurrency improves throughput, but it does not change obligations around consent, retention, or secure handling.
The event loop should also be observable. Record request durations, timeout counts, task failures, and queue lengths. During a busy period such as an end-of-financial-year reporting deadline or a major sale, these measurements reveal whether the bottleneck is a remote service, a database pool, CPU work, or an overly restrictive concurrency limit.
Recommended Asyncio Practices
Reliable asynchronous code comes from disciplined resource management and clear limits. Start with a small example, verify that the libraries are genuinely async-compatible, and test failure paths as carefully as successful responses. A program that works on a laptop can still fail under real traffic when a dependency slows down or connections remain open.
Use structured shutdown behaviour where possible. Cancel outstanding tasks, wait for them to finish cleanup, close clients and database pools, and then stop the event loop. This is particularly important for containerised services that receive termination signals during deployment.
- Use
asyncio.run()once at the application entry point whenever practical. - Prefer
asyncio.gather()or tasks for independent operations, and preserve sequentialawaitcalls for dependent steps. - Set timeouts on network and database operations so stalled dependencies cannot consume resources forever.
- Limit concurrency with semaphores, queues, connection pools, or service-specific rate limits.
- Move blocking file, legacy-library, and CPU-heavy work away from the event loop.
- Close asynchronous clients, streams, and database connections in
finallyblocks or asynchronous context managers. - Test cancellation, partial failures, retries, and shutdown instead of testing only the successful path.
Asyncio is most effective when it matches the workload. It can serve many waiting tasks efficiently, but it cannot make blocking code non-blocking merely because that code appears inside an async def. Once the event loop, awaitables, concurrency controls, and failure modes are understood, Python developers can build responsive services that remain easier to reason about as their workload grows.