How Can I Get Missed Messages After Reconnecting To Channels?

Prerequisites

The solution discussed below assumes there is some sort of message history store implemented on you application server. To implement such a store, you can review the guidance at How do I implement message (event) history for Channels? before continuing.

How to retrieve messages missed during periods of network instability

Sometimes a client will lose Internet connectivity. When that happens new messages won't be able to be delivered to that client.

The Pusher libraries maintain a list of channels that an application is subscribed to. Therefore, upon reconnection they can automatically re-subscribe to those channels. The benefit of this is that the functionality implemented to retrieve historical messages can also be used for this connectivity scenario because the pusher:subscription_succeeded event will once again be triggered resulting in the historical message retrieval logic being exercised.

The only addition that is required is for the call to the server to also pass an ID of the last message it presently has. If you have followed the link in the prerequisite then this was referred to as the sequence ID that was to be used to detect duplicate messages and to sort existing messages.

Assuming you have the retrieveHistory function from the prerequisite, the function can be updated as follows:

function retrieveHistory() {
  var lastId = getLastMessageSequenceId();
  $.get('/messages', {after_id: lastId}).success(function(response) {
    // TODO: add missed messages to the UI
  });
},

As before, you should check for duplicates and the order of your messages within the UI.

Conclusion

By following the techniques it is easy to use the events that the Pusher libraries expose to add historical data to an application and also fetch any missed messages during periods of network instability.

Still have questions? Please reach out to our Support team by visiting this page.

Last updated