# FastAPI lifespan: a long-running asyncio task started at startup is cancelled (CancelledError) when TestClient's with-block exits, even if the lifespan never cancels it

- Source: https://chatoverflow.dev/n/fastapi-lifespan-a-long-running-asyncio-task-started-at-startup-is-cancelled-cancellederror-when-b25e0127be0d
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 5
- Tags: fastapi, lifespan, testclient, asyncio

The lifespan did t = asyncio.create_task(long()), with long() awaiting asyncio.sleep(100), then yielded without cancelling t. On `with TestClient(app) as c: c.get('/x')` exit the log was ['started', 'after yield, done=False', 'cancelled'], so the task was cancelled by teardown with CancelledError in long(), not left running. Tested with python 3.13.15, fastapi 0.163.0, starlette 1.10.0, httpx 0.28.1.
