Python’s asyncio lets one thread manage many in-flight operations when those operations can wait without blocking the event loop. That makes it useful for concurrent network requests, streaming updates, and services that spend much of their time waiting for responses. It does not mean that Python code is inherently blocking, that asynchronous execution makes every calculation faster, or that adding async automatically makes a synchronous HTTP client nonblocking. The important distinction is between work that can cooperatively yield control and work that occupies the executing thread until it finishes.
A high-performance API client therefore needs more than a collection of coroutines. It needs an asynchronous network library, connection management, bounded concurrency, timeouts, cancellation behavior, retry rules, and evidence that the server can handle the offered load. This tutorial develops that model and gives reproducible examples without claiming that a toy benchmark represents production capacity.
Understand the event loop before writing requests
The event loop schedules tasks and runs their Python code in turns. When a coroutine reaches an awaitable that is genuinely pending, the task can suspend so another ready task can run. For a network client, useful suspension points include waiting for a socket to connect, for data to arrive, or for a backoff interval. Ordinary CPU-bound Python code does not yield just because it lives inside an async def function. A long calculation, synchronous file read, blocking HTTP request, or time.sleep() call can still prevent the loop from serving other tasks promptly.
Use async def to declare a coroutine function and await to wait for an awaitable. Calling a coroutine function produces a coroutine object; it does not independently execute the operation. asyncio.run(main()) is a normal entry point for a standalone program, creating and closing the event loop around the main coroutine. Do not call it from inside a notebook or framework that already runs its own event loop; use that environment’s supported scheduling method instead.
The official Python coroutines and tasks documentation defines these behaviors, including cancellation and the distinctions between gather() and TaskGroup. Read the documentation for your installed interpreter version because features such as TaskGroup require Python 3.11 or later.
Demonstrate concurrency without depending on a web service
Start with a deterministic simulation before involving real API credentials, rate limits, DNS, or proxy settings:
import asyncio
async def simulated_request(name, delay):
await asyncio.sleep(delay) # yields to other ready tasks
return f"{name}: complete"
async def main():
results = await asyncio.gather(
simulated_request("alpha", 0.3),
simulated_request("beta", 0.2),
simulated_request("gamma", 0.1),
)
print(results)
asyncio.run(main())
All three requests are scheduled concurrently; the total waiting time is normally close to the longest individual delay plus scheduling overhead, rather than the sum of the delays. The result list remains in argument order even when operations finish in a different order. asyncio.sleep() is deliberately not a network request, and this example cannot measure real HTTP throughput. Its purpose is to make suspension and result ordering visible.
Compare that code with a loop that calls time.sleep() inside each coroutine. The synchronous sleep blocks the event-loop thread, so the apparent concurrency disappears. Replace the artificial delay with a true asynchronous I/O operation only after selecting an appropriate HTTP client.
Choose an asynchronous HTTP client deliberately
Python’s standard-library urllib.request functions are synchronous. Wrapping one in an async def function does not change that. For production HTTP work, use a reputable asynchronous client whose documented interfaces match the installed package version; alternatives include HTTPX’s AsyncClient and aiohttp. These libraries are not identical, so adapt examples to one rather than combining their APIs.
For example, the conceptual HTTPX pattern is to create a reusable AsyncClient in an async with block, then await its get() or post() methods. Reuse the same client for related requests to benefit from connection pooling instead of instantiating a new client for each URL. Set explicit connect/read/request timeouts, reasonable connection limits, and TLS verification appropriate to the environment. Do not disable certificate verification for convenience or assume that a timeout means the server performed no work.
API credentials belong in an approved secret-management workflow, not inside demonstration source pasted into a blog post. Avoid copying access tokens into exception messages, logs, query strings, screenshots, or analytics. Test against a controlled service or the provider’s documented sandbox, and verify its usage policy before making concurrent requests.
Bound concurrency and respect the provider
Creating thousands of coroutines at once can exhaust file descriptors, connection pools, memory, DNS capacity, or server quotas. A semaphore can bound the number of simultaneously active operations:
import asyncio
async def bounded_call(name, semaphore):
async with semaphore:
await asyncio.sleep(0.1) # replace with real async I/O
return name
async def main():
limit = asyncio.Semaphore(5)
jobs = [bounded_call(str(i), limit) for i in range(20)]
return await asyncio.gather(*jobs)
print(asyncio.run(main()))
A semaphore limits activity inside the protected section; it is not a complete request-rate limiter. Ten requests per second and ten concurrent requests are different constraints. For APIs that publish quotas, combine bounded concurrency with request pacing and explicit handling of 429 Too Many Requests or documented backoff signals. Honor Retry-After where applicable and avoid synchronized retry storms.
Do not optimize solely for the shortest local wall-clock time. Record successful responses, errors, timeout rates, server-side rate-limit responses, transferred bytes, connection utilization, and the number of outstanding tasks. A faster client that overloads the service, duplicates orders, or loses errors is not higher quality.
Use structured concurrency and explicit error handling
There are different ways to coordinate related tasks. asyncio.gather() collects results in order, but under its default behavior an exception from one awaited operation is propagated without automatically cancelling all other scheduled operations. This matters when requests have side effects or subsequent tasks must not continue after a failure. asyncio.TaskGroup, available starting with Python 3.11, provides structured concurrency: the group owns its child tasks and waits for them as a unit; on an ordinary child failure, other tasks in the group are cancelled and failures are reported together.
Neither approach removes the need for application-specific recovery. A cancelled client task might already have submitted a request to the server. You cannot assume that cancellation or a timeout rolls back a payment, a data modification, or a queued job. For side-effecting APIs, use provider-supported idempotency keys, transaction identifiers, and reconciliation before retrying. GET-like read operations and POST-like write operations usually need different retry policies.
Catch expected network errors at a boundary where they can be classified. Distinguish DNS/connect failures, TLS errors, HTTP status errors, response parsing failures, and cancellations. Use try/finally or asynchronous context managers so sockets, files, and other resources are released. Avoid swallowing asyncio.CancelledError; the event loop and structured-concurrency machinery depend on cancellation propagation.
At the application level, consider returning a record containing the request identifier, result type, elapsed time, status code, and the minimum safe diagnostic information. That structure makes partial success visible when processing a batch of API calls. Do not return raw secrets or entire response payloads into general-purpose logs.
Separate CPU-heavy work from asynchronous waiting
Async I/O improves overlap during waiting; it does not create additional CPU cores. JSON parsing of very large payloads, image processing, encryption workloads, machine-learning inference, or complex numerical calculations can block the event-loop thread. Some workloads can be offloaded with asyncio.to_thread() when a synchronous function is I/O-bound, but this is not a universal solution for CPU-bound Python work. Process pools, worker services, native extensions, or distributed queues may be more appropriate for heavy compute depending on the environment and data ownership.
A service often combines the two kinds of work. For example, collecting metrics from multiple APIs is I/O-heavy, while performing an expensive analysis on every response may be CPU-heavy. Design the pipeline so the event loop does not become the bottleneck during analysis. Bounded queues and backpressure prevent fast producers from overwhelming slower consumers.
Memory also deserves attention. If every request collects a large response body and all results are retained in a single list, a highly concurrent run can consume far more memory than a sequential one. Stream data when the client supports it, parse incrementally where appropriate, and release completed results promptly after their downstream consumer has accepted them.
Test throughput, failure behavior, and recovery
Establish a sequential baseline with the same endpoint, request size, authentication and network path. Then run an async version with a small concurrency limit, increase that limit gradually, and watch latency percentiles as well as total throughput. A plateau or rising error rate indicates that another constraint has been reached. That constraint may be the server, its rate limiter, the client’s connection pool, an intermediate proxy, a database, or the local machine.
Test with predictable failures: a slow response, connection refusal, malformed JSON, intermittent 503, 429 with Retry-After, expired credentials, cancellation during a response, and shutdown while requests are pending. Verify that logs identify the failing operation without exposing sensitive information and that retry behavior matches the endpoint’s semantics.
For scheduled workloads, store durable progress so a restart knows what completed. In-memory task lists vanish when the process exits. When an API changes remote state, reconciliation through a provider transaction identifier is safer than simply resending all timed-out requests.
The correct goal is not the largest possible number of tasks. It is a predictable system that increases useful throughput while keeping latency, error handling, rate limits, and resource usage within defined bounds. Once you can measure those properties, asyncio becomes a practical engineering tool rather than a promise that every Python program will run faster.