Skip to content

Fast api is blocking long running requests when using asyncio calls #8842

Answered by sm-Fifteen
mindej asked this question in Questions
Discussion options

You must be logged in to vote

Here are the three main cases. The first one (async_will_block) is what you want to avoid.

from fastapi import FastAPI
from time import sleep
from asyncio import sleep as async_sleep

app = FastAPI()

# Blocking call in async route
# Async routes run on the main thread and are expected
# to never block for any significant period of time.
# sleep() is blocking, so the main thread will stall.

@app.get("/async_will_block")
async def async_will_block():
    sleep(10)
    return []

# Blocking calls on sync route
# Sync routes are run in a separate thread from a threadpool,
# so any blocking will not affect the main thread.

@app.get("/sync_no_block")
def sync_no_block():
    sleep(10)
    re…

Replies: 7 comments 3 replies

Comment options

You must be logged in to vote
0 replies
Answer selected by Kludex
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
3 replies
@john-jaraceski
Comment options

@jayapratha111998
Comment options

@sm-Fifteen
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question or problem question-migrate
8 participants
Converted from issue

This discussion was converted from issue #3091 on February 28, 2023 16:52.