Skip to main content

Python Async Programming Patterns

Master Python asyncio with practical patterns for concurrent HTTP requests, database queries, task queues, and real-time data processing.

Fill in the placeholders

Edit the values, then copy your finished prompt.

Your Prompt
prompt.txt
Create a comprehensive Python asyncio implementation guide for a real-time data aggregation service that needs to handle 500 concurrent API calls and 50 simultaneous database operations. The project uses Python 3.12 and aiohttp, asyncpg, and aiocache. Build these patterns: 1) Design the async application structure — create an async main() entry point, configure the event loop with uvloop for performance, set up graceful shutdown handling for SIGTERM/SIGINT, and implement structured concurrency using TaskGroups. Show the project layout with async services, repositories, and handlers. 2) Implement concurrent HTTP requests using aiohttp — build an AsyncHTTPClient class that manages a connection pool of 100 connections, implements retry with exponential backoff, respects rate limits with a token bucket algorithm limiting to 200 requests per second, handles timeouts at both connection and read levels, and batches 50 requests using asyncio.gather() with return_exceptions=True. 3) Create an async database pattern using asyncpg with SQLAlchemy 2.0 async — implement connection pooling with 20 connections, write async CRUD operations with proper transaction management (async with session.begin()), and demonstrate the unit-of-work pattern with async context managers. 4) Build a producer-consumer pipeline using asyncio.Queue — create 10 worker coroutines that consume from a queue, process items with JSON transformation, validation, and database insertion, handle backpressure when the queue exceeds 1000, and implement a dead-letter queue for failed items. 5) Implement async generators for streaming data: read a WebSocket feed of market data in chunks, transform data with async generator composition (yield from equivalent), and demonstrate async for iteration. 6) Add observability: implement async-compatible logging that includes the task name, create async timing decorators that measure and report coroutine execution time, and build a health check endpoint that reports event loop lag and active task count. 7) Handle the common async pitfalls: demonstrate proper exception handling in gathered tasks, show how to avoid blocking the event loop with CPU-bound work (use run_in_executor with ProcessPoolExecutor with 4 workers), and prevent resource leaks with async context managers.

What this prompt does

This prompt produces a comprehensive Python asyncio implementation guide for a [project_type] that must handle a specific [concurrency_requirement]. Rather than abstract theory, it builds the patterns that matter in production: an async application structure with graceful shutdown and TaskGroups, concurrent HTTP with connection pooling and rate limiting, async database access, a producer-consumer pipeline with backpressure, async generators for streaming, observability, and the common pitfalls. Grounding everything in [python_version] and [async_libraries] keeps the code concrete and runnable.

The variables size the system. [pool_size], [rate_limit], and [batch_size] shape the HTTP client's connection pool, token-bucket limiting, and asyncio.gather batching with exponential backoff, while [db_library] and [db_pool_size] define the async database layer and its unit-of-work pattern. [worker_count] and [queue_max_size] drive the producer-consumer pipeline and when backpressure kicks in, [data_source] feeds the streaming async generators, and [executor_type] handles offloading CPU-bound work so it never blocks the event loop. A dead-letter queue captures items that repeatedly fail so one bad payload does not stall the whole pipeline.

When to use it

  • Building a service that fans out to many APIs or databases concurrently.
  • Implementing rate-limited, pooled HTTP clients with retry and backoff in aiohttp.
  • Designing a producer-consumer pipeline with real backpressure and a dead-letter queue.
  • Streaming large data sources in chunks with async generators.
  • Avoiding event-loop blocking by offloading CPU-bound work via [executor_type].
  • Adding async-aware observability like event-loop lag and active task counts.

Example output

You get a structured implementation guide with code: an async main() with event-loop config via [event_loop_config], SIGTERM/SIGINT graceful shutdown, and TaskGroups; an AsyncHTTPClient managing a [pool_size]-connection pool with exponential backoff, a token bucket at [rate_limit], and [batch_size] batching via gather(return_exceptions=True); an async database layer on [db_library] with a [db_pool_size] pool and unit-of-work; a [worker_count]-worker queue pipeline with backpressure at [queue_max_size] and a dead-letter queue; async generators streaming [data_source]; observability helpers; and a pitfalls section covering run_in_executor with [executor_type].

Pro tips

  • Use structured concurrency (TaskGroups) so one failing task cancels its siblings cleanly rather than leaking orphaned coroutines.
  • Always pass return_exceptions=True to gather when batching [batch_size] requests, then inspect results, so one failure does not sink the whole batch.
  • Never run CPU-bound work directly in a coroutine; offload it with run_in_executor and [executor_type], or it blocks the entire event loop.
  • Set [queue_max_size] to enforce real backpressure; an unbounded queue just moves your out-of-memory crash downstream.
  • Match [pool_size] and [rate_limit] to what the upstream API actually tolerates, not just your peak ambition, or you will trade throughput for a wall of 429 errors.
  • Tag async logs with the task name and add timing decorators around key coroutines; without that context, interleaved concurrent logs are nearly impossible to follow when something stalls.

Frequently Asked Questions

Why use run_in_executor for CPU-bound work in async code?
asyncio runs on a single thread, so CPU-heavy work blocks the event loop and stalls every other coroutine. Offloading it to `[executor_type]` via `run_in_executor` keeps the loop responsive, which is essential when you are juggling hundreds of concurrent I/O operations.
What does backpressure mean in the queue pipeline?
When producers outpace consumers, the queue grows. Capping it at `[queue_max_size]` makes producers wait once it fills, preventing unbounded memory growth. The prompt also adds a dead-letter queue so items that repeatedly fail processing are set aside rather than blocking the pipeline.
Is uvloop required for this to work?
No. uvloop is the default `[event_loop_config]` for better performance, but the patterns work on the standard asyncio loop too. uvloop is a drop-in speedup on Linux and macOS, while standard asyncio remains the portable fallback, including on Windows.
How does it prevent one failed request from breaking a batch?
It uses `asyncio.gather` with `return_exceptions=True`, which returns exceptions as results instead of raising immediately. You then inspect each result and handle failures individually, so a single failing call in a `[batch_size]` batch does not cancel the rest.
Engr Mejba Ahmed

Need this built for real?

Engr Mejba Ahmed

AI Developer · Software Engineer

I'm Mejba — I design and ship production AI systems, automations, and full-stack apps. If you want this turned into a working solution for your team, let's talk.

More in Python & Automation Prompts

Engr Mejba Ahmed

Engr Mejba Ahmed

AI assistant · trained on my work

👋

Hey there!

Quick Actions

WhatsApp Direct line to me

Chat on WhatsApp

+880 1723 741224 · Replies within the hour on working days

Popular Questions

Engr Mejba Ahmed is connected
Engr Mejba Ahmed is typing...
Engr Mejba Ahmed avatar

✉ Want me to follow up? Drop your email

Engr Mejba Ahmed avatar

📞 Connect Directly

Choose how you'd like to reach me

WhatsApp

+880 1723 741224

Email

mejba.13@gmail.com

✓ Details sent! I'll get back to you shortly.

Powered by OpenAI

335+

Blog Posts

25

AI Courses

63

Projects

Services & Expertise

Pricing & Process

Learning & Resources

Connect & Support