pythonwebsocketfastapi

Does FastAPI websocket example deadlock the process?


The code in the docs has a while True: block and I am curious if something like that would deadlock the process. If I get two requests, would the second one just not go through? why or why not?

Source: https://fastapi.tiangolo.com/advanced/websockets/

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"Message text was: {data}")

Solution

  • Based on the code sample given in your question, the short answer is that subsequent requests would go through (regardless of the while True loop) and processed concurrently.

    The long answer is depends on what kind of operations you would like to perform inside the async def function/endpoint (including the while True loop), i.e., non-blocking I/O-bound or blocking I/O-bound or CPU-bound operations?. When a function is called with await and concerns a non-blocking I/O-bound operation (e.g., waiting for data from the client to be sent through the network or waiting for contents of a file in the disk to be read), the event loop (that runs in the main thread) can then continue on and service other coroutines (requests) while waiting for such operations to complete (i.e., in your case, waiting for a message to be either received or sent, using await websocket.receive_text() and await websocket.send_text()). If, however, you perform some blocking I/O-bound tasks (e.g., using the requests library to perform HTTP requests) or CPU-bound tasks (i.e., audio or image processing, machine learning, etc.), the event loop will get blocked; that means, no further requests would go through, until that I/O-bound or CPU-bound operation is completed.

    Please refer to this answer for more details and solutions around this subject.