Publish/Subscribe API for PubNub Rust SDK

The foundation of the PubNub service is the ability to send a message and have it delivered anywhere in less than 100ms. Send a message to just one other person, or broadcast to thousands of subscribers at once.

For higher-level conceptual details on publishing and subscribing, refer to Connection Management and to Publish Messages.



Available in features


The publish_message() function is used to send a message to all subscribers of a channel. To publish a message you must first specify a valid publish_key at initialization. A successfully published message is replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel.

Publish Anytime

It's not required to be subscribed to a channel in order to publish to that channel.

Message Data

The message argument can contain any JSON serializable data, including Objects, Arrays, Integers, and Strings. data should not contain special classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.

Don't JSON serialize

It is important to note that you should not JSON serialize when sending signals/messages via PUBNUB. Why? Because the serialization is done for you automatically. Instead, just pass the full object as the message payload. PubNub takes care of everything for you.

Message Size

The maximum number of characters per message is 32 KiB by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5 KiB) providing optimal network performance.

Message Too Large Error

If the message size exceeds 32KiB, you receive an appropriate error response.

For further details, check the support article.

Message Publish Rate

Messages can be published as fast as bandwidth conditions will allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber can't keep pace with the publisher.

For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.

Publishing to Multiple Channels

It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.

Publishing Messages Reliably

There are some best practices to ensure messages are delivered when publishing to a channel:

  • Publish to any given channel in a serial manner (not concurrently).
  • Check that the return code is success (for example, [1,"Sent","136074940..."])
  • Publish the next message only after receiving a success return code.
  • If a failure code is returned ([0,"blah","<timetoken>"]), retry the publish.
  • Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
  • Throttle publish bursts in accordance with your app's latency needs, for example, Publish no faster than 5 messages per second to any one channel.


To Publish a message you can use the following method(s) in the Rust SDK:

.publish_message(T: Serialize)
.meta(Option<HashMap<String, String>>)
publish_messageT: SerializeYesThe message payload. Any type that implements the Serialize trait is allowed.
channelInto<String>YesThe channel to send the message to.
storeOption<bool>OptionalAccount defaultWhether to store the messages in Message Persistence or not.
metaOption<HashMap<String, String>>OptionalA hash map of additional information about the message you can use for Filters.
replicateboolOptionalWhether to replicate the messages across points of presence or not. Refer to Replicated Transactions for more information.
ttlOption<u32>OptionalA per message time to live in Message Persistence.
1. If store = true, and ttl = 0, the message is stored with no expiry time.
2. If store = true and ttl = X (X is an Integer value), the message is stored with an expiry time of X hours.
3. If store = false, the ttl parameter is ignored.
4. If ttl isn't specified, then expiration of the message defaults back to the expiry value for the key.
use_postboolOptionalfalseWhether to use HTTP POST to publish the message.
executeYesfalseExecutes the request based on the provided data. This function returns a Future and you must .await the value.

Basic Usage

Publish a message to a channel:

Other Examples


The publish() operation returns a PublishResult which contains the timetoken, or a PubNub Error which contains the error indicator and the description of the error.

// success example
PublishResult { timetoken: "16808621084073203" }

// failure example
Error: PublishError("Status code: 400, body: OtherResponse { status: 400, error: true, service: \"Access Manager\", message: \"Invalid Subscribe Key\" }")



Available in features


Receive messages

Your app receives messages and events via event listeners. The event listener is a single point through which your app receives all the messages, signals, and events that are sent in any channel you are subscribed to.

For more information about adding a listener, refer to the Event Listeners section.


This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified channel. To subscribe to a channel the client must send the appropriate subscribe_key at initialization.

By default a newly subscribed client will only receive messages published to the channel after the subscribe() call completes. If a client gets disconnected from a channel, it can automatically attempt to reconnect to that channel and retrieve any available messages that were missed during that period. This can be achieved by setting with_retry_policy() to RequestRetryPolicy::Linear, when initializing the client.


To subscribe to a channel you can use the following method(s) in the Rust SDK:

channels()Vec<String>Either channels() or channel_groups() is required.Channels to subscribe to.
channel_groups()Vec<String>Either channels() or channel_groups() is required.Channel groups to subscribe to.
cursor()u64OptionalTimetoken allowing you to subscribe from a specific point in time.
heartbeat()u32OptionalInterval (in seconds) in which the client annouces itself to the server.
filter_expression()StringOptionalString allowing the client to only receive messages that satisfy the conditions of the filter. The message filter is set by the subscribing client(s) but it is applied on the server side thus preventing unwanted messages (those that do not meet the conditions of the filter) from reaching the subscriber.

For more information, refer to the Publish Messages documentation.

Basic Usage

Subscribe to a channel with automatic connection handling:

Event listeners

The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.


The subscribe() operation returns a Subscription which implements the stream trait and contains a SubscribeStreamEvent as its item.

SubscribeStreamEvent has the following variants:

StatusSubscribeStatusStatus of the subscription. Available statuses:

  • Connected
  • Disconnected (disconnected after previously connecting)
  • DisconnectedUnexpectedly (disconnected after previously connecting while trying to reestablish the connection to the PubNub network)
  • ConnectionError (initial connection attempt failed)
UpdateUpdateThe actual real-time update, like a message or a presence update.

The Update enum contains the following variants:

PresencePresence change real-time update. Payload represents one of the presence types:

  • join – a user joined the channel.
  • leave – a user left channel.
  • timeout – service didn't notice a user for a while.
  • interval – bulk update on joined, left and timeout users.
  • state-change - a user changed their associated state.
ObjectObject (App Context) real-time update.
MessageActionMessages reactions real-time update.
FileFile sharing real-time update.
MessageReal-time message update.
SignalReal-time signal update.

Other Examples

Raw asynchronous subscribe with no connection handling

Raw synchronous subscribe with no connection handling

Only receive message updates

let subscription = client
.channels(["my_channel".into(), "other_channel".into()].to_vec())

tokio::spawn(async move {
let mut message_stream = subscription.message_stream();
while let Some(update) = {
match update {
Update::Message(message) => {
// Deserialize the message payload as you wish
match serde_json::from_slice::<Message>(& {
Ok(message) => println!("defined message: {:?}", message),
show all 24 lines

Only receive status updates

let subscription = client
.channels(["my_channel".into(), "other_channel".into()].to_vec())

tokio::spawn(async move {
let mut status_stream = subscription.status_stream();
while let Some(status) = {
println!("\nstatus: {:?}", status);

Subscribing to multiple channels

It's possible to subscribe to more than one channel using the Multiplexing feature. The example shows how to do that using a vector to specify the channel names.


When subscribed to a single channel, this function causes the client to issue a leave from the channel and close any open socket to the PubNub Network. For multiplexed channels, the specified channel(s) will be removed and the socket remains open until there are no more channels remaining in the list.

Unsubscribing from all channels

Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken and thus, there could be some gaps in the subscription that may lead to message loss.


To Unsubscribe from a channel you can use the following method(s) in the Rust SDK:


Basic Usage

Unsubscribe from a channel:

Event listeners

The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.


This method doesn't return anything. Note that the Subscription entity will cease to exist and will no longer be usable.

Last updated on