Skip to the page

Concurrency · senior

Tasks, gather, TaskGroup and limiting concurrency

Tasks that nobody holds or awaits can vanish and hide errors. gather does not cancel the others when one fails, a TaskGroup does, and any large fan-out needs a limit on calls in flight.

The notes

What you must know

  • asyncio.create_task with no saved reference: the loop keeps only a weak reference, so a task can be garbage-collected before it finishes.
  • An exception in a task nobody awaits appears only as "Task exception was never retrieved" in the asyncio logger, often not sent to the error tracker. On shutdown, pending tasks are destroyed.
  • Fix: keep tasks in a set, use add_done_callback to discard and log failures, and wait for pending tasks with a time limit on shutdown. Must-deliver work belongs in a durable queue or an outbox table with retries and an idempotency key.
  • gather with return_exceptions=False raises the first exception at once, and the other awaitables are not cancelled. They keep running.
  • TaskGroup (3.11) cancels the remaining tasks when one fails, waits for all of them, then raises an ExceptionGroup, handled with except*. async with asyncio.timeout(2) gives one deadline.
  • Cancelling does not undo side effects: release a reservation in a compensating step, use idempotency keys and expiry. Code must not swallow CancelledError: clean up in finally and re-raise.
  • gather on 50,000 URLs opens 50,000 sockets and hits the open-files limit. Limit with asyncio.Semaphore(100) or worker tasks reading a bounded Queue in a TaskGroup. Use one shared client session with a per-host limit.
  • Every request needs a timeout. Retry 429 and 5xx with exponential backoff and jitter, honour Retry-After, and write results as they finish with a checkpoint.

The red pen

Common traps: mistake → fix

  • Mistake: gather cancels the rest when one fails

    Fix: it does not; TaskGroup does.

  • Mistake: Raising ulimit fixes the too many open files error

    Fix: the real fix is limiting concurrency.

  • Mistake: await the webhook inside the request

    Fix: it makes the request slow and fails the order when the merchant is down; use a durable queue.

  • Mistake: return_exceptions=True with nothing logged is fine

    Fix: errors are lost.

Easy to hard

Questions interviewers ask, easy to hard

  1. Why can an asyncio.create_task webhook never be sent?
  2. What is the difference between gather and TaskGroup when one call fails?
  3. How do you limit an async script to 100 calls in flight?
  4. Why does cancelling a task not undo a stock reservation?
  5. How would you design must-deliver webhooks?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview