Written for Python 3.14 and 3.15. Versions checked November 30, 2026: Python 3.15.2 and 3.14.10 are current, and APIs and deprecations match the Python 3.15 asyncio documentation.
Your API gateway fans out to five downstream services on every request, and it has handled load fine for months. Then a pull request adds a synchronous database call inside one async handler. p99 latency jumps for every request on that worker, because one blocking call holds up the single thread every request shares, and nothing in the logs says why.
That is the trade most teams sign up for when they adopt asyncio or inherit a service that already uses it. Some workloads get much cheaper to run, and some get slower in ways that are hard to spot in review.
Python async pays off when your service spends most of its time waiting on the network and every library in the request path is async-native. It hurts when handlers do heavy CPU work or call synchronous libraries directly, and most production pain with async Python comes from crossing that line without noticing.
Python async at a glance
asyncio runs many I/O-bound operations concurrently in one thread by switching tasks whenever one awaits, and it doesn’t make CPU-bound code any faster. This table shows where the main pieces stand in November 2026.
| Item | Status in November 2026 | Source |
|---|---|---|
| Latest Python | 3.15.2 (October 25, 2026); 3.15.0 shipped October 9, 2026. Latest 3.14 bugfix is 3.14.10 (October 25, 2026) | Python downloads |
| asyncio.TaskGroup | Available since 3.11; recommended over gather() for related tasks | Coroutines and tasks: TaskGroup |
| asyncio.timeout() | Available since 3.11 | Coroutines and tasks: timeouts |
| TaskGroup.cancel() | New in 3.15 | What’s new in Python 3.15 |
| python -m asyncio ps and pstree | New in 3.14; –retries N added in 3.15 | Command-line introspection tools |
| get_event_loop() with no current loop | Raises RuntimeError since 3.14 | Event loop docs |
| asyncio policy system | Deprecated in 3.14; removal scheduled for 3.16, not yet removed | Pending removal in Python 3.16 |
| Free-threaded build | Supported but optional; not the default | PEP 779 |
How Python async await runs your code
asyncio runs your coroutines on one event loop in one thread, and it switches to another task only when the current one reaches an await. That single rule explains why async services handle thousands of idle connections and why one bad call can freeze them all.
What async def, await, and asyncio.run() do
The async and await keywords came from PEP 492 in Python 3.5. Calling an async def function doesn’t run its body. It returns a coroutine object, and nothing happens until you await that coroutine or schedule it.
await pauses the current coroutine until the awaited object finishes. The coroutines and tasks docs list three main types of awaitable objects: coroutines, tasks, and futures. While a coroutine sits paused on an await, the event loop runs something else, so every task has to give up control voluntarily at its awaits.
asyncio.run() is the entry point. It creates the event loop, runs your top-level coroutine, finalizes async generators, and closes the default executor (giving it 5 minutes to shut down). Call it once per program. It can’t run while another event loop is running in the same thread.
How the event loop schedules coroutines and tasks
A coroutine runs only when something awaits it. A task is a coroutine that the event loop has scheduled to run on its own. You create one with asyncio.create_task() or, better, inside a task group. Tasks are how you get concurrency, because several can be waiting at the same time.
This sample runs three simulated downstream calls inside a TaskGroup:
import asyncio
import time
async def call_service(name: str, delay: float) -> str:
await asyncio.sleep(delay) # stands in for a network call
return f"{name} done"
async def main() -> None:
start = time.perf_counter()
async with asyncio.TaskGroup() as tg:
users = tg.create_task(call_service("users", 0.3))
orders = tg.create_task(call_service("orders", 0.5))
prices = tg.create_task(call_service("prices", 0.2))
print(users.result(), orders.result(), prices.result())
print(f"elapsed: {time.perf_counter() - start:.2f}s")
asyncio.run(main())
Run it and time it yourself. The elapsed time should land close to the longest call, not the sum of all three. Then swap the task group for three sequential await call_service(…) lines and compare.
Why a blocking call stalls other requests
The event loop runs every callback and task in its one thread. While a task is running, no other task can run in that thread. The asyncio developer guide gives a plain example: if a function does 1 second of CPU-intensive work, every concurrent task and I/O operation is delayed by 1 second.
A blocking call is anything that holds the thread without reaching an await. Common ones in production code:
- Synchronous HTTP clients and database drivers called from an async def handler
- time.sleep() where you meant await asyncio.sleep()
- Parsing a large JSON payload in the request path
- File reads and writes in hot paths
- Image resizing, compression, or any tight Python loop
None of these raise an error. Each one slows every other request on that worker, which is why they slip through code review.
When asyncio helps and when it hurts
asyncio helps workloads where most of each request is spent waiting on network I/O and very little is spent computing. If your profiler shows the process idle on sockets most of the time, you’re in the right place.
The wider choice between threads, processes, and asyncio, including how the GIL and the free-threaded build change it, is covered in choosing between threads, processes, and asyncio in our GIL article. This section stays on the asyncio side of that decision: which services should be async, and what to do with the parts that shouldn’t.
Concurrent network calls, database queries, and model APIs
These workloads fit the model well:
- API gateways and backends-for-frontends that fan out to several internal services per request
- Crawlers and webhook senders that keep many HTTP requests in flight
- WebSocket and long-poll servers holding many mostly idle connections
- Queue consumers that call external APIs for each message
- Services that call LLM APIs, where each request spends most of its time waiting on the model’s response
Three conditions have to hold for the payoff to show up:
- Every I/O library in the request path is async-native. Check whether your database driver and HTTP client offer an async API.
- Concurrency per process is high, meaning many requests are waiting at once.
- CPU work per request is small.
If any of these fail, threads or plain synchronous code will likely serve you better.
Where CPU work and synchronous dependencies cause trouble
CPU-bound work (image processing, heavy parsing, model inference written in Python) doesn’t get any faster under asyncio, and it stalls every other request on the loop. Send that work to a ProcessPoolExecutor, which uses multiprocessing to side-step the GIL. Only picklable objects can cross the process boundary.
On Linux, Python 3.14 changed the pool’s default start method from fork to forkserver, so workers no longer inherit module-level state from the parent. Our what’s new in Python 3.14 article covers what that breaks, and the GIL article covers InterpreterPoolExecutor as the in-process alternative.
A codebase built mostly on synchronous libraries has a different problem. Every call needs a thread wrapper, so you take on async complexity and still do the waiting in threads.
There’s also the “function color” cost. Async functions can only be awaited from async code, so async def spreads up your call stacks. Your team pays for it in test fixtures, tracing setup, and onboarding time for engineers new to the model.
| Workload | asyncio | Threads | Processes | Recommendation |
|---|---|---|---|---|
| Many concurrent network calls | Strong fit | Works, one thread per waiting call | More overhead than the work needs | Use asyncio |
| A few blocking library calls in an async service | Wrap the calls | Run them via to_thread() | Not needed | asyncio plus to_thread() |
| CPU-heavy request handling | Stalls the loop | Limited by the GIL | Strong fit | Use processes |
| Mixed service with a small CPU hot path | Fine for the I/O part | Not for the CPU part | For the hot path | asyncio plus a process pool |
| Batch job with little concurrency | Extra complexity | Simple enough | Only if CPU-bound | Plain synchronous code |
Low-concurrency internal tools, scripts, and admin jobs belong in that last row. Don’t make them async to match the rest of the codebase.
When to use asyncio.to_thread() or an executor
Wrap a blocking I/O call in asyncio.to_thread() so the event loop keeps serving other requests. Because of the GIL, it’s useful mainly for I/O-bound functions. It can help CPU-bound ones only with extension modules that release the GIL, or with Python implementations that don’t have one.
import asyncio
import time
def legacy_lookup(key: str) -> str:
time.sleep(0.2) # blocking call from a synchronous library
return key.upper()
async def handler(key: str) -> str:
return await asyncio.to_thread(legacy_lookup, key)
async def main() -> None:
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(handler(k)) for k in ("a", "b", "c")]
print([t.result() for t in tasks])
asyncio.run(main())
Watch the shared pool. loop.run_in_executor() with executor=None uses a lazily created ThreadPoolExecutor, and loop.getaddrinfo() uses that same pool for DNS lookups. When it’s saturated, those lookups get delayed, and your HTTP client may report the delay as timeouts.
Give heavier blocking work its own executor:
import asyncio
from concurrent.futures import ThreadPoolExecutor
pool = ThreadPoolExecutor(max_workers=8)
def export_report(path: str) -> str:
return f"wrote {path}" # stands in for slow, blocking file work
async def main() -> None:
loop = asyncio.get_running_loop()
result = await loop.run_in_executor(pool, export_report, "report.csv")
print(result)
asyncio.run(main())
Python asyncio best practices for structuring concurrent tasks
Structure related concurrent work inside a task group, keep a reference to every task you create outside one, and treat cancellation as normal control flow. These three habits prevent most leaked-task and silent-failure bugs in async services.
Use TaskGroup for related work and failure cleanup
asyncio.TaskGroup, added in Python 3.11, awaits all its tasks when the block exits. The first time a task fails with anything other than CancelledError, the group cancels the remaining tasks and refuses new ones. All failures come back together in an ExceptionGroup, which you handle with except* from PEP 654.
import asyncio
async def fetch(name: str, delay: float, fail: bool = False) -> str:
await asyncio.sleep(delay)
if fail:
raise ConnectionError(f"{name} unreachable")
return name
async def main() -> None:
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(fetch("inventory", 0.1, fail=True))
tg.create_task(fetch("pricing", 1.0))
except* ConnectionError as eg:
for exc in eg.exceptions:
print("failed:", exc)
asyncio.run(main())
The pricing call gets canceled as soon as inventory fails, so you don’t pay for work whose result you’d throw away.
Know when asyncio.gather() leaves tasks running
With the default return_exceptions=False, asyncio.gather() passes the first exception to the caller, and the other awaitables keep running. Your handler returns an error while background calls keep hitting downstream services.
With return_exceptions=True, exceptions land in the result list and nothing gets canceled either. The docs say TaskGroup gives stronger safety guarantees because it cancels the rest on failure. Keep gather() for cases where you want every result regardless of failures, and you’re fine with all calls finishing.
Keep references to independently created tasks
The event loop holds only weak references to tasks. If you call asyncio.create_task() and drop the result, the task can be garbage collected before it finishes. For fire-and-forget work, store tasks in a set and remove them when they finish:
import asyncio
from collections.abc import Coroutine
background_tasks: set[asyncio.Task] = set()
def fire_and_forget(coro: Coroutine) -> None:
task = asyncio.create_task(coro)
background_tasks.add(task)
task.add_done_callback(background_tasks.discard)
Use this for work like audit logging or metrics flushes, where the request shouldn’t wait. If you type helpers like this across a large codebase, the callback patterns in our Python type hints guide show how to annotate functions that return coroutines with Awaitable.
Treat cancellation as part of the control flow
Cancellation raises asyncio.CancelledError at the task’s current await. Timeouts, task group failures, and shutdown all use it. If you catch it, re-raise it. Put cleanup in try/finally so it runs no matter why the task stopped.
import asyncio
async def worker() -> None:
print("worker: opened connection")
try:
while True:
await asyncio.sleep(1) # waits on the network
finally:
print("worker: closing connection")
async def main() -> None:
try:
async with asyncio.timeout(0.1):
await worker()
except TimeoutError:
print("main: gave up on worker")
asyncio.run(main())
On Ctrl-C, asyncio.run() cancels the main task, so your finally blocks run before KeyboardInterrupt is raised. asyncio.shield() protects an inner awaitable from cancellation, but the caller is still canceled, and its await still raises CancelledError. Don’t expect it to keep a handler alive.
Keep async at the edges
Keep domain logic (pricing rules, validation, data transforms) in plain synchronous functions when it does no I/O, and keep async in the layer that talks to the network: handlers, clients, and repositories.
Synchronous functions are easier to test and can be called from both sides. Don’t wrap a synchronous library call in an async def function and assume that makes it non-blocking, because the call still holds the event loop.
Where AnyIO fits if you run FastAPI
If your services run on FastAPI, you’re already running on AnyIO. The FastAPI docs say Starlette and FastAPI are based on AnyIO, which makes them compatible with both asyncio and Trio, and that you can use AnyIO directly for more advanced concurrency patterns in your own code.
That matters most for sync endpoints. When a path operation is declared with plain def, FastAPI runs it in an external threadpool and awaits it. Starlette’s threadpool docs say that pool goes through anyio.to_thread.run_sync and is capped at 40 tokens, so only 40 sync endpoints, sync dependencies, and sync background tasks can run at once across the process. Under load, the 41st concurrent sync call waits for a token even while the event loop sits idle. You can raise the limit through anyio.to_thread.current_default_thread_limiter(), and Starlette warns that more threads cost memory and performance, so first move the slow sync calls behind async clients where you can.
AnyIO’s own task groups follow the same rule as asyncio.TaskGroup: if a child task raises, the other children are canceled, and multiple failures arrive in an ExceptionGroup. The equivalent of the earlier to_thread() sample looks like this:
import time
import anyio
from anyio import to_thread
def legacy_lookup(key: str) -> str:
time.sleep(0.2) # blocking call from a synchronous library
return key.upper()
async def handler(key: str, results: dict[str, str]) -> None:
results[key] = await to_thread.run_sync(legacy_lookup, key)
async def main() -> None:
results: dict[str, str] = {}
async with anyio.create_task_group() as tg:
for key in ("a", "b", "c"):
tg.start_soon(handler, key, results)
print(results)
anyio.run(main)
to_thread.run_sync() draws from the same 40-token default limiter as FastAPI’s sync endpoints, so heavy use in a FastAPI app competes with them. Pick one style per codebase. In a FastAPI service, AnyIO primitives in application code are a reasonable default; in a plain asyncio service, the standard library covers everything in this article.
How to keep an async service under control
You keep an async service under control by putting a timeout on every outbound call, capping how much work can be in flight, and running debug mode before production does the debugging for you. Without those limits, one slow dependency turns into thousands of stuck tasks.
Set timeouts around outbound work
asyncio.timeout() and asyncio.timeout_at() (both 3.11) limit how long a block can wait. The context manager turns the internal CancelledError into TimeoutError, so you can only catch TimeoutError outside the async with block.
import asyncio
async def call_downstream() -> str:
await asyncio.sleep(5) # a slow dependency
return "ok"
async def main() -> None:
try:
async with asyncio.timeout(2):
print(await call_downstream())
except TimeoutError:
print("downstream timed out, returning fallback")
asyncio.run(main())
Pick the timeout from the dependency’s real latency, measured in your own environment, plus a margin your callers can tolerate.
Limit concurrency and queue growth
An asyncio.Semaphore caps how many tasks enter a block at once. Wrap every outbound call to a rate-limited service in async with sem:. That applies to model APIs as much as to an internal billing service.
For producer and consumer pipelines, use a bounded asyncio.Queue. With maxsize above 0, await put() waits when the queue is full. The default maxsize=0 is unbounded, so a slow consumer lets the queue grow until memory runs out. Queue.shutdown() (3.13) gives consumers a clean exit: later put() calls raise QueueShutDown, and get() raises it once the queue is empty.
import asyncio
async def producer(q: asyncio.Queue) -> None:
for i in range(20):
await q.put(i) # waits while the queue is full
q.shutdown()
async def consumer(q: asyncio.Queue, name: str) -> None:
try:
while True:
await q.get()
await asyncio.sleep(0.05) # simulated outbound call
except asyncio.QueueShutDown:
print(name, "exiting")
async def main() -> None:
q = asyncio.Queue(maxsize=5)
async with asyncio.TaskGroup() as tg:
tg.create_task(producer(q))
for n in range(3):
tg.create_task(consumer(q, f"c{n}"))
asyncio.run(main())
Decide what happens when the bounded queue is full
A full queue moves the wait upstream. Every producer blocked in await put() is a suspended task, and if that producer is a request handler, the wait shows up as request latency. A bounded queue stops memory growth, but on its own it turns a slow consumer into slow responses and, eventually, client timeouts and retries that add more load.
Decide on purpose which of three behaviors each producer gets:
- Wait. Plain await put() is right for internal pipelines where the producer can afford to slow down, such as a batch reader feeding workers.
- Wait, then reject. Wrap put() in asyncio.timeout() and return 503 with a Retry-After header when the queue stays full, so clients back off instead of piling on.
- Reject at once. put_nowait() raises QueueFull immediately when there is no free slot, which suits endpoints where a fast “try later” beats any wait.
import asyncio
queue: asyncio.Queue[str] = asyncio.Queue(maxsize=2)
async def enqueue_or_reject(job: str, wait: float = 0.5) -> int:
"""Return the HTTP status the handler should send."""
try:
async with asyncio.timeout(wait):
await queue.put(job) # waits while consumers catch up
except TimeoutError:
return 503 # still full: shed load and send Retry-After
return 202
async def main() -> None:
# No consumer is running, so the third job finds the queue full.
print([await enqueue_or_reject(f"job-{i}", wait=0.1) for i in range(3)])
try:
queue.put_nowait("job-3")
except asyncio.QueueFull:
print("put_nowait: QueueFull, rejected without waiting")
asyncio.run(main())
The first two jobs return 202 and the third returns 503 after 0.1 seconds. Export the queue’s qsize() as a metric next to the 503 count: a queue that sits at maxsize for minutes means you need more consumers or a lower intake, and a bigger maxsize only delays the same outcome.
Handle shared state and cross-thread calls deliberately
asyncio synchronization primitives and asyncio queues aren’t thread-safe. Don’t use an asyncio.Lock or asyncio.Queue to coordinate OS threads.
When a worker thread needs to talk to the loop, use the two thread-safe entry points:
- loop.call_soon_threadsafe(callback) for plain callbacks
- asyncio.run_coroutine_threadsafe(coro, loop) for coroutines, which returns a concurrent.futures.Future the thread can wait on
Grab the loop with asyncio.get_running_loop() inside a coroutine and hand it to the thread when you start it.
Diagnose a stalled event loop
Debug mode catches most blocking calls before they reach users. Turn it on in any of four ways:
- Set PYTHONASYNCIODEBUG=1
- Run in Python Development Mode
- Call asyncio.run(main(), debug=True)
- Call loop.set_debug(True)
In debug mode, asyncio logs callbacks that take longer than 100 milliseconds, logs slow I/O selector calls, and makes many non-thread-safe APIs raise when called from the wrong thread. loop.slow_callback_duration adjusts the 100-millisecond threshold. Keep debug mode on in tests and staging, and leave it off by default in production.
Treat two warnings as bugs. “coroutine ‘…’ was never awaited” means someone called an async def function without awaiting or scheduling it. “Task exception was never retrieved” means a task failed and nobody looked. Debug mode adds the traceback showing where that task was created.
How to test async code, including timeouts and cancellation
Test the unhappy paths first. Manual testing exercises the happy path on every run, while timeout branches, cancellation cleanup, and task group failures often run for the first time in production.
Set up pytest-asyncio
pytest-asyncio (1.5.0 on PyPI as of November 2026) runs async def tests inside an event loop. In its default strict mode, it runs only tests that carry the @pytest.mark.asyncio marker, and by default each test gets its own event loop. Set the fixture loop scope explicitly in pytest.ini, because 1.5.0 warns when it’s unset:
[pytest]
asyncio_default_fixture_loop_scope = function
Run the suite with PYTHONASYNCIODEBUG=1 in CI so slow-callback logs and “never awaited” warnings show up next to the test that caused them.
Test the timeout and cancellation paths
Inject the dependency so a test can swap in one that never answers, and keep test timeouts in milliseconds so the suite stays fast:
import asyncio
import pytest
async def call_with_fallback(dependency, timeout: float) -> str:
try:
async with asyncio.timeout(timeout):
return await dependency()
except TimeoutError:
return "fallback"
@pytest.mark.asyncio
async def test_slow_dependency_returns_fallback() -> None:
async def slow() -> str:
await asyncio.sleep(10)
return "ok"
assert await call_with_fallback(slow, timeout=0.05) == "fallback"
@pytest.mark.asyncio
async def test_cancellation_runs_cleanup() -> None:
closed = asyncio.Event()
async def worker() -> None:
try:
await asyncio.sleep(10) # stands in for a long network wait
finally:
closed.set()
task = asyncio.create_task(worker())
await asyncio.sleep(0) # let the worker reach its first await
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert closed.is_set()
The second test fails if someone later swallows CancelledError or moves the cleanup out of finally, which is the regression you want to catch. Add the same kind of test for a task group with one failing child, asserting on the ExceptionGroup and on the siblings being canceled, and for a full queue returning your 503.
If your codebase runs on FastAPI and AnyIO, AnyIO ships its own pytest plugin with a pytest.mark.anyio marker. Its docs warn that it clashes with pytest-asyncio’s auto mode, so leave pytest-asyncio in strict mode if both are installed.
What changed in Python 3.14 and 3.15 for existing services
Python 3.14 is the release that breaks old asyncio habits, and 3.15 adds one new task group feature without deprecating or removing anything in asyncio. Python 3.15.0 shipped October 9, 2026, and the current releases are 3.15.2 and 3.14.10 (both October 25, 2026). Python 3.10 reached end of life on October 1, 2026, per the Python developer guide.
This section covers the asyncio changes only. For the rest of the 3.14 upgrade (t-strings, deferred annotations, the rollout plan), see our what’s new in Python 3.14 article.
| Change | Version | Status in November 2026 | What to do | Source |
|---|---|---|---|---|
| get_event_loop() raises RuntimeError with no current loop | 3.14 | In effect | Use asyncio.run(), or get_running_loop() inside coroutines | What’s new in 3.14 |
| Child watcher classes removed | 3.14 | Removed | Rely on the default subprocess support | What’s new in 3.14 |
| asyncio policy system deprecated | 3.14 | Removal scheduled for 3.16, not yet removed | Use loop_factory | Pending removal in 3.16 |
| asyncio.iscoroutinefunction() deprecated | 3.14 | Removal scheduled for 3.16, not yet removed | Use inspect.iscoroutinefunction() | Pending removal in 3.16 |
| create_task() passes all keyword arguments to the task factory | 3.14 | In effect | Check custom task factories | What’s new in 3.14 |
| TaskGroup.cancel() | 3.15 | New | Use for early, non-error exits | What’s new in 3.15 |
Replace implicit event loop creation and deprecated policies
Since 3.14, asyncio.get_event_loop() raises RuntimeError when there’s no current event loop. It no longer creates one for you. The What’s new in Python 3.14 page says most uses can move to asyncio.run(), or to asyncio.Runner (3.11) when you mix async calls with blocking code. Inside coroutines and callbacks, call asyncio.get_running_loop().
The policy classes and set_event_loop_policy() are deprecated, with removal scheduled for 3.16 according to the deprecations list. Pass a loop factory instead:
import asyncio
async def main() -> None:
await asyncio.sleep(0)
# Before (deprecated in 3.14, the pattern to replace):
# asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# asyncio.run(main())
# After:
asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)
Passing asyncio.EventLoop (3.13) picks the most efficient loop for the platform and skips the policy system entirely. If a custom task factory accepts a fixed set of keyword arguments, test it against 3.14’s create_task() change before you upgrade.
Use task inspection tools to find stuck work
Python 3.14 added python -m asyncio ps PID and python -m asyncio pstree PID, which read a live process and list its pending tasks as a flat table or as an await tree. Our Python 3.14 article walks through what each one prints. Two production details matter for async services:
- The command-line tools work only on supported platforms and may need extra permission to inspect another process, so confirm your production containers allow it while nothing is on fire.
- Python 3.15 adds –retries N, which retries when the target process changes while its state is being read. On a busy service, make it your default.
From inside your program, asyncio.capture_call_graph(), asyncio.print_call_graph(), and asyncio.format_call_graph() (all 3.14) show the async call graph. Wire format_call_graph() into a debug endpoint or a signal handler for staging.
In 3.15, the new Tachyon sampling profiler (the profiling.sampling module) adds an –async-aware mode that reconstructs task-based stacks, so a profile shows which coroutines are consuming time. Its one-shot dump mode with –async-aware prints every asyncio task in a hung process.
Account for TaskGroup.cancel() and optional free-threading
TaskGroup.cancel() gives you a clean early exit when the group’s goal is met, such as the first of several mirrors answering. A child task can call it if you pass it the group, and the group exits without raising CancelledError:
# Requires Python 3.15.
import asyncio
async def query_mirror(name: str, delay: float, tg: asyncio.TaskGroup,
results: list[str]) -> None:
await asyncio.sleep(delay)
results.append(name)
tg.cancel()
async def main() -> None:
results: list[str] = []
async with asyncio.TaskGroup() as tg:
for name, delay in [("us", 0.3), ("eu", 0.1), ("ap", 0.5)]:
tg.create_task(query_mirror(name, delay, tg, results))
print("first answer:", results[0])
asyncio.run(main())
Python 3.14 also gave asyncio first-class support for free-threaded builds, so several event loops can run in parallel on different threads. That build (for example, python3.14t) is supported but optional, and the standard build still has the GIL. Treat it as an experiment for your own workload, and check every C extension dependency before you try it. The GIL article covers how to test a service on the free-threaded build.
Separately, 3.14 switched native tasks to a per-thread doubly linked list. What’s new in Python 3.14 reports 10 to 20% better results on standard asyncio benchmarks plus lower memory use. Measure your own service before counting on any of that.
A rollout plan for introducing asyncio to an existing service
Introduce asyncio one service at a time, after you’ve confirmed the service is I/O-bound and its dependencies have async APIs. This plan keeps the synchronous version as your baseline until the async one beats it under the same load.
- Profile the service and confirm most request time is spent waiting on the network.
- List every I/O dependency in the request path and check whether each one offers an async API.
- Pick one service or one endpoint group as the pilot.
- Move the pilot to Python 3.14 or newer first, so get_event_loop() and policy changes surface before the async work starts.
- Make asyncio.run() the single entry point.
- Put asyncio.timeout() and a Semaphore around every outbound call, and decide what each producer does when its queue is full.
- Write tests for the timeout, cancellation, and task group failure paths, and run tests and staging with debug mode on. Fix every slow-callback log and “never awaited” warning.
- Load-test against the synchronous version and compare your own p50 latency, p99 latency, and error rates.
- Roll out behind a feature flag or to one instance group, then widen.
Go/no-go checklist before you widen the rollout:
- Debug mode in staging flags no blocking calls
- Every outbound call has a timeout, and tests cover the timeout and cancellation paths
- No “never awaited” or “Task exception was never retrieved” warnings in the logs
- p99 latency and error rate match or beat the synchronous baseline under the same load
- Someone on call can read a python -m asyncio pstree dump
What to look for in an engineer who runs asyncio in production
Async services need engineers who’ve debugged one under load. Look for people who can reason about I/O-bound versus CPU-bound work, structure concurrency and cancellation, design backpressure, and profile a stalled event loop.
Senior back-end developers should be able to show those skills on your own code. If your services run on FastAPI, FastAPI developers with production async experience are a direct fit, and they should already know where AnyIO’s 40-thread limit bites.
A strong live exercise is handing a candidate a slow async handler and asking them to find the blocking call, then asking how they’d test the timeout path they add. Arc’s interview guide covers how to structure and score technical rounds like that. Put those specifics in your Python developer job description, and name the async work the role will own.
The software engineer job description guide covers how to frame seniority and scope for the posting. When you’re ready to source candidates, the guide to the best platforms to hire Python developers compares where to look.
Frequently asked questions
Is Python async faster than threading?
Python async is faster than threading only for I/O-bound work with many concurrent waits, where one thread can keep thousands of requests in flight. One thread runs one task at a time, so CPU-bound code doesn’t get any faster. asyncio.to_thread() still runs under the GIL on the standard build, so it won’t speed up pure Python computation either.
When should I not use async Python?
Skip it for CPU-heavy handlers, codebases built mostly on synchronous dependencies, and low-concurrency tools or admin jobs. The docs’ example shows the risk: 1 second of CPU work delays every task and I/O operation on that loop by 1 second. Plain synchronous code or a process pool fits those cases better.
Should I use asyncio.gather or TaskGroup?
Use TaskGroup, added in 3.11, for related tasks. When one task fails, it cancels the others and raises the failures together in an ExceptionGroup. gather() passes the first exception up and leaves the other awaitables running unless you track and cancel them yourself, so failed requests can keep calling downstream services.
Why does asyncio.get_event_loop raise RuntimeError?
Since Python 3.14, get_event_loop() raises RuntimeError when no event loop is current instead of creating one implicitly. Start your program with asyncio.run(), or use asyncio.Runner when you mix async calls with blocking code. Inside coroutines and callbacks, call asyncio.get_running_loop() to get the loop you’re on.
Does free-threaded Python make asyncio obsolete?
No. The free-threaded build is optional and not the default, so most deployments still run with the GIL. On free-threaded builds, 3.14 lets separate event loops run in parallel threads, which adds to what asyncio can do. Services that mostly wait on the network still fit asyncio’s single-loop concurrency model.
Deciding where asyncio belongs in your services
Use asyncio where your service spends most of its time waiting on the network and every dependency in the request path is async-native. Keep CPU-heavy work in processes, and keep low-concurrency scripts synchronous.
Inside async services, standardize on task groups, asyncio.timeout() around every outbound call, and bounded concurrency with semaphores and queues that reject work deliberately when they fill. Test the timeout and cancellation paths, move to Python 3.14 or newer so you get ps, pstree, and the call graph tools, and drop the policy system before 3.16 removes it.
That work goes faster with engineers who have already found a blocking call in a production event loop. Arc matches you with Python developers from the top 2% of vetted talent, freelance in 72 hours or full-time in 14 days, and you pay $0 until you hire.








