Troubleshooting Silent Execution in Python Async Workflows
Stacks & QueuesModel answerLast updated
Analyze and fix a Python async script that finishes silently without invoking its async functions, and explore concurrent execution options with asyncio.
You are reviewing a Python script designed to fetch data sequentially from two remote endpoints, extract values from the JSON payloads, sum them up, and log the final result to standard output.
However, executing the script completes immediately without printing any output.
import asyncio
import aiohttp
async def fetch_payload(session, endpoint_url):
async with session.get(endpoint_url) as response:
return await response.json()
async def execute_pipeline():
async with aiohttp.ClientSession() as session:
first_req = fetch_payload(session, "https://api.service.internal/v1/alpha")
second_req = fetch_payload(session, "https://api.service.internal/v1/beta")
val_a = (await first_req)["count"]
val_b = (await second_req)["count"]
total = val_a + val_b
print(f"Total Count: {total}")
def main():
execute_pipeline()
if __name__ == "__main__":
main()
Requirements
- Identify the primary cause of the missing output and explain why no HTTP calls take place.
- Provide a minimal fix that executes the pipeline sequentially and prints the result as intended.
- Refactor the code to execute both network requests concurrently. Discuss the trade-offs, potential runtime pitfalls (such as exception behavior, cancellation semantics, timeouts, and resource management), and best practices in modern Python.
Hints
Hint 1
Consider what invoking an `async def` function actually evaluates to in Python when not combined with `await` or driven by an event loop driver like `asyncio.run`.
Hint 2
Check standard error output when running un-awaited coroutines in CPython.
Hint 3
Compare sequential awaiting of coroutines against structured concurrency mechanisms like `asyncio.TaskGroup` or legacy helpers like `asyncio.gather`.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Root Cause Analysis
The script exits without producing output or making network requests because of how Python handles async def functions:
- Unstarted Event Loop: Calling an
async deffunction directly (execute_pipeline()) does not execute the function body. Instead, Python returns a coroutine object. Because the script never passes this coroutine object to an event loop (e.g., viaasyncio.run()), the event loop never starts, and execution never entersexecute_pipeline. - Garbage Collection Warning: When
main()finishes, the un-awaited coroutine object is garbage collected. CPython emits aRuntimeWarning: coroutine 'execute_pipeline' was never awaitedtosys.stderr. If standard error is redirected, suppressed, or unobserved, the script appears to exit cleanly and silently. - Sequential Execution of Requests inside the Coroutine: Inside
execute_pipeline,fetch_payload(...)is called twice withoutawaitat task creation time. Even ifexecute_pipelinewere running,(await first_req)would suspend execution until the first HTTP request completes before(await second_req)is evaluated. This creates sequential latency rather than concurrent execution.
2. Sequential Fix
To execute the coroutine sequentially, use asyncio.run() in main() to initialize the event loop and drive execute_pipeline to completion:
import asyncio
import aiohttp
async def fetch_payload(session: aiohttp.ClientSession, endpoint_url: str) -> dict:
async with session.get(endpoint_url) as response:
response.raise_for_status()
return await response.json()
async def execute_pipeline() -> int:
async with aiohttp.ClientSession() as session:
# Sequentially awaited
data_a = await fetch_payload(session, "https://api.service.internal/v1/alpha")
data_b = await fetch_payload(session, "https://api.service.internal/v1/beta")
total = data_a["count"] + data_b["count"]
print(f"Total Count: {total}", flush=True)
return total
def main() -> None:
asyncio.run(execute_pipeline())
if __name__ == "__main__":
main()
3. Concurrent Refactoring & Best Practices
If the two API requests are independent, running them concurrently cuts total execution time from $T_1 + T_2$ down to $\max(T_1, T_2)$.
Modern Python (3.11+) Approach: asyncio.TaskGroup
Structured concurrency with asyncio.TaskGroup ensures tasks are scoped to a block and exceptions/cancellations are managed cleanly.
import asyncio
import aiohttp
REQUEST_TIMEOUT = aiohttp.ClientTimeout(total=5.0)
async def fetch_payload(session: aiohttp.ClientSession, endpoint_url: str) -> dict:
async with session.get(endpoint_url) as response:
response.raise_for_status()
return await response.json()
async def execute_pipeline() -> int:
timeout_config = aiohttp.ClientTimeout(total=5.0)
async with aiohttp.ClientSession(timeout=timeout_config) as session:
async with asyncio.TaskGroup() as tg:
task_a = tg.create_task(
fetch_payload(session, "https://api.service.internal/v1/alpha")
)
task_b = tg.create_task(
fetch_payload(session, "https://api.service.internal/v1/beta")
)
# Once context exits, both tasks are guaranteed to be complete.
total = task_a.result()["count"] + task_b.result()["count"]
print(f"Total Count: {total}", flush=True)
return total
def main() -> None:
asyncio.run(execute_pipeline())
if __name__ == "__main__":
main()
Legacy Approach (Python < 3.11): asyncio.gather
async def execute_pipeline_legacy() -> int:
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=5.0)) as session:
data_a, data_b = await asyncio.gather(
fetch_payload(session, "https://api.service.internal/v1/alpha"),
fetch_payload(session, "https://api.service.internal/v1/beta")
)
total = data_a["count"] + data_b["count"]
print(f"Total Count: {total}", flush=True)
return total
Concurrency Considerations & Pitfalls
-
Exception Propagation & Cleanup:
asyncio.TaskGroup: If one task fails (e.g., HTTP 500 or timeout), the remaining tasks in the group are immediately cancelled. The context manager raises anExceptionGroupcontaining all errors, preventing orphan requests.asyncio.gather: By default (return_exceptions=False), if one coroutine fails,gatherimmediately raises that exception. However, sibling coroutines continue executing in the background un-awaited. Ifreturn_exceptions=Trueis used, exceptions are returned in the result list and must be explicitly filtered withisinstance(res, Exception).
-
Resource Management:
- Always open
ClientSessionin the parent coroutine scope and pass it into worker functions. Creating aClientSessionper request breaks connection pooling and leads to socket exhaustion. - Response bodies must be read (
await response.json()) inside theasync with session.get()scope while the underlying socket stream is open.
- Always open
-
Timeouts:
- Async network calls without explicit timeouts can hang indefinitely, keeping the event loop occupied. Use
aiohttp.ClientTimeoutorasyncio.timeout(3.11+).
- Async network calls without explicit timeouts can hang indefinitely, keeping the event loop occupied. Use
-
Cancellation Hygiene:
- Never use broad
except Exception:blocks that swallowasyncio.CancelledError(in Python 3.7 and earlier,CancelledErrorderived fromException). In modern Python (3.8+),CancelledErrorinherits directly fromBaseException, but best practice remains avoiding bareexcept:or re-raising caught cancellation errors.
- Never use broad
-
Existing Event Loop Environments:
- Calling
asyncio.run()in environments where an event loop is already active (such as Jupyter notebooks or Tornado/Twisted apps) throws aRuntimeError. In such environments, useawait execute_pipeline()directly orasyncio.create_task().
- Calling
Complexity Analysis
- Time Complexity:
- Sequential: $O(T_{\text{alpha}} + T_{\text{beta}})$ latency + $O(S_{\text{payload}})$ parsing.
- Concurrent: $O(\max(T_{\text{alpha}}, T_{\text{beta}}))$ latency + $O(S_{\text{payload}})$ parsing.
- Space Complexity: $O(S_{\text{payload}})$, proportional to the combined JSON response payloads buffered in memory.