How does Discourse implement live update notifications?

AI-generated summary

piratdavid inquired whether Discourse’s instant live updates for the ‘latest topics’ page rely on frequent AJAX polling or a more efficient method like WebSockets. angus clarified that Discourse utilizes a custom message bus (available in a separate repo) rather than simple timeouts, directing the user to subscribe to this bus for real-time updates. gdpelican further explained that the MessageBus is implemented using long polling rather than WebSockets, where requests are held open by the server until new data is available. After the initial explanation, piratdavid asked if it is possible to stop subscribing to specific channels when navigating away from a page. gdpelican confirmed that unsubscribing is fully supported and provided code examples demonstrating how to use messageBus.unsubscribe() to stop listening for specific topic events, allowing developers to dynamically manage subscriptions based on the user’s current view.

Hi,

I have written a plugin that has a news feed with a lists of latest topics in a sidebar. It updates regularly by making an ajax call to /latest.json every few seconds. The existing latest page in the forum has the same kind of functionality but the update is instant when something is posted. Is it safe to turn down the ajax calls to a very short interval or is this implemented using something like websockets, etc.

Thanx

Discourse does this via its messagebus.

The messagebus the Discourse team built has its own separate repo here.

It looks like the ‘latest’ topics are subscribed to here.

So rather than making ajax calls on a timeout, just subscribe to the messagebus.

If you’re curious, MessageBus is implemented using long polling (it does not support Websockets), which means the ‘live’ updating is done through requests which are held waiting on the server until something needs to update, at which point it responds with some data, and then initiates another ‘long’ request.

Sam’s exhaustive explanation here.

Thanx guys!

Things cleared a lot. :slight_smile:

Is it necessary or even possible to stop subscribing if I switch to another page or for some reason don’t want my feed to update? That is without stoping any subscriptions in discovery.

Is there an answer to this? :slight_smile:

Yep, it’s certainly possible. Babble’s implementation:

const messageBus = Discourse.__container__.lookup('message-bus:main')
messageBus.subscribe('/babble/topics/1/posts', (data) => { performSomeAction() })

Later, when we switch chat channels and don’t want to listen for topic 1’s events anymore:

messageBus.unsubscribe('/babble/topics/1/posts')
messageBus.subscribe('/babble/topics/2/posts', (data) => { performSomeOtherAction() })