question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

FastAPI websocket can`t handle a large incoming of streams?

See original GitHub issue

Hi there. I have am using FastAPI websocket on Docker in my Ubuntu server. I have come very far in finishing it, and am currently in the test phase before everyting is “completed”.

While running different tests, I experienced a strange problem. From my client side, I am simulating an IoT devices sending realtime data including “position”, meaning as long as it is moving, it sends JSON object including its position. Im extremely confused at this point. Is it my code? Is my Dockerfile, is the linux server the problem? Therefore i feel the need to share all my file.

Before sharing my websocket code, here is my simple client code which i use to send data to my websocket server:

from websocket import create_connection
import json
import time

ws = create_connection("ws://139.59.210.113:5080/ws/testchannel")

time.sleep(1)


def send_json_all_the_time(position):
    generate_json = { "machineID":"001", "RepSensor": position}
    send_json = json.dumps(generate_json)
    print("JSON SENT FROM IoT SENSOR: {}".format(send_json))
    time.sleep(0.3)
    ws.send(json.dumps(send_json))
    time.sleep(0.3)


while True:
    for x in range(100):
        send_json_all_the_time(x)

    for x in range(100, -1, -1):
        ws.send("pause a little bit, starting again soon!")
        send_json_all_the_time(x)

The code above is simply runned locally from my computer, and sends a lot og realtime data to the websocket server.

The code snippet below is taken from my websocket script that is runned on the linux ubuntu server:


@app.websocket("/ws/testchannel")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    try:
        while True:
            data = await websocket.receive_text()
            print("Received data: {} ".format(data))
            await websocket.send_text(f"you sent message: {data}")
            await connection_manager.send_message_to_absolutely_everybody(data)

            """
            PROBLEM: if i use this " await connection_manager.send_message_to_absolutely_everybody(data) " line, than i get delay into the server.
            I think by optimizing the code this can be solved. You can test by commenting out the line 408 and you will see the difference.
            """

    except WebSocketDisconnect:
        print("client left chat.")

"""
The second problem: when a IoT device send a data to the server in real time and high speed, it gets disconnected randomly! 
"""

So while I am watching the terminal, the data comes in… but then “client left the chat” occurs randomly!

So my question is, is the problem at the script? the server? dockerfile? docker commands?

For instance, i share also my Dockerfile as well. And if someone is interested, i could invite to my private github repo.

FROM ubuntu:latest
FROM python:3

MAINTAINER raxor2k "xxx.com"

RUN apt-get update -y

RUN apt-get install -y python3-pip build-essential python3-dev

COPY . /app
WORKDIR /app

RUN pip3 install --upgrade pip
RUN pip3 install -r requirements.txt
RUN pip3 install fastapi uvicorn #dennekanfjernes?

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80", "--reload"]

Any answers or help would be appreciated!

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:16 (1 by maintainers)

github_iconTop GitHub Comments

3reactions
includeamincommented, Oct 8, 2020

Cool! I will definitely test this out!

I supposed i need to add gunicorn to my requrements.txt file? This is how my file currently looks like:

Click==7.0
fastapi==0.54.1
h11==0.8.1
httptools==0.1.1
pydantic==1.5.1
python-engineio==3.12.1
python-socketio==4.5.1
six==1.11.0
starlette==0.13.2
uvicorn==0.11.5
uvloop==0.14.0
websockets==8.1
hbmqtt==0.9.6

add this:

gunicorn==20.0.4


3reactions
includeamincommented, Oct 8, 2020
CMD gunicorn main:app  -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:80

check this out for more detail about gunicorns configs

Read more comments on GitHub >

github_iconTop Results From Across the Web

FastAPI websocket can't handle large incoming of data?
here is my server code which i run in dockercontainer: import json import time import socketio from fastapi import FastAPI, WebSocket from  ......
Read more >
WebSockets - FastAPI
Try the WebSockets with dependencies​​ Open your browser at http://127.0.0.1:8000. There you can set: The "Item ID", used in the path.
Read more >
Server-Sent Events: the alternative to WebSockets you should ...
WebSockets are the most used technology for real-time web apps. ... This may not seem a big deal, however it means that WebSockets...
Read more >
Getting Started With FastAPI And More
Let's create a FastAPI application, complete with web sockets, uploading files, and streaming media from the filesystem or database with ...
Read more >
API — websockets 8.1 documentation
Anything that isn't listed in this document is a private API. High-level¶. Server¶. websockets.server defines the WebSocket server APIs.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found