Search code examples
javascriptnode.jspubnub

PubNub Subscribe Keeps Unsubscribing


I am using the PubNub Node.js module to listen to a channel but it randomly unsubscribes and I would like it to auto-reconnect if this happens.

I have added the restore: true option but this does not seem to be working.

const pubnub = new PubNub({
  subscribeKey: config.SUB_KEY,
  uuid: config.UUID,
  restore: true,
  autoNetworkDetection: true,
});

Solution

  • PubNub Functions instead of Server-side Subscribe

    Server-side Subscribe challenges to consider

    Subscribing on the server requires your server to keep an open connection to PubNub at all times. For a single channel or several channels, this is not difficult. But scale that to thousands of channels and you are putting quite a bit of responsibility on your server and you to implement this in a scalable and resident way.

    • What if the server goes down, is there another instance to listen to those channels?
    • How many channels/message (rate of messages) can your server handle before you need more instances to handle the load?
    • If you have multiple instance subscribing to the same channels, how do you determine which server handles each message (prevent duplicate handling)?
    • How do you determine which channels each server listens to if no duplicate those channels across all instances?

    PubNub will scale, but will your server/s? And there are answers to all of the above using best practices (contact PubNub support if you are in need of this sort of design) but there is another way that requires less work on your part and puts the burden on PubNub, which is why we exist, using PubNub Functions.

    PubNub Functions FTW!

    So, you want your server to receive messages that are published to a channel (or many channels)? Create an After Publish Function that binds to the channel you were originally subscribing to, and send the message to your server using xhr to POST the message. You will need to provide a REST endpoint on your server to receive these web requests but that is going to be the code you have in place to receive the subscribe messages. You just need to add that code to your REST endpoint (assuming you know how to implement this endpoint but if not, there are plenty of tuts about that).

    If you want to modify the message before it is sent to your server, use a Before Publish Function.

    To get a jumpstart on the Functions code for third party features, you can look at PubNub Integrations. But the code you need to get you started is a simple xhr.