Skip to content

Lesson 2 of 9 · 21m

Tasks, create_task, and the Lifecycle You Own

How coroutines become scheduled tasks, when fire-and-forget is safe, and why unreferenced tasks and hidden exceptions are production incidents waiting to happen.

A coroutine becomes concurrent work only when something schedules it. In application code that usually means asyncio.create_task(). That one call is powerful and dangerous: it starts work in the background, but it does not transfer responsibility for the work to some mythical supervisor. You own the task lifecycle.

create_task schedules now, execution starts soon

async def refresh_cache():
    await cache.rebuild()
async def handler():
    task = asyncio.create_task(refresh_cache())
    return {'status': 'refresh queued'}

create_task() wraps the coroutine in a Task and arranges for it to run on a future loop iteration. It does not run synchronously before the next line. If the handler returns immediately, the rebuild continues in the background.

The garbage collector can kill your fire-and-forget task

This pattern is a classic production bug:

asyncio.create_task(upload_metrics(batch))

Nothing stores the task. Python only keeps a weak reference internally in some situations, so the task can be garbage-collected mid-flight. The service then loses work silently or logs 'Task was destroyed but it is pending'. Keep a strong reference and remove it when done:

background = set()

task = asyncio.create_task(upload_metrics(batch))
background.add(task)
task.add_done_callback(background.discard)

Python 3.11+ type checkers and linters often catch missing references, but the data structure is still your responsibility.

Exceptions inside tasks do not propagate by magic

async def fail_later():
    await asyncio.sleep(0.1)
    raise RuntimeError('boom')

task = asyncio.create_task(fail_later())
await asyncio.sleep(1)       # logs 'Task exception was never retrieved'

The exception is stored on the task object. If nobody awaits it or calls task.exception(), asyncio eventually complains. In a service, that means failures are invisible exactly where you need them most.

For deliberate background work, attach error handling or inspect completion:

def report_done(task):
    try:
        task.result()
    except Exception:
        logger.exception('background task failed')

task.add_done_callback(report_done)

gather is concurrency with a join

asyncio.gather() schedules several awaitables and waits for all results:

users, orders, inventory = await asyncio.gather(
    load_users(account_id),
    load_orders(account_id),
    load_inventory(account_id),
)

By default the first exception propagates, but sibling tasks keep running. return_exceptions=True turns failures into result values, which is useful for fan-out where partial success is meaningful — and dangerous if you forget to inspect those values.

Field notes

  • Treat background tasks like spawned threads: name them, track them, and define shutdown behavior; create_task is not a queue — a million tasks is a million live objects waiting for memory, sockets, and deadlines.
  • Use asyncio.wait() when you need completion order, timeouts, or FIRST_EXCEPTION semantics instead of all-at-once gather behavior.
  • In tests, await asyncio.sleep(0) once does not guarantee a background task finished; it only gives the loop one scheduling pass.

Was this lesson helpful?

Sign in to rate