KatInterview

Troubleshooting Silent Execution in Python Async Workflows

Stacks & QueuesModel answer
MediumModel answerStacks & Queuespythonasyncioconcurrency

Last 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

  1. Identify the primary cause of the missing output and explain why no HTTP calls take place.
  2. Provide a minimal fix that executes the pipeline sequentially and prints the result as intended.
  3. 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`.