pythonasynchronousasync-awaitpython-asynciofastapi

FastAPI asynchronous background tasks blocks other requests?


I want to run a simple background task in FastAPI, which involves some computation before dumping it into the database. However, the computation would block it from receiving any more requests.

from fastapi import BackgroundTasks, FastAPI

app = FastAPI()
db = Database()

async def task(data):
    otherdata = await db.fetch("some sql")
    newdata = somelongcomputation(data,otherdata) # this blocks other requests
    await db.execute("some sql",newdata)
   


@app.post("/profile")
async def profile(data: Data, background_tasks: BackgroundTasks):
    background_tasks.add_task(task, data)
    return {}

What is the best way to solve this issue?


Solution

  • Your task is defined as async, which means fastapi (or rather starlette) will run it in the asyncio event loop. And because somelongcomputation is synchronous (i.e. not waiting on some IO, but doing computation) it will block the event loop as long as it is running.

    I see a few ways of solving this: