0

In our flask socketio app, we have a socket.on("disconnect") that is called whenever a socket client disconnects, to handle the db state updates. However, when our server is killed due to a restart or due to a crash, this disconnect function cannot be called (since the server is transiently nonexistent), and is discarded. When the server is back up, all those socket disconnects to each frontend can never be processed properly, so the state is inconsistent.

Is there a way to "cache" these disconnect events to run when the server is back up? The end goal is to ideally have all the sockets would reconnect as well automatically, but currently we do this disconnect then reconnect manually. Our setup is Gunicorn flask threads being Nginx load balanced with a redis event queue with flask socket io.

John Targaryen
  • 1,109
  • 1
  • 13
  • 29

2 Answers2

1

You should register process signal

def handler(signum, frame):
    # loop and handle all socket disconnect

# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
juice
  • 31
  • 4
1

The best way to handle this is to not force-kill your server. Instead, handle a signal such as SIGINT and disconnect all clients in a corresponding signal handler.

Another alternative is to keep track of your connected clients in a database (redis, for example). If the application is killed and restarted, it can go through those users and perform any necessary cleanup before starting a new server instance.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Miguel Grinberg
  • 65,299
  • 14
  • 133
  • 152
  • Could you give an example of how we would place the signal handler in the codebase? Thank you! – John Targaryen Oct 18 '20 at 03:26
  • The accepted answer on [this SO question](https://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python) shows how to write a signal handler for SIGINT. – Miguel Grinberg Oct 18 '20 at 10:34