3

TL;DR: Rails-server restarts aren't handled gracefully in Action Cable, resulting in corrupted state. How to fix that?

I run a Rails server which uses Action Cable, among other things.

When I change a file, the server restarts as expected. But it doesn't exactly restart gracefully.

The Action Cable connection logs {"type":"disconnect","reason":"server_restart","reconnect":true} in the established socket. Then the socket appears to be cut and my channel's unsubscribed method does not run. Upon reconnect, however, the subscribed method does run—as it should, but now we have an asymmetry. Something as simple as keeping track of the number of connected clients has become unreliable because upon a server restart that number will now double although the true number remained the same. That's because it gets to increment the count when subscribed is called, but decrementing the counter happens in unsubscribed, which is not called when the server restarts.

If this only happened in development, it wouldn't be a huge issue, but it happens in production as well during server restarts caused by deployments.

How do I tell Rails to restart the server gracefully, by which I mean it should also run the unsubscribed method in my channel instead of just cutting the connection?

EDIT: I've also filed an issue with Rails: https://github.com/rails/rails/issues/41005

Dennis Hackethal
  • 13,662
  • 12
  • 66
  • 115
  • Why not listen for the disconnect callback on the client-side and trigger a reconnection to the server? Also, you might find help in this Github issue https://github.com/rails/rails/issues/30678 – theterminalguy Feb 01 '21 at 04:19
  • "Why not listen for the disconnect callback on the client-side and trigger a reconnection to the server?" Because that wouldn't cover the following use case: server restarts and while server is down the client closes the connection. Then, when the server finishes restarting, the cleanup is never done. More generally speaking, I cannot rely on clients to trigger the cleanup for me. Regarding the link, maybe, but it looks like something else. I'll have to try it. – Dennis Hackethal Feb 15 '21 at 05:43
  • were you able to resolve this issue? – Abhinay Jan 28 '22 at 09:28
  • @Abhinay I don't recall. – Dennis Hackethal Jan 29 '22 at 04:01

0 Answers0