Tactical blueprint for high-performance Python asyncio. Focuses on structured concurrency, resource safety, and resilient background processing.
This blueprint provides the procedural truth for engineering high-performance, non-blocking systems using Python's asyncio ecosystem.
This skill should be used when completing tasks related to python async.
Follow these procedures to implement the capability:
TaskGroup: Always use asyncio.TaskGroup() for managing multiple tasks. It ensures that if one task fails, all others are cancelled, preventing "zombie" tasks.asyncio.wait_for(coro, timeout=X).asyncio.shield() only when a task must complete even if the parent is cancelled (e.g., critical DB writes).async with for every resource that supports it (Sessions, Files, Connections).async with, implement a try...finally block to ensure await resource.close() is called.aiohttp.ClientSession for every request. Implement a singleton or lifespan-managed session pool.asyncio.Queue for local background processing. Implement 3+ workers to ensure throughput.await queue.join()) before terminating the process.asyncio.to_thread() to run CPU-bound or blocking I/O (e.g., legacy libs) in a separate thread without blocking the event loop.| Symptom | Probable Cause | Recovery Operation |
| : | : | : |
| Event Loop Lag | Blocking I/O (e.g., requests.get) called in async code. | Identify the blocker via loop.set_debug(True); replace with aiohttp or wrap in to_thread(). |
| Silent Task Failure | Background task raised an exception that wasn't awaited. | Attach a callback via task.add_done_callback() to log errors; use TaskGroup to ensure exceptions bubble up. |
| Memory Leak (Zombie Tasks) | asyncio.create_task() called without tracking the task or using a TaskGroup. | Move tasks into a managed list or use a TaskGroup context manager. |
async def worker(queue: asyncio.Queue, worker_id: int):
while True:
item = await queue.get()
try:
await process_item(item)
except Exception as e:
logger.error(f"Worker {worker_id} failed: {e}")
finally:
queue.task_done()
@asynccontextmanager
async def lifespan(app: FastAPI):
# Setup: Create global session
app.state.http_client = aiohttp.ClientSession()
yield
# Teardown: Close global session
await app.state.http_client.close()
| Action | Command / Tool |
| : | : |
| Debug Loop | asyncio.run(main(), debug=True) |
| Profile Async | py-spy record -o profile.svg --pid <PID> |
| Test Async | pytest-asyncio |
Before finalized any async implementation:
async with or lifespan.TaskGroup or Semaphore (to prevent DDOSing backends).npx skills add gitwalter/编程 — Python asyncio下载完整 Skill 目录,包含 SKILL.md 及所有相关文件
Category:other