Use this when Python must handle many network operations concurrently.
AsyncIO
AsyncIO is Python's library for asynchronous code with async and await, letting one thread handle many concurrent network operations, such as polling hundreds of devices with aiohttp or asyncssh.
1. asyncio runs many I/O tasks concurrently (APIs, SSH with asyncssh).
2. Limit concurrency with semaphores.
3. Timeouts per task.
4. Handle exceptions in gather.
5. Don't block the event loop.
tasks → event loop → concurrent I/O → results
Context & applicabilityCommon mistakes · platform/version boundaries
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
Capture the concrete output, symptom, packet, log or counter before changing anything.
Step 1 Verification path Verify boundary
Use debug/development mode and a fixture with concurrent tasks, one controlled timeout/cancellation and one exception. Show every created task is awaited/owned, exceptions surface to the caller, and cleanup executes on cancellation. Measure event-loop responsiveness while invoking suspected blocking work. Repeat with deterministic IDs so completion ordering can vary without changing correctness.
Step 2 Common mistakes Narrow the fault
- Blocking libraries inside asyncio.
Step 3 Where it fails Narrow the fault
Separate coroutine scheduling/event-loop health, task logic, blocking dependency calls, network/service latency and cleanup. A slow remote API is not the same as a blocked event loop; cancellation does not guarantee a remote side effect was undone. Do not blindly recreate tasks after ambiguous timeout. Inspect task state and external target before retrying, and fix ownership before increasing concurrency.
Evidence · 1 on this Topic
Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.
- async/await in one thread.
- aiohttp, asyncssh.
- Limit with semaphores.
python3 -c 'import asyncio;print(asyncio.run(asyncio.sleep(0,"ok")))'— asyncio works- Semaphore for concurrency limit — protection
- Timeouts with asyncio.wait_for — hangs
ReferenceWhy it matters1 section · depth on demand
In depth
AsyncIO is Python's built-in framework for concurrent I/O using async/await: while one task waits for a network response, others run. It is ideal for calling many APIs or devices at once from a single thread.
import asyncio, httpx
async def fetch(client, url):
r = await client.get(url, timeout=10)
return url, r.status_code
async def main(urls):
sem = asyncio.Semaphore(20) # limit concurrency
async with httpx.AsyncClient() as client:
async def limited(u):
async with sem:
return await fetch(client, u)
return await asyncio.gather(*(limited(u) for u in urls))
results = asyncio.run(main(urls))
Async code only helps I/O-bound work and needs async-capable libraries; CPU-heavy work still needs processes.
ReferenceImportant terms & boundaries1 section · depth on demand
Mechanics
asyncio provides cooperative concurrency around an event loop, coroutines, tasks, futures and nonblocking I/O. A coroutine does nothing until awaited/scheduled; tasks make progress when control returns to the loop. Blocking CPU or synchronous I/O inside the loop stalls unrelated tasks. Cancellation is delivered as an exception at await points and must coexist with cleanup. Task lifetime and exception observation are part of correctness, not incidental implementation details.
ReferenceConfiguration & state1 section · depth on demand
Lifecycle
Run one top-level event-loop lifecycle with asyncio.run or an explicitly owned loop, and use structured task ownership so background tasks do not outlive their caller accidentally. Define timeouts, cancellation and cleanup for sockets/sessions/files. Keep blocking libraries behind threads/processes where appropriate, and pin Python/library behavior for production. Avoid global hidden tasks started during import.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Verification history & basis
When and against what this Topic was checked. Later text edits do not count as a new check.
Authoritative/upstream documentation reviewed for bounded claims in Python Automation > AsyncIO. Documentation verification only; this is not observed lab or production Evidence.
Basis: https://docs.python.org/3/library/asyncio.html · confidence 94%Quick lookup tables
Python Automation → AsyncIO · operational reference
Context-specific ownership, verification, output and failure-boundary lookup for Python Automation → AsyncIO.
| Layer | Python Automation → AsyncIO operational reference |
|---|---|
| Runtime/ownership | Python asyncio event loop and structured asynchronous I/O · identify controller/parser, durable intent, identity and target ownership before mutation |
| Persistent intent | Versioned definition/configuration with explicit dependencies, scope and credential boundary |
| Verification | python -X dev async_probe.py; capture task names/results/exceptions, timeout/cancellation paths and resource cleanup. |
| Expected interpretation | Coroutines execute on the intended event loop, awaited tasks finish or cancel deterministically, exceptions are observed, blocking work does not stall the loop, and resources close cleanly. |
| Recovery boundary | Preserve correlation IDs + pre-state, repair first failing boundary, then verify the target independently |
Deep reference
Healthy vs suspicious evidence
Output interpretation
Capture task/correlation name, start/end, result or exception type, timeout/cancel reason, retry attempt and resource IDs. Completion order should not be mistaken for submission order. Warnings about never-awaited coroutines, pending tasks or slow callbacks are important evidence. Aggregate results should preserve per-task failures rather than only one overall exit code.