2

When pubnub is connected, users inside my app receive messages no problem. However, let's say they refresh the page or go to another page within the app. There's a 2 -> 5 seconds of downtime before the user can connect to pubnub again. During this time some pubnub messages may be missed.

Thankfully, the pubnub subscribe API allows you to specify a timetoken to point to a past time (e.g. 10 seconds ago).

pubnub.subscribe({
  channels: ['my_channel'],
  timetoken: '13534398158620385'
});

Description:

Specifies timetoken from which to start returning any available cached messages.

Question: What's the safest way to specify this timetoken such that few messages are missed?

Rob Campion
  • 1,359
  • 13
  • 26
  • 2 - 5 seconds for a page load? I'd consider optimizing your page loads. We haven't had anyone submit a support ticket with this issue. But your answer below is solid. Nice work. – Craig Conover Dec 24 '16 at 05:57
  • @CraigConover I wanted to keep the question pretty basic so this is just an example. Note, load here refers to webpage load, as opposed to how long it takes pubnub to load. – Rob Campion Dec 24 '16 at 10:12
  • Right, that was my understanding. Just wondering what the content is that takes that long. Perhaps you could hit PubNub first before loading the content? – Craig Conover Dec 26 '16 at 18:50
  • Potentially. Either way, there's gonna be a period of downtime though. – Rob Campion Dec 27 '16 at 17:05
  • Right, just saying nothing special has had to be implemented for many web apps using PubNub. – Craig Conover Dec 27 '16 at 17:07

1 Answers1

2

First, listen out for beforeunload events on the window. These will be fired before the page is moved away from. Inside this create a cookie to save the current timetoken:

window.addEventListener('beforeunload', () => {
  const now = new Date().getTime();
  // pubnub timetokens are 17 digits long
  const timetoken = `${now}0000`;

  createCookie(PUBNUB_TIMETOKEN_COOKIE, timetoken, EXPIRATION);
});

Note: PUBNUB_TIMETOKEN_COOKIE and EXPIRATION are constants of your choosing. I set my cookie to expire after 10 seconds to prevent clashes. Also you'll need to define a createCookie function similar to this one.

Next, when subscribing to pubnub on page load, use this cookie if it exists:

pubnub.subscribe({
  channels: ['my_channel'],
  timetoken: getCookie(PUBNUB_TIMETOKEN_COOKIE)
});

This way, if the user refreshes or navigates to another page, missed messages should be caught.

Community
  • 1
  • 1
Rob Campion
  • 1,359
  • 13
  • 26