BackgroundTasks blocks entire FastAPI application #11210
-
First Check
Commit to Help
Example Codefrom time import sleep
from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
async def testing():
print('I am going to block whole application')
sleep(60)
print('I am alive again after 60 seconds of blocking')
@app.get("/check")
def check():
return 'It works'
@app.get("/task")
def add_task(background_tasks: BackgroundTasks):
background_tasks.add_task(testing)
return 'Task was added' DescriptionTo reproduce:
Expected result: I saw similar question in discussion section in github but this bug doesn't related to any middleware. As you see I don't use middleware in code. Could you tell me how to use async code in the background in a FastAPI application please? Operating SystemmacOS Operating System DetailsMac OS Sonoma 14.3.1 (23D60) FastAPI Version0.110.0 Pydantic Version2.6.2 Python Version3.10.10 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Your issue is linked to the way Python handles asynchronous code, not FastAPI itself. For instance, this works as expected:
As you can see, the only difference is that now, your async background task is really asynchronous ( Each Python thread has a single Asyncio There are multiple solutions:
|
Beta Was this translation helpful? Give feedback.
-
That's because you are using a blocking call (sleep) in an async function. I suppose the sleep would be the repr. of your code. So I can understand you are using a block function or maybe without the "await" in your async background task. |
Beta Was this translation helpful? Give feedback.
Your issue is linked to the way Python handles asynchronous code, not FastAPI itself.
For instance, this works as expected:
As you can see, the only difference is that now, your async background task is really asynchronous (
asyncio.sleep
and nottime.sleep
), it w…