When subscribing to a topic, how do I get the last message that was broadcasted?

Use case: A document is shared for editing, but it can have only one editor at a time. When someone request access for edition, a message is broadcasted to all subscribers.

Problem: when someone subscribes later (i.e. after the editor has been designated), that subscriber won’t know who is the editor. How can this subscriber get the last message that was broadcasted, in order to be up-to-date with the state?

More concretely, people join a room, a LiveView, where a document is editable. The document is editable only by one user at the time, there is some checkbox which allows locking/unlocking edition access. When the editor is changing, the new editor is broadcasted.
Problem: If someone joins that room/LiveView later on, he doesn’t know who is editing (and that is really annoying as he thinks no one is editing, and can lock the document for edition while someone was editing).

AFAIK, Phoenix PubSub channels are (fairly intentionally) not durable for clients that were not connected at the time. You will need to pursue some other form of coordination or persistence. Perhaps new clients can publish a request to know the current editor upon joining, or you could expose that aspect through a non-channel request.

2 Likes

You could use phoenix presence to propagate who’s the current editor. But keep in mind that it’s only eventually consistent. If you need stronger guarantees this will be more complex.

Sorry could you elaborate on that a little bit? :sweat_smile:

If you have multiple nodes in a cluster, which are currently unable to connect it’s not ensured that all clients see the same state being propagated by phoenix presence. It will however converge when they happen to be able to connect again.

this problem doesn’t happen with PubSub? It’s something specific to Presence?

The same does happen with pubsub as well, just that pubsub doesn’t usually hold state, so it rather means your might not reach all listeners.