cloudflare/workers-chat-demo

Persisting WebSocket connections

molefrog opened this issue · 2 comments

First of all, thank you of a well-documented demo! It really helped me to understand the concept of Durable Objects, which I find one of the most amazing things that the Workers platform has.

The demo and the official documentation mention that a durable object can be destroyed and then recreated again, I assume in order to migrate the object closer to the clients and to make it easier to handle deploys. This perfectly explains why there are essentially two ways of storing data: in-memory and storage. The memory acts as a cache: we can keep intermediate data in there that can be lost. In order to ensure data safety we sync that data with the storage, which will guarantee the presence of the data between the lifecycles of the object.

In the chat demo however we store a list of all current WebSocket clients in an instance variable this.sessions. And that made me wonder: what happens with these WebSocket connections when an object is destroyed? Do they get disconnected? And if they are not is there a way to persist a WebSocket object in the storage (since they aren't plain JS objects)?

what happens with these WebSocket connections when an object is destroyed? Do they get disconnected? And if they are not is there a way to persist a WebSocket object in the storage (since they aren't plain JS objects)?

Hi @molefrog , thanks for the kind words.

You're correct that WebSockets will be disconnected when an object is destroyed. We don't have any plans to attempt to keep them connected in such cases. If the object itself is being moved to a different machine or a different location it could be quite difficult for us to seamlessly transition the existing WebSocket connections to hook up to the new instance.

If it makes you feel better, these disconnections should be relatively uncommon, on the order of once or twice a week, corresponding to when a new version of the workers runtime is released or when an edge PoP or machine is taken down for maintenance.

Hey @a-robinson, thanks for your fast response!

You're correct that WebSockets will be disconnected when an object is destroyed.

Alright, it actually makes things much easier! I guess the documentation could have mentioned this, but I'm sure you guys already have that in your roadmap.

If it makes you feel better, these disconnections should be relatively uncommon, on the order of once or twice a week.

It is quite interesting. I guess that means that for apps that don't require strong data persistency, we could write workers that use only in-memory storage, for example a 1-1 chat room that keeps messages alive for a certain period of time.

Anyways, keep up the good work!