Skip to main content

Python Async Runtimes & Structured Concurrency: Asyncio, Trio, AnyIO & Threading Masterclass

Total Questions: 20 Curriculum: Runtimes & Structured Concurrency (7), TaskGroups & Exception Handling (6), Threading Bridges & Production Triage (7)


Overview​

Python concurrency in 2026–2027 has evolved beyond raw callbacks and unstructured asyncio.create_task() calls. The modern ecosystem is centered on Structured Concurrency—ensuring that concurrent tasks have clear lifecycles, bounded lifespans, and deterministic cancellation. This masterclass compares asyncio, trio, anyio, and threading, providing real-world code, error recovery architectures, and execution flow diagrams.


Quick Comparison Matrix​

Feature / DimensionStandard asyncio (3.11+)trioanyiothreading
Concurrency PhilosophyCooperative event loop (historically unstructured, added TaskGroup in 3.11)Strict Structured Concurrency by design (Nurseries)Universal Structured Concurrency compatibility layerOS Kernel Pre-emptive Preemption (Thread per task)
Task Spawningasyncio.TaskGroup / create_tasknursery.start_soon()task_group.start_soon()threading.Thread.start()
Exception HandlingExceptionGroup + except* (3.11+)ExceptionGroup (MultiError legacy)ExceptionGroup + except*Unhandled exceptions crash thread only (silent loss unless joined)
Cancellation ReliabilityModerate (Tasks can swallow CancelledError)Extremely High (Checkpoints at every I/O point)Extremely High (Trio-grade semantics on both backends)Very Low (No native thread cancellation in Python)
Ecosystem & Library SupportMassive (Standard Library, aiohttp, asyncpg)Moderate (HTTPX, custom trio drivers)Massive (Powers FastAPI, Starlette, HTTPX)Universal (Works with all legacy blocking libraries)
When to UseStandard library purity, simple async scriptsSafety-critical async systems, deep cancellation needsModern web backends (FastAPI), writing dual-runtime async librariesBlocking C-extensions releasing GIL, CPU bound with C code, legacy I/O

Table of Contents​


Chapter 1: Runtimes & Structured Concurrency​

Q1: What is Structured Concurrency and why is asyncio.create_task() / asyncio.gather() considered hazardous?​

Level: Senior / Principal

Scenario: A background scraping service uses asyncio.create_task() to spawn 50 concurrent web scrapers inside an HTTP request handler. When the client disconnects or times out, the request handler exits, but all 50 scraper tasks continue running in the background indefinitely, consuming CPU and database connections.

Impact: Task leaks, memory exhaustion, zombie network requests, and unhandled exceptions that get logged hours later without request context.

Root Cause: Unstructured Concurrency (The "Go statement considered harmful" problem): asyncio.create_task() spawns a task onto the global event loop with zero lifecycle binding to the parent function scope. If the parent function exits or errors, child tasks become orphaned. Similarly, asyncio.gather() does not automatically cancel sibling tasks if one task fails, leaving background coroutines running in an indeterminate state.

Fix: Adopt Structured Concurrency using asyncio.TaskGroup (Python 3.11+), anyio.create_task_group(), or trio.open_nursery(). In structured concurrency:

  1. Child tasks are strictly scoped within an asynchronous context manager block.
  2. The parent block cannot exit until all child tasks have completed.
  3. If any child task raises an exception, the runtime automatically cancels all remaining sibling tasks in the group before propagating the error.

Code:

import asyncio

# UNSTRUCTURED (Anti-pattern: leaks tasks on parent failure)
async def bad_worker():
task1 = asyncio.create_task(fetch_data("A"))
task2 = asyncio.create_task(fetch_data("B"))
# If fetch_data("A") fails, task2 is NOT cancelled! It runs forever as a zombie!
return await task1, await task2

# STRUCTURED (Modern 3.11+ pattern: strict lifecycle bounding)
async def good_worker():
async with asyncio.TaskGroup() as tg:
t1 = tg.create_task(fetch_data("A"))
t2 = tg.create_task(fetch_data("B"))
# Context manager guarantees both tasks finished before exiting!
# If t1 fails, t2 is automatically cancelled!
return t1.result(), t2.result()

Workflow Diagram:

[Unstructured: create_task()]
Parent Function ──> Spawns Task 1 & Task 2 (Detached into global event loop)
│
(Parent exits on error) ──> Task 1 & Task 2 continue running as ZOMBIES!

[Structured Concurrency: TaskGroup / Nursery]
async with TaskGroup() as tg:
├── tg.create_task(Task 1)
└── tg.create_task(Task 2)
│
(If Task 1 raises Exception) ──> Automatically sends CancelledError to Task 2!
│
(All tasks guaranteed dead before context manager block unrolls!)

Interviewer Notes: Tests understanding of modern asynchronous language design (pioneered by Martin Sústrik and Nathaniel J. Smith in Trio, adopted into Python 3.11 and Java 21).

Red Flags:

  • Calling asyncio.create_task() in production without keeping a strong reference to the task or scoping it within a TaskGroup.

Q2: What is AnyIO and why do modern frameworks (FastAPI, Starlette, HTTPX) build on it instead of raw asyncio?​

Level: Senior / Principal

Technical Answer: AnyIO is an asynchronous networking and concurrency library that provides a unified, structured API on top of either asyncio or trio. Modern libraries use AnyIO because:

  1. Write-Once Compatibility: Library authors write async code once; users can run it on standard asyncio (default) or trio by toggling anyio.run(main, backend="trio").
  2. Superior Structured Concurrency: AnyIO provides Trio-grade structured concurrency semantics (TaskGroups, cancellation scopes) even when running on older or standard asyncio runtimes.
  3. Robust Thread Bridging: Provides safe, zero-leak utilities for offloading blocking code to worker threads (anyio.to_thread.run_sync()) and calling async functions from threads (anyio.from_thread.run()).

Code:

import anyio

async def fetch_item(item_id: int):
await anyio.sleep(0.1)
return f"Item {item_id}"

async def main():
# AnyIO TaskGroup works identically on asyncio or trio!
async with anyio.create_task_group() as tg:
for i in range(5):
tg.start_soon(fetch_item, i)

# Run on asyncio backend (default) or trio
anyio.run(main, backend="asyncio")

Behind the Question: Architectural understanding of the Python async ecosystem hierarchy.

Red Flags:

  • Thinking AnyIO is an alternative event loop implementation (it is an abstraction layer on top of asyncio/trio).

Q3: When should you choose Trio over Asyncio?​

Level: Principal

Technical Answer: Choose Trio when:

  1. Correctness and Determinism Outweigh Standard Library Purity: Trio enforces structured concurrency unconditionally—there is literally no create_task() in Trio. Every task must belong to a nursery.
  2. Rock-Solid Cancellation Semantics: In asyncio, a task can catch asyncio.CancelledError and ignore it, hanging the process. In Trio, cancellation is a permanent state enforced at every checkpoint (I/O operation); tasks cannot accidentally un-cancel themselves.
  3. Testing Complex Time and Concurrency: Trio includes a deterministic virtual clock (trio.testing.MockClock) allowing complex distributed timeout tests to run in milliseconds without real-world sleeping.

Trade-offs: Incompatible with standard library asyncio packages unless bridged through AnyIO; smaller third-party driver ecosystem.

Code:

import trio

async def child_task(name: str):
await trio.sleep(1)
print(f"Child {name} completed")

async def parent():
async with trio.open_nursery() as nursery:
nursery.start_soon(child_task, "Alpha")
nursery.start_soon(child_task, "Beta")
print("All nursery children completed!")

trio.run(parent)

Interviewer Notes: Tests awareness of async design flaws in early asyncio and how Trio redesigned them from first principles.

Red Flags:

  • Believing Trio is just another wrapper around asyncio (Trio has its own native event loop written from scratch).

Q4: When should you use Threading over Asyncio/AnyIO in Python?​

Level: Senior / Principal

Technical Answer: Use threading (or concurrent.futures.ThreadPoolExecutor) when:

  1. Third-Party Libraries are Synchronous and Blocking: Interfacing with legacy relational database drivers, SDKs, or filesystem libraries that do not provide async APIs.
  2. Operations Release the CPython GIL: CPU-intensive scientific operations (NumPy matrix multiplication, OpenCV image filters, PyTorch tensor math, or C-extensions) release the Global Interpreter Lock during computation, achieving true multi-core CPU parallelism across threads without multiprocessing IPC overhead.
  3. Low to Moderate Concurrency (< 500 connections): For simple background workers where the overhead of 1MB thread stacks is negligible and async/await syntax coloring complexity is unjustified.

Use Asyncio/AnyIO when:

  1. High-concurrency network I/O (10,000+ simultaneous WebSockets, chat servers, high-RPS microservices) where allocating 10,000 OS threads would exhaust kernel memory and CPU context switching budgets.

Code:

# Threading is optimal when the underlying library releases the GIL!
import threading
import numpy as np

def compute_heavy_matrix(size: int):
# NumPy C-extension releases the GIL! Runs in true parallel on multiple CPU cores!
a = np.random.rand(size, size)
b = np.random.rand(size, size)
return np.dot(a, b)

threads = [threading.Thread(target=compute_heavy_matrix, args=(2000,)) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()

Interviewer Notes: Senior engineers must know that Python threads DO achieve true multi-core parallelism when executing C-extensions that release the GIL.

Red Flags:

  • Saying Python threads are completely useless because of the GIL (they are great for I/O and GIL-releasing C libraries).

Q5: How do Cancellation Semantics differ between Asyncio and AnyIO/Trio?​

Level: Senior / Principal

Scenario: An API timeout cancels an in-flight background export task in asyncio. The task has a broad except Exception: block that catches the cancellation and continues running, ignoring the timeout.

Impact: Timeouts fail to terminate runaway tasks, causing resource leaks.

Root Cause: In Python 3.7 and earlier, asyncio.CancelledError inherited from Exception, meaning generic except Exception: caught it accidentally. In Python 3.8+, CancelledError inherits from BaseException. However, a task can still catch it and fail to re-raise. Furthermore, in raw asyncio, performing another await inside the cleanup block can raise another cancellation immediately.

Fix: In AnyIO and Trio, cancellation scopes provide an explicit shield=True context manager to allow clean async cleanup without being interrupted:

Code:

import anyio

async def worker():
try:
await anyio.sleep(10)
except anyio.get_cancelled_exc_class():
# Clean asynchronous cleanup protected by shield
with anyio.CancelScope(shield=True):
print("Cleaning up database connection safely...")
await anyio.sleep(0.1) # Protected: will NOT be interrupted!
raise # Re-raise cancellation cleanly

Workflow Diagram:

[Cancellation Signal Received]
│
▼
[Raises CancelledError]
│
├── (Unshielded await) ──> Immediately interrupted again! (Broken cleanup)
│
└── (Shielded Scope) ────> Guaranteed completion of cleanup before exit!

Interviewer Notes: Tests deep knowledge of async cancellation subtleties and graceful resource cleanup.

Red Flags:

  • Catching BaseException and swallowing it without re-raising.

Q6: How does asyncio.timeout() in Python 3.11+ replace asyncio.wait_for()?​

Level: Medium

Technical Answer: Prior to Python 3.11, asyncio.wait_for(coro, timeout) was used. It suffered from cancellation race conditions and poor composability. Python 3.11 introduced asyncio.timeout(delay) (an asynchronous context manager inspired by AnyIO/Trio fail_after). It creates a scoped timeout block that cleanly cancels in-flight work when the deadline expires and can be dynamically rescheduled via timeout.reschedule().

Code:

import asyncio

async def fetch_with_deadline():
try:
# Python 3.11+ scoped timeout
async with asyncio.timeout(2.0) as cm:
await asyncio.sleep(1.0)
# Can extend deadline dynamically if needed:
# cm.reschedule(asyncio.get_running_loop().time() + 5.0)
return "Success"
except TimeoutError:
print("Operation exceeded 2-second deadline!")

Behind the Question: Modern Python 3.11+ standard library async idioms.

Red Flags:

  • Using asyncio.wait_for() in new Python 3.11+ codebases.

Q7: What is the Memory Footprint comparison: OS Thread vs Python Coroutine?​

Level: Senior

Technical Answer:

  • OS Thread (threading.Thread): Allocates a native OS virtual memory stack (typically 2MB to 8MB in Linux/macOS) plus Python's internal thread state object (~16KB). 1,000 idle threads consume 2 GB to 8 GB of virtual memory and trigger high kernel scheduler context-switch overhead.
  • Python Coroutine (asyncio / anyio): A generator-like Python object on the heap consuming only ~500 bytes to 1.5 KB of RAM. 100,000 idle coroutines consume only ~100 MB of RAM.

Workflow Diagram:

[10,000 OS Threads] ──> Requires 20 GB - 80 GB Virtual RAM! (System crashes)
[10,000 Coroutines] ──> Requires ~15 MB RAM total! (Single process, smooth)

Behind the Question: Hardware resource scaling and why async is used for I/O density.

Red Flags:

  • Claiming async is faster for single-threaded CPU calculation (async adds coroutine frame overhead; it is for I/O density, not raw computation speed).

Chapter 2: TaskGroups & Exception Handling​

Q8: How does Exception Handling work in TaskGroup using Python 3.11+ ExceptionGroup and except*?​

Level: Senior / Principal

Scenario: Inside a TaskGroup, two child tasks fail concurrently: Task 1 raises ValueError("Invalid ID") and Task 2 raises ConnectionError("Database down"). A standard try / except ValueError: block fails to catch the error, crashing the process.

Impact: Uncaught exceptions and crash of the parent service.

Root Cause: Because multiple tasks run concurrently inside a TaskGroup, multiple exceptions can occur simultaneously. Python cannot raise two distinct exceptions with traditional except. Python 3.11 introduced ExceptionGroup, which bundles multiple exceptions together. Traditional except ValueError does not match an ExceptionGroup.

Fix: Use Python 3.11's new except* syntax (except-star), which unwraps and matches individual exception types within the ExceptionGroup.

Code:

import asyncio

async def fail_value():
await asyncio.sleep(0.01)
raise ValueError("Invalid configuration parameter")

async def fail_network():
await asyncio.sleep(0.02)
raise ConnectionError("Payment gateway timed out")

async def main():
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(fail_value())
tg.create_task(fail_network())
# Python 3.11+ except* unbundles and handles both errors concurrently!
except* ValueError as eg:
for err in eg.exceptions:
print(f"Handled ValueError: {err}")
except* ConnectionError as eg:
for err in eg.exceptions:
print(f"Handled ConnectionError: {err}")

asyncio.run(main())

Workflow Diagram:

[TaskGroup Execution]
├── Task 1 raises: ValueError
└── Task 2 raises: ConnectionError
│
▼
[Bundled into ExceptionGroup("unhandled errors in a TaskGroup", [ValueError, ConnectionError])]
│
┌─────────┴─────────┐
▼ ▼
except* ValueError except* ConnectionError
(Matches Task 1) (Matches Task 2)

Interviewer Notes: Tests understanding of Python 3.11's flagship concurrency and error handling feature.

Red Flags:

  • Using bare except Exception: on a TaskGroup block without understanding ExceptionGroup.

Q9: What happens when one task in an asyncio.TaskGroup raises an exception?​

Level: Senior

Technical Answer: When the first task in a TaskGroup raises an exception:

  1. The TaskGroup catches the exception internally.
  2. It immediately issues a cancellation request (task.cancel()) to all other active sibling tasks in the group.
  3. The TaskGroup waits for all sibling tasks to complete or handle their cancellation.
  4. Once all tasks have finished, all raised exceptions are collected into an ExceptionGroup and raised out of the context manager block.

Behind the Question: Understanding the failure cascade and cleanup guarantees of TaskGroups.

Red Flags:

  • Thinking sibling tasks are killed instantly without executing their finally blocks.

Q10: How does anyio.create_task_group() differ from asyncio.TaskGroup()?​

Level: Medium

Technical Answer:

  1. API: anyio uses tg.start_soon(func, arg1, arg2) taking a callable and arguments; asyncio.TaskGroup uses tg.create_task(coro()) taking an already-instantiated coroutine.
  2. Readiness Await: AnyIO provides tg.start(func) which blocks the parent until the child task signals it is initialized and ready (via task_status.started()).
  3. Backend Agnostic: AnyIO TaskGroup works seamlessly on both asyncio and trio.

Code:

import anyio

async def server_worker(task_status=anyio.TASK_STATUS_IGNORED):
# Setup listener...
task_status.started() # Signals parent that server is listening!
await anyio.sleep(10)

async def main():
async with anyio.create_task_group() as tg:
# Parent waits until server_worker calls task_status.started()!
await tg.start(server_worker)
print("Server is officially ready to accept connections!")

anyio.run(main)

Behind the Question: Knowing how to synchronize task startup readiness in microservices.

Red Flags:

  • Using asyncio.sleep(0.5) to guess when a child background task has finished starting up.

Q11: How to collect return values from tasks in an asyncio.TaskGroup?​

Level: Medium

Technical Answer: Unlike asyncio.gather(), TaskGroup does not return a list of values from the context manager. You must either inspect task.result() on the task handles after the context manager exits, or append results to a shared collection.

Code:

import asyncio

async def compute(x: int) -> int:
await asyncio.sleep(0.01)
return x * 10

async def main():
async with asyncio.TaskGroup() as tg:
t1 = tg.create_task(compute(1))
t2 = tg.create_task(compute(2))

# Safe to read .result() AFTER context manager exits!
print("Results:", t1.result(), t2.result()) # 10, 20

asyncio.run(main())

Behind the Question: Practical API mechanics of asyncio.TaskGroup.

Red Flags:

  • Calling t1.result() inside the TaskGroup context manager before the tasks finish.

Q12: How to implement a bounded concurrency worker pool with anyio.CapacityLimiter?​

Level: Senior

Scenario: A service needs to process 1,000 URLs concurrently, but must never open more than 10 simultaneous HTTP connections to prevent overwhelming the target host.

Impact: Target server rate-limiting, 429 Too Many Requests, and socket starvation.

Root Cause: Spawning 1,000 tasks inside a TaskGroup without a concurrency limiter.

Fix: Use anyio.CapacityLimiter(10) or asyncio.Semaphore(10).

Code:

import anyio

async def worker(item_id: int, limiter: anyio.CapacityLimiter):
async with limiter:
# At most 10 tasks execute this block simultaneously!
await anyio.sleep(0.1)
print(f"Finished {item_id}")

async def main():
limiter = anyio.CapacityLimiter(10) # Bound to 10 concurrent slots
async with anyio.create_task_group() as tg:
for i in range(100):
tg.start_soon(worker, i, limiter)

anyio.run(main)

Behind the Question: Bounded concurrency patterns and rate-limiting.

Red Flags:

  • Spawning unbounded coroutines and assuming the OS will handle thousands of open sockets.

Q13: Can you dynamically add tasks to a TaskGroup from inside a child task?​

Level: Senior

Technical Answer: Yes. If you pass the TaskGroup handle tg into the child coroutine, the child can call tg.create_task(...) or tg.start_soon(...). The parent context manager will automatically remain open until all dynamically spawned child and grandchild tasks complete.

Code:

import asyncio

async def recursive_crawler(url: str, depth: int, tg: asyncio.TaskGroup):
if depth <= 0: return
# Dynamically spawn sub-crawler in the same TaskGroup!
tg.create_task(recursive_crawler(f"{url}/child", depth - 1, tg))

async def main():
async with asyncio.TaskGroup() as tg:
tg.create_task(recursive_crawler("https://site.com", 3, tg))

Behind the Question: Dynamic DAG task generation and crawler architectures.

Red Flags:

  • Spawning independent create_task() calls inside children instead of binding to the parent group.

Chapter 3: Threading Bridges & Production Systems Triage​

Q14: How to safely call Blocking Synchronous Code from Asyncio/AnyIO without blocking the Event Loop?​

Level: Senior / Principal

Scenario: A FastAPI endpoint calls a legacy synchronous SDK time.sleep(2) or queries SQLite using a blocking driver. During the 2-second call, all other incoming HTTP requests freeze.

Impact: Event loop starvation: high latency and inability to process concurrent requests.

Root Cause: Executing blocking I/O directly on the single-threaded async event loop thread.

Fix: Offload the blocking synchronous function to a worker thread using anyio.to_thread.run_sync() or asyncio.to_thread(). This executes the function in a thread pool and yields the event loop until the thread completes.

Code:

import asyncio
import anyio
import time

def blocking_legacy_calculation(x: int) -> int:
time.sleep(1.0) # Blocking sync call!
return x * 2

# Standard asyncio (Python 3.9+)
async def run_with_asyncio():
result = await asyncio.to_thread(blocking_legacy_calculation, 21)
return result

# Universal AnyIO (Cancels and context-propagates cleanly)
async def run_with_anyio():
result = await anyio.to_thread.run_sync(blocking_legacy_calculation, 21)
return result

Workflow Diagram:

[Event Loop Thread] ──(Calls blocking code directly)──> Loop Freezes for 1s! (Bad)

[With anyio.to_thread.run_sync()]
Event Loop Thread ──(Delegates to Worker Thread)──> Continues processing other web requests!
│
[Worker Thread in Pool] (Executes blocking call)
│
Event Loop Thread <──(Notified on completion)─────┘

Interviewer Notes: Essential integration pattern in FastAPI and async web backends.

Red Flags:

  • Calling run_in_executor() with manual thread pools when asyncio.to_thread() exists in modern Python.

Q15: How to call Asynchronous Code from a Background Worker Thread?​

Level: Senior / Principal

Scenario: A legacy desktop GUI or Celery worker running on an OS thread needs to invoke an asynchronous library function and retrieve its result synchronously.

Impact: RuntimeError: There is no current event loop in thread or deadlocks.

Root Cause: Attempting to call asyncio.run() on an active loop, or creating competing unmanaged event loops in worker threads.

Fix: Use anyio.from_thread.run() or asyncio.run_coroutine_threadsafe().

Code:

import anyio

async def async_database_query(user_id: int) -> dict:
await anyio.sleep(0.05)
return {"id": user_id, "name": "Alice"}

def background_thread_worker():
# Called from a synchronous OS thread: blocks thread and awaits async function!
user = anyio.from_thread.run(async_database_query, 42)
print("User fetched from thread:", user)

Behind the Question: Bidirectional bridging between synchronous and asynchronous architectures.

Red Flags:

  • Instantiating a new event loop on every thread call (asyncio.new_event_loop()).

Q16: What is a Coroutine Race Condition and how does it differ from a Thread Race Condition?​

Level: Principal

Technical Answer:

  • Thread Race Condition: Occurs because the OS kernel can preempt a thread at any arbitrary CPU assembly instruction. Even count += 1 is not thread-safe without a lock.
  • Coroutine Race Condition: Coroutines run cooperatively on a single thread and can never be interrupted between await expressions. Code between two await points is guaranteed to execute atomically. However, race conditions still occur across await points if shared state changes while a coroutine yields control.

Code:

import asyncio

# Atomic: Zero await keywords between read and write! Safe in asyncio!
# (NOT safe in multi-threaded Python without a lock!)
counter = 0
async def safe_inc():
global counter
counter += 1

# Race Condition: Yield point (await) allows other coroutines to mutate state!
balance = 100
async def unsafe_withdraw(amount: int):
global balance
if balance >= amount:
await asyncio.sleep(0.01) # YIELD POINT! Another coroutine runs!
balance -= amount # Balance can become negative!

Workflow Diagram:

[Thread Race]: OS preempts anywhere (even mid-instruction!)
[Coroutine Race]: Switch occurs ONLY at explicit 'await' keywords!

Interviewer Notes: High-level concurrency theory question. Candidate must articulate that single-threaded async eliminates assembly-level data races but does NOT eliminate logical interleaving race conditions.

Red Flags:

  • Thinking async code is immune to race conditions and never needs asyncio.Lock.

Q17: Why does aiofiles use Thread Pools under the hood for asynchronous disk I/O?​

Level: Senior

Technical Answer: Standard operating systems (Linux, macOS, Windows) historically do not support true non-blocking file system I/O through standard socket selectors (epoll / kqueue). Disk reads and writes can block the calling thread on filesystem cache misses and page faults. Consequently, aiofiles and anyio.Path delegate file operations to worker threads in a thread pool under the hood. (Modern Linux io_uring provides native async file I/O, but is not yet the default standard in CPython).

Behind the Question: Systems internals and operating system limitations regarding disk vs network I/O.

Red Flags:

  • Assuming file I/O uses epoll non-blocking sockets like network TCP connections.

Q18: What is uvloop and how does it optimize standard asyncio performance?​

Level: Medium / Senior

Technical Answer: uvloop is a drop-in C-extension replacement for the standard Python asyncio event loop. Written in Cython and built directly on top of libuv (the same high-performance C networking engine powering Node.js), uvloop reduces Python event loop overhead and speeds up network throughput by 2x to 4x. Frameworks like Sanic, Uvicorn, and FastAPI automatically use uvloop when available.

Code:

import asyncio
import uvloop

# Enable uvloop as global event loop policy
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

async def main():
print("Running with ultra-fast C-based libuv event loop!")

asyncio.run(main())

Behind the Question: Performance optimization in production Python API deployments.

Red Flags:

  • Modifying business code to use uvloop (it requires zero code changes; it is a drop-in event loop policy).

Q19: Deadlock Triage: Circular Dependency across Channels in Structured Nurseries​

Level: Senior / Principal

Scenario: An ETL pipeline runs two tasks inside an AnyIO task group communicating via memory object streams (anyio.create_memory_object_stream(1)). Both tasks block forever, and the task group never exits.

Impact: Application freeze and memory leak.

Root Cause: Task 1 sends to stream A and waits to receive from stream B; Task 2 sends to stream B and waits to receive from stream A. Because stream buffers were full, both coroutines blocked on their respective send() calls, creating a circular channel deadlock.

Fix: Ensure consistent channel ordering or use asynchronous worker pools with unbounded buffers, or select between send/receive operations.

Interviewer Notes: Tests distributed concurrency communication and deadlock diagnosis.

Red Flags:

  • Assuming structured concurrency automatically prevents communication deadlocks.

Q20: Architecture Decision Record (ADR): Choosing between Asyncio, AnyIO, and Threading for 2026–2027 Python Backends​

Level: Principal

Technical Answer:

  • Default to AnyIO for New Web Services & Libraries: When building with FastAPI, Starlette, or creating reusable open-source packages. You get Trio's strict structured concurrency safety and clean cancellation scopes while remaining 100% compatible with the standard asyncio ecosystem.
  • Use Standard asyncio + TaskGroup (Python 3.11+): When strict standard-library-only zero-external-dependency constraints apply (e.g. AWS Lambda lightweight functions or standard CLI tools).
  • Use threading / ProcessPoolExecutor: When dealing with CPU-bound number crunching (NumPy, PyTorch, image rendering) or integrating synchronous legacy C-libraries.
  • Avoid: Unstructured concurrency (asyncio.create_task(), asyncio.gather()) without lifecycle bounding.

Behind the Question: Evaluates architectural governance and pragmatic decision-making.

Red Flags:

  • Recommending threading for 50,000 concurrent WebSockets.