Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Business framing: Async programming lets services handle many IO-bound tasks (requests, DB calls, websockets) efficiently. This notebook introduces asyncio fundamentals, a Pyodide-safe event-loop demo, when to choose async vs threads, and safe patterns for idempotency and cancellation.


Learning objectives

  • Understand event loop, coroutine, task, and await.

  • Compare async (single-threaded concurrency) vs thread pools for IO-bound work.

  • Write simple asyncio code that is deterministic and safe to run in-browser.


Pyodide-safe asyncio demo (deterministic)


Visual intuition: event loop vs thread pool

Caption: Async uses a single event loop to multiplex coroutines; threads use OS threads for parallel blocking IO.


MCQ

  • Q: For a high-concurrency web client that performs many short HTTP requests, which model usually gives the best throughput with lowest overhead?

    • A) Multiprocessing

    • B) Thread pool

    • C) Asyncio

    • (Answer: C)

Exercises

  1. Modify simulated_io to sometimes raise a recoverable exception; add a retry wrapper using asyncio.sleep between retries.

  2. Implement a simple cancellation test: start a long-running coroutine and cancel it after a short timeout, observing cleanup behavior.

  3. (Stretch) Compare asyncio vs ThreadPoolExecutor on a simulated blocking function by measuring elapsed time for N tasks.