0

I have a FastAPI asynchronous task that I would like to run after returning from an endpoint. To do this, I am using BackgroundTasks; however, it seems that whilst the background task is running the main event loop is blocked.

async def simple_task():
    await asyncio.sleep(10)
    print("completed")

@router.post("/test")
async def test(background_tasks: BackgroundTasks):
    background_tasks.add_task(simple_task)
    return {"message": "Task started"}

In the above code, I am unable to hit any other endpoints on the swagger page whilst the background task is running.

If instead I don't use BackgroundTasks e.g.

@router.post("/test2")
async def test():
    await asyncio.sleep(10)
    return {"message": "Task started"}

Then I am able to hit other endpoints on the swagger page whilst the task is running.

Potentially I have a misunderstanding of how FastAPI/starlette BackgroundTasks work. I thought the BackgroundTask is kicked off on the main event loop thread, and since I am using an asynchronous function, the main event loop thread should be freed to respond to other requests.

Rookleton
  • 11
  • 2
  • It seems like my issue is to do with FastAPI middleware and how that interacts with BackgroundTasks. If I remove all my middleware then it works, does anyone know a workaround for this? Starlette: https://github.com/encode/starlette/issues/919 FastAPI: https://github.com/tiangolo/fastapi/issues/1355 – Rookleton Aug 02 '23 at 00:03

0 Answers0