Browse Python Topics ▼
Pick a Web Framework

Asynchronous Programming with Asyncio

📂 Concurrency & Async 📘 Lesson 48 of 57

Build ultra-fast, event-driven asynchronous applications with Python's asyncio module, async and await keywords, coroutines, and the event loop.

Imagine walking into a busy coffee shop.

  • The Multi-Threaded Model: The shop hires 20 baristas. Each barista takes an order from one customer, turns around to press the espresso button, and stands completely frozen for 60 seconds waiting for the coffee to brew before serving the customer. Managing 20 baristas takes massive space and resources.
  • The Asynchronous Event Loop Model: One skilled barista works the counter. They take Customer 1’s order and press the espresso button. While that machine is brewing, the barista immediately turns to Customer 2 and takes their order. When Customer 1’s espresso finishes (an event!), the barista pours the cup and hands it over.

With a single thread, that one barista can handle hundreds of customers concurrently without wasting time waiting!

In Python, this architecture is called Asynchronous Programming, powered by the built-in asyncio module and the async / await keywords. It is the engine behind modern, high-performance web frameworks like FastAPI.


1. Coroutines: async def and await

To write asynchronous code in Python, you define a Coroutine using async def:

import asyncio

async def fetch_temperature():
    print("Connecting to weather satellite...")
    # Non-blocking pause: gives control back to the event loop!
    await asyncio.sleep(1.0)
    print("Received telemetry data.")
    return 72.5

The Beginner Trap: Calling a Coroutine Directly

Look at what happens if you call fetch_temperature() like a normal function:

# MISTAKE:
data = fetch_temperature()
print(data)
# Output: <coroutine object fetch_temperature at 0x7fa28409>
# RuntimeWarning: coroutine 'fetch_temperature' was never awaited!

Calling an async def function does not execute its body! It returns a coroutine object—a recipe ready to be executed on the event loop.

To actually execute a coroutine, you must either:

  1. await it inside another coroutine: data = await fetch_temperature()
  2. Run it as the main entry point with asyncio.run(): asyncio.run(fetch_temperature())

2. Launching the Event Loop with asyncio.run()

The Event Loop is the central scheduler that manages and distributes execution time between coroutines.

In Python 3.7+, the standard entry point to start the event loop is asyncio.run():

import asyncio

async def main():
    print("Welcome to the async engine!")
    await asyncio.sleep(0.5)
    print("Task finished.")

# Starts the event loop, runs main(), and closes the loop cleanly:
asyncio.run(main())

3. Running Concurrent Tasks with asyncio.gather()

The true power of asyncio is launching multiple I/O tasks simultaneously and collecting their results with asyncio.gather():

import asyncio
import time

async def fetch_api(service_name, delay):
    print(f"[{service_name}] Request dispatched...")
    await asyncio.sleep(delay)  # Non-blocking simulated network latency
    print(f"[{service_name}] Response ready!")
    return f"{service_name}: OK (200)"

async def main():
    start_time = time.perf_counter()
    
    # Run all three requests concurrently on the single thread!
    results = await asyncio.gather(
        fetch_api("AuthService", 0.5),
        fetch_api("BillingService", 0.3),
        fetch_api("AnalyticsService", 0.4)
    )
    
    elapsed = time.perf_counter() - start_time
    print(f"\nAll services responded in {elapsed:.2f} seconds!")
    print("Results:", results)

asyncio.run(main())

Output:

[AuthService] Request dispatched...
[BillingService] Request dispatched...
[AnalyticsService] Request dispatched...
[BillingService] Response ready!
[AnalyticsService] Response ready!
[AuthService] Response ready!

All services responded in 0.51 seconds!
Results: ['AuthService: OK (200)', 'BillingService: OK (200)', 'AnalyticsService: OK (200)']

Notice what happened:

  • If run sequentially, the three tasks would take $0.5 + 0.3 + 0.4 = 1.2$ seconds.
  • With asyncio.gather(), they all run concurrently and finish in 0.51 seconds (the time of the single slowest request)!
  • And notice the completion order: BillingService (0.3s) finished first, followed by AnalyticsService (0.4s), then AuthService (0.5s)!

4. The Cardinal Rule: NEVER Block the Event Loop!

Because asyncio executes on a single thread, you must never call blocking synchronous functions inside a coroutine:

# CATASTROPHIC ANTI-PATTERN:
async def bad_worker():
    import time
    time.sleep(5)  # DANGER: Freezes the entire operating system thread!

Why is time.sleep() disastrous in async code?

time.sleep() halts the physical CPU thread. Because asyncio only has that one thread, the entire event loop freezes! All thousands of other concurrent users connected to your web server will suddenly experience a 5-second freeze!

The Golden Rules:

  1. Use await asyncio.sleep() instead of time.sleep().
  2. Use async HTTP clients (like httpx or aiohttp) instead of synchronous requests.
  3. If you must run a third-party legacy blocking function, offload it to a thread using asyncio.to_thread(blocking_func):
    result = await asyncio.to_thread(legacy_blocking_function, arg1)

Summary & Stage 12 Capstone

Congratulations on completing Stage 12: Concurrency & Async! You now understand the full landscape of simultaneous programming in Python:

  1. Concurrency vs Parallelism, I/O vs CPU bottlenecks, and the CPython GIL.
  2. Thread pools and process pools with concurrent.futures.
  3. Single-threaded, event-driven coroutines with Asyncio and async/await.

Now that you can write complex, multi-tasking applications, how do you verify that your code actually works correctly and never breaks in production? Learn how to write bulletproof automated test suites in Stage 13, starting with pytest.

Test your understanding of Asynchronous Programming with Asyncio

Quick interactive practice questions with instant feedback.

Take Quiz →