All about Python AsyncIO for GenAI developers
If you are like me, you must be wondering what this “async” buzz is all about. Recently, we’ve seen a significant rise in asynchronous programming across modern applications. Initially, dragging my feet on learning it, I finally decided to take a closer look, and what a revelation it was. I was wondering why I did not know about it. This library has actually been part of Python’s ecosystem for over a decade, and fortunately, it is not nearly as complex as it might first appear. What is particularly exciting is how tremendously useful async programming has become, especially when building GenAI(Agents and all) applications, which most of us are involved with these days.
In this introductory article, I will start from first principles and build up your understanding step by step, covering only essential concepts you will need to get started.
Why do we suddenly need Async?
These days, with the rise of microservices and models as a service(OpenAI’s LLMs), we are seeing a lot of programs that call API endpoints and then simply wait for responses. Similarly, a lot of our code spends time writing to databases or files. These kinds of operations are classified as I/O operations (or I/O-bound operations), unlike CPU-bound operations, for example, running a machine learning model to give the predictions.
If you think about it fundamentally, when a client is performing I/O operations, it is not actively doing any computations; the CPU sits idle, waiting for data to arrive or confirm it was written. And we really hate idle compute resources! This is precisely where the async paradigm shines. The core idea is elegantly simple: we can run multiple I/O-bound (read: async) tasks concurrently and wait on all of them simultaneously. After all, if we are going to be waiting anyway, we might as well wait for multiple operations at once.
This approach makes particularly good sense in modern systems, where applications frequently need to coordinate with multiple services, databases, and external systems. Rather than blocking while waiting for each operation in sequence, async programming lets us maximize throughput by overlapping these waiting periods, ultimately reducing latency and delivering more responsive applications.
Comparing Asynchronous Programming, Multithreading, and Multiprocessing
If you are already here, you must have heard of multithreading and multiprocessing. I will take a short detour just for the sake of completeness — you can safely ignore this section. Asynchronous programming is very much like parallel programming, and since we’re on this topic, let’s see what other paradigms exist.
Asynchronous Programming
Asynchronous programming is ideal for I/O-bound operations like network calls and file operations. It uses single-threaded cooperative multitasking, where tasks voluntarily yield control at well-defined points. This approach provides excellent resource efficiency with very low overhead since everything runs in a single thread. The Python GIL(Global Interpreter Lock) doesn’t affect it negatively.
Best for: Web scraping, chat applications, API orchestration, and network-heavy applications
Advantages: Resource efficiency, no thread synchronization issues, excellent for waiting operations
Limitations: Requires “async all the way down,” debugging challenges, and needs async-compatible libraries. All functions and the involved library should be async
An example can be a travel booking platform, which uses async programming to query dozens of airline, hotel, and car rental APIs simultaneously. This reduces search response times from potentially 10+ seconds (if done sequentially) to just 1–2 seconds, dramatically improving user experience while efficiently utilizing system resources.
Multithreading
Multithreading creates multiple execution paths within the same process that share memory. In Python, it’s limited by the Global Interpreter Lock (GIL), which prevents true CPU parallelism. Threads are preemptively scheduled by the operating system.
Best for: I/O-bound operations with blocking code, GUI applications, database connection pools. Before async became popular in Python, we were using multithreading for the job.
Advantages: Works with synchronous code, simpler conceptual model, good for mixing blocking and non-blocking operations.
Limitations: Thread safety concerns, GIL limitations for CPU tasks, increased memory overhead
Multiprocessing
Multiprocessing launches separate processes, each with its own Python interpreter and memory space. This approach bypasses the GIL constraint, enabling true parallelism across CPU cores, but with higher communication costs. This is equivalent to running the same Python file in multiple terminals with different and independent data.
Best for: CPU-bound computations like image processing, scientific simulations, machine learning, big data tasks
Advantages: True parallelism across CPU cores, isolation prevents shared state issues
Limitations: Higher memory usage, expensive process creation, complex inter-process communication, no shared memory among processes.
Weather Forecasting Systems: Organizations like NOAA distribute massive computational workloads across thousands of processors, with each process handling different geographic regions or atmospheric layers. This CPU-intensive number crunching leverages true parallelism to generate complex weather models that would otherwise take too long to be useful.
Understanding Python’s AsyncIO Library
With preliminaries done, let’s jump to the actual library. The following examples aren’t exhaustive — they’re designed to convey the core concepts. There are many other interesting methods and functions in the library that you should explore if needed. But for most cases, what I’ll cover below will be enough to get you started.
As we go through these examples, remember that the goal is to understand the patterns and principles behind async programming, not to memorize every API detail. Once you grasp these fundamentals, you’ll find it straightforward to discover and apply more specialized features when your applications require them.
Introduction to AsyncIO
Python’s AsyncIO library provides a framework for writing single threaded concurrent code using coroutines(explaination upcoming). It serves as the foundation for asynchronous programming in Python, enabling efficient handling of many concurrent operations without the overhead of threads or processes.
What is a Coroutine?
A coroutine is a specialized function that can pause its execution at designated points, allowing other code to run, and later resume from where it left off. Think of it as a function that can have multiple entry and exit points.
Defining Coroutines with async def
# This is how you define a coroutine
async def fetch_data(url):
print(f"Starting to fetch data from {url}")
# Simulate network delay
await asyncio.sleep(2)
print(f"Finished fetching data from {url}")
return f"Data from {url}"The async def Syntax tells Python this function is a coroutine. When called, it doesn't execute immediately but returns a coroutine object.
# This doesn't run the function, just creates a coroutine object
coro = fetch_data("https://example.com")
print(coro)
# Output: <coroutine object fetch_data at 0x...>This coroutine object is essentially a promise of future work. To actually execute it, we need to await it or schedule it with the event loop.
Running Coroutines
Using await Inside Another Coroutine
The await keyword pauses the current coroutine until the awaited coroutine completes:
async def main():
# This pauses main() until fetch_data completes
result = await fetch_data("https://example.com")
print(f"Result: {result}")
return resultRunning with asyncio.run()
To run a coroutine from synchronous code:
# This is the proper way to run the top-level coroutine
import asyncio
# For Python 3.7+
result = asyncio.run(main())Running in Jupyter Notebooks
Jupyter notebooks require special handling as they already have an event loop:
# For Jupyter notebooks
import nest_asyncio
nest_asyncio.apply()
# Now you can use asyncio.run() in notebooks
result = asyncio.run(main())
# Alternatively, you can use this pattern:
await main() # This works directly in notebook cells with IPython 7+Creating and Managing Tasks
What is a Task?
A task is a powerful abstraction that wraps around a coroutine, automatically scheduling it for execution on the event loop. Think of it as an independent unit of work that gains a life of its own once created, intelligently finding opportunities to progress whenever other coroutines pause during I/O operations or awaiting other results.
What makes tasks particularly powerful is their autonomy. When you create a task using asyncio.create_task(), you are essentially telling the event loop: "Run this whenever you have a chance." The task then opportunistically executes during those small windows of time between other coroutines' operations, maximizing CPU utilization that would otherwise be wasted.
async def main():
# Create a task
task = asyncio.create_task(fetch_data("https://example.com"))
# Do other work while the task runs in the background
print("Doing other work...")
await asyncio.sleep(1)
# Wait for the task to complete
result = await task
print(f"Task result: {result}")At the end of your main coroutine, you have a choice: you can either gather the results of your tasks using await or asyncio.gather() If you need their return values, or you can simply let them complete on their own if the results aren't necessary. This flexibility makes tasks ideal for operations like logging, cache updates, or analytics that can safely run in the background without blocking your primary workflow.
By the way there are other cool methods related to task management, you can explore them if needed
task.cancel(): Requests cancellation of a task, useful for timeouts or user interruptionstask.done(): Checks if the task has finished without blockingtask.result(): Gets the return value (raises exception if not done)asyncio.wait_for(): Runs a coroutine with a timeout, cancelling if it takes too longasyncio.shield(): Protects a task from being cancelled by parent cancellationsasyncio.gather(): Runs multiple tasks concurrently and collects all resultsasyncio.wait(): Waits for tasks with fine-grained control (first_completed, all_completed)asyncio.as_completed(): Returns tasks as they complete, not waiting for alltask.add_done_callback(): Schedules a callback to run when task completesasyncio.current_task(): Gets the currently running taskasyncio.all_tasks(): Gets all tasks in the event loop
These methods give you precise control over task lifecycle, error handling, and coordination patterns.
The Event Loop: Behind the Scenes
The event loop is the central coordinator of all asynchronous operations in Python. Think of it as a ring master that keeps everything organized and running smoothly.
Get Shrish’s stories in your inbox
Join Medium for free to get updates from this writer.
What the Event Loop Does
The event loop handles three main jobs:
- Tracking Tasks: It keeps a list of all the coroutines and tasks that need to run.
- Deciding What Runs Next: When one task pauses, the event loop picks another one to continue.
- Managing I/O Operations: It watches for completed network requests, file operations, and other external processes.
How Tasks Take Turns
When a coroutine uses await, it's telling the event loop: "I need to wait for something, so I'll pause for now." The event loop then:
- Puts that coroutine on hold
- Makes note of what it’s waiting for
- Picks another coroutine that’s ready to run
This passing back and forth happens automatically, letting multiple operations make progress without wasting time.
The Loop’s Work Cycle
The event loop works in a continuous cycle:
- Check if any waiting operations (like network requests) have finished
- Run any coroutines that are now ready to continue
- Check for new tasks that need to be scheduled
- Repeat
This cycle happens very quickly, giving the impression that everything is running at once, even though Python is actually working on one thing at a time.
async def demonstrate_event_loop():
# This visual example shows how coroutines take turns
async def task1():
print("Task 1: Starting")
await asyncio.sleep(2) # Yields control back to event loop
print("Task 1: After 2 seconds")
await asyncio.sleep(1) # Yields control again
print("Task 1: Finished")
async def task2():
print("Task 2: Starting")
await asyncio.sleep(1) # Yields control back to event loop
print("Task 2: After 1 second")
await asyncio.sleep(2) # Yields control again
print("Task 2: Finished")
# Schedule both tasks to run concurrently
# try commenting this gather line and run the code
await asyncio.gather(task1(), task2())
import nest_asyncio
nest_asyncio.apply()
# Alternatively, you can use this pattern:
await demonstrate_event_loop() #
# Output will show tasks interleaving their execution:
# Task 1: Starting
# Task 2: Starting
# Task 2: After 1 second
# Task 1: After 2 seconds
# Task 2: Finished
# Task 1: FinishedA dummy demo example
Finally we are here to see the impact of async programming. This is what I was building up for.
The following code demonstrates an asynchronous workflow that mimics real-world scenarios in modern applications. It shows how to manage different types of I/O-bound operations (database writes, LLM API calls, and HTTP requests) using Python’s asyncio library. This example illustrates key concepts like dependent tasks (where we await results immediately) and background tasks (where we create tasks but don’t immediately wait for them). I will suggest you pull up one Jupyter notebook and copy these code snippets one by one in cells and run them to see for yourself.
import asyncio
import time
import random
# Store all events in a timeline for later analysis
async_timeline_events = []
# Keep track of background tasks we'll gather at the end
tasks = []
# Capture the start time to calculate relative timestamps
initial_timestamp = time.monotonic()
def log_event(timeline, task, event):
"""
Log an event with timestamp to visualize when operations start and end
You can simply ignore this this does not serve any pupose in the pipeline.
Args:
timeline: List to append the event to
task: Name/ID of the task
event: Description of what happened (e.g., START or END)
"""
timestamp = time.monotonic() - initial_timestamp # Calculate time since start
timeline.append({
"task": task,
"event": event,
"timestamp": timestamp,
})
print(f"[{timestamp:.2f}] {event}: {task}")
async def async_db_operation(step):
"""
Simulate a database write operation (like saving analytics or logs)
In real applications, this would be writing data to a database,
which is I/O-bound and benefits from asynchronous execution.
"""
task_id = f"log_{step}"
log_event(async_timeline_events, task_id, "START") # just logging time
# Simulate variable database operation time
await asyncio.sleep(random.uniform(0.3, 3.0))
log_event(async_timeline_events, task_id, "END") # just logging time
async def async_llm_call(prompt):
"""
Simulate a call to a Large Language Model API
In real applications, this would be a network request to an API like
OpenAI, Anthropic, or a self-hosted LLM service.
"""
task_id = f"llm_{prompt[:10]}"
log_event(async_timeline_events, task_id, "START") # just logging time
# LLM calls often take longer than other API calls
await asyncio.sleep(random.uniform(0.5, 3.2))
log_event(async_timeline_events, task_id, "END") # just logging time
return f"LLM result: {prompt}"
async def async_http_call(endpoint):
"""
Simulate an HTTP request to an external API
In real applications, this could be fetching data from a REST API,
microservice, or other web service.
"""
task_id = f"http_{endpoint.replace('/', '')}"
log_event(async_timeline_events, task_id, "START") # just logging time
# Simulate variable network latency
await asyncio.sleep(random.uniform(0.4, 4.0))
log_event(async_timeline_events, task_id, "END") # just logging time
return f"HTTP result from {endpoint}"
async def run_async_pipeline():
"""
Main workflow that coordinates the execution of different async operations
This demonstrates both:
1. Dependent tasks (using 'await') - where we need results immediately
2. Background tasks (using create_task) - where we can fire and forget
"""
log_event(async_timeline_events, "main_pipeline", "START_PIPELINE")
# DEPENDENT TASK: We need the LLM result before proceeding
llm_result = await async_llm_call("What's the user intent?")
# BACKGROUND TASK: Log the result to the database, but don't wait for it
tasks.append(asyncio.create_task(async_db_operation("llm_result")))
# DEPENDENT TASK: We need this HTTP result for our business logic
http1 = await async_http_call("/api/data")
# BACKGROUND TASK: Log this API call, but don't block on it
tasks.append(asyncio.create_task(async_db_operation("http1")))
# DEPENDENT TASK: We need this data too before proceeding
http2 = await async_http_call("/api/details")
# BACKGROUND TASK: Another non-blocking logging operation
tasks.append(asyncio.create_task(async_db_operation("http2")))
# DEPENDENT TASK: Generate a summary using the LLM with collected data
summary = await async_llm_call("Summarize everything")
# BACKGROUND TASK: Log the summary generation
tasks.append(asyncio.create_task(async_db_operation("summary")))
log_event(async_timeline_events, "main_pipeline", "END_PIPELINE")
# Wait for all background tasks to complete before exiting
# This ensures all logging operations finish properly
# This will run without gathering all tasks as well, you can try
await asyncio.gather(*tasks)
# Fix for running asyncio in environments like Jupyter notebooks
import nest_asyncio
nest_asyncio.apply()
# Reset the timer before starting
initial_timestamp = time.monotonic()
print("\n--- Running Async Pipeline ---\n")
# Run the main async workflow
asyncio.run(run_async_pipeline())
Output
--- Running Async Pipeline ---
[0.00] START_PIPELINE: main_pipeline
[0.00] START: llm_What's the
[0.94] END: llm_What's the
[0.94] START: http_apidata
[0.94] START: log_llm_result
[1.56] END: http_apidata
[1.56] START: http_apidetails
[1.56] START: log_http1
[1.89] END: log_llm_result
[3.04] END: log_http1
[3.38] END: http_apidetails
[3.38] START: llm_Summarize
[3.38] START: log_http2
[5.23] END: llm_Summarize
[5.23] END_PIPELINE: main_pipeline
[5.23] START: log_summary
[5.63] END: log_http2
[6.70] END: log_summaryThe same example with sync functions
This code demonstrates the traditional synchronous approach to handling I/O-bound operations like database writes, LLM API calls, and HTTP requests. In contrast to the asynchronous version we saw earlier, this code executes each operation sequentially, waiting for it to complete before moving to the next one. This pattern is simpler to understand but can lead to significant inefficiencies in I/O-bound applications.
# Timeline to track events for visualization and analysis
sync_timeline_events = []
# Capture start time for calculating relative timestamps
initial_timestamp = time.monotonic()
def sync_db_operation(step):
"""
Simulate a synchronous database write operation
In real applications, this would be writing data to a database,
but here we're blocking the entire program while it runs.
"""
task_id = f"log_{step}"
log_event(sync_timeline_events, task_id, "START")
# Block the entire program during this "database operation"
time.sleep(random.uniform(0.3, 3.0))
log_event(sync_timeline_events, task_id, "END")
def sync_llm_call(prompt):
"""
Simulate a synchronous call to a Large Language Model API
In real applications, this would be waiting for a response from
an AI service like OpenAI or Anthropic, completely blocking execution.
"""
task_id = f"llm_{prompt[:10]}"
log_event(sync_timeline_events, task_id, "START")
# Block the entire program during this "API call"
time.sleep(random.uniform(0.5, 3.2))
log_event(sync_timeline_events, task_id, "END")
return f"LLM result: {prompt}"
def sync_http_call(endpoint):
"""
Simulate a synchronous HTTP request to an external API
In real applications, this would be waiting for a network response,
with the program doing nothing else during this time.
"""
task_id = f"http_{endpoint.replace('/', '')}"
log_event(sync_timeline_events, task_id, "START")
# Block the entire program during this "network request"
time.sleep(random.uniform(0.4, 4.0))
log_event(sync_timeline_events, task_id, "END")
return f"HTTP result from {endpoint}"
def run_sync_pipeline():
"""
Main workflow that coordinates operations in a strictly sequential manner
Each operation completely blocks the program until it finishes,
resulting in poor resource utilization and longer total execution time.
"""
log_event(sync_timeline_events, "main_pipeline", "START_PIPELINE")
# Step 1: Make LLM call and wait for it to complete
llm_result = sync_llm_call("What's the user intent?")
# Step 2: Log the result and wait for logging to complete
sync_db_operation("llm_result")
# Step 3: Make first HTTP call and wait for it to complete
http1 = sync_http_call("/api/data")
# Step 4: Log the HTTP result and wait for logging to complete
sync_db_operation("http1")
# Step 5: Make second HTTP call and wait for it to complete
http2 = sync_http_call("/api/details")
# Step 6: Log the HTTP result and wait for logging to complete
sync_db_operation("http2")
# Step 7: Make final LLM call and wait for it to complete
summary = sync_llm_call("Summarize everything")
# Step 8: Log the summary and wait for logging to complete
sync_db_operation("summary")
log_event(sync_timeline_events, "main_pipeline", "END_PIPELINE")
# Reset the timer before starting
initial_timestamp = time.monotonic()
print("\n--- Running Sync Pipeline ---\n")
# Run the synchronous workflow
run_sync_pipeline()Output
--- Running Sync Pipeline ---
[0.00] START_PIPELINE: main_pipeline
[0.00] START: llm_What's the
[2.36] END: llm_What's the
[2.36] START: log_llm_result
[3.60] END: log_llm_result
[3.60] START: http_apidata
[5.55] END: http_apidata
[5.55] START: log_http1
[7.48] END: log_http1
[7.48] START: http_apidetails
[11.12] END: http_apidetails
[11.12] START: log_http2
[12.36] END: log_http2
[12.36] START: llm_Summarize
[13.72] END: llm_Summarize
[13.72] START: log_summary
[16.16] END: log_summary
[16.16] END_PIPELINE: main_pipelinePlotting results: to see is to belive
Following code will plot the timeline_events we have collected for both of our examples, generating one plot for sync and another for async execution. Looking closely at these visualizations will reveal a lot about the asyncio library and specifically the inner workings of the event loop.
import matplotlib.pyplot as plt
from collections import defaultdict
# Do not worry about this function, just think this give nice plot for event timelines
def plot_timeline(events, title):
task_labels = {
"main_pipeline": "Pipeline Start/End",
"llm_What's the": "LLM: Intent",
"log_llm_result": "Log: LLM result",
"http_apidata": "HTTP1: /api/data",
"log_http1": "Log: http1 result",
"http_apidetails": "HTTP2: /api/details",
"log_http2": "Log: http2 result",
"llm_Summarize ": "LLM: Summary",
"log_summary": "Log: final summary"
}
segments = defaultdict(lambda: {"start": None, "end": None})
task_order = []
seen = set()
for event in events:
task = event["task"]
if task not in seen:
seen.add(task)
task_order.append(task)
if event["event"] == "START" or event["event"] == "START_PIPELINE":
segments[task]["start"] = event["timestamp"]
elif event["event"] == "END" or event["event"] == "END_PIPELINE":
segments[task]["end"] = event["timestamp"]
segments_labeled = [(task_labels.get(task, task), seg) for task, seg in segments.items()]
segments_labeled = list(reversed(segments_labeled))
fig, ax = plt.subplots(figsize=(12, 6))
for i, (label, seg) in enumerate(segments_labeled):
start, end = seg["start"], seg["end"]
if start is not None and end is not None:
ax.hlines(i, start, end, colors="blue", linewidth=1)
ax.plot(start, i, "g>", markersize=5)
ax.plot(end, i, "r<", markersize=5)
ax.set_yticks(range(len(segments_labeled)))
ax.set_yticklabels([label for label, _ in segments_labeled])
ax.set_xlabel("Time (seconds)")
ax.set_title(title)
ax.grid(True)
plt.tight_layout()
plt.show()
plot_timeline(async_timeline_events, "Async Task Timeline")
plot_timeline(sync_timeline_events, "Sync Task Timeline")Async vs Sync: The Numbers Don’t Lie
Seeing the actual timing data makes all the difference in understanding why async programming matters. Looking at the execution logs, the results are crystal clear.
The async pipeline wrapped up everything in just 6.70 seconds, while the sync version dragged on for 16 seconds(some variation can come due to random numbers as well, but you get the point). And this is just a simple example — in real-world applications with dozens of API calls and database operations, this difference compounds dramatically.
What I want to point out is how operations overlap in the async timeline. Notice how at the 0.94s mark, the first LLM call finishes and immediately kicks off both an HTTP request and a database logging operation simultaneously. This efficient interleaving continues throughout the execution. Meanwhile, the sync version plods along one operation at a time, with the CPU sitting idle during all those I/O waits.
In our timeline visualization, you would see the async execution as a dense, efficient pattern with multiple operations stacked in parallel, while the sync version looks like a simple, stretched-out sequence with lots of wasted time.
The main pipeline itself (excluding some background tasks) finished in just 5.23 seconds with async, compared to 16 seconds for the sync approach.
Explore More Resources
Here are some additional insights and resources to take your understanding to the next level.
The Python asyncio ecosystem is rich and continuously evolving. To dive deeper:
The official asyncio documentation is surprisingly approachable and comprehensive. It covers everything from basic coroutines to more advanced patterns like queues, synchronization primitives, and subprocess management.
Real Python’s async guide offers one of the most practical, hands-on introductions you’ll find.
Limitations and Challenges
While async programming is powerful, it’s not without its challenges:
The “Async All the Way Down” Problem
One frustrating limitation is that you can’t mix synchronous and asynchronous code freely. Once you start using async, your entire call stack typically needs to support it. If you call a synchronous function that performs blocking I/O from an async function, you’ll block the entire event loop — defeating the purpose of using async in the first place.
async def get_user_data():
# This blocks the entire event loop despite being in an async function!
results = requests.get("https://api.example.com/users") # Blocking!
return results.json()Instead, you need to use async-compatible libraries:
async def get_user_data():
async with aiohttp.ClientSession() as session:
async with session.get("https://api.example.com/users") as response:
return await response.json()Thanks for your time. I hope this helped you develop an understanding of asynchronous programing with asyncio library.
If you enjoyed the article, I invite you to follow me for future content. Additionally, feel free to connect with me on LinkedIn.






