The community forums are in BETA and closed to the public.

Calculating a PubNub Message Payload Size

Calculating a PubNub Message Payload Size

Today PubNub's maximum JSON message byte size is 32,000 bytes 32K of data. It is necessary to prevent yourself from getting a "Message Too Large" gateway response by ensuring you aren't going to be sending too large of payloads on a per-message basis. Best way to test this before sending is to use the following pattern for testing potential message payload size.

// Calculating a PubNub Message Payload Size.
function calculate_payload_size( channel, message ) {
    return encodeURIComponent(
        channel + JSON.stringify(message)
    ).length + 100;

This is a pre-packaged JavaScript function which allows you to test your message payload size.

You'll want to calculate your message size before sending to PubNub in order to prevent "Message Too Large" Gateway Responses. Normally this isn't necessary if you generally cap your message size well below 32,000 bytes, but if you want to approach the absolute limit, here is the solution:

JSON Message Size Calculation JavaScript Function Usage

var channel = "my_channel_name";
var message = { 
    "name" : "Rob Middleton", 
    "company" : "Lyft", 
    "language" : "JavaScript" };

var size = calculate_payload_size( channel, message );

console.log( "Payload Size: ", size );

OUTPUT: Payload Size: 197

Keep in mind that you'll want to ensure UTF-8 encoding on message before calculating the string length. On a mobile platform with keyboards that support multi-byte chars and unicode emoji, calculating payload size can be a bit challenging.

Yes agreed ensure your .length implementation allows UTF-8 character counting support.

And for C#:

var pubnub = new PubNub(your keys);

var messageSize = pubnub.JsonPluggableLibrary.SerializeToJsonString(message).Length * sizeof(Char);

Robert ty! Good for C#.

Login or Signup to post a comment