The pub/sub functionality in PubNub

Every PubNub capability builds on the pub/sub model (also called the publish-subscribe pattern). This page explains the model that publishing and subscribing share:

  • how a channel routes data
  • what travels on one
  • how message types categorize that traffic
  • where PubNub's responsibility for delivery ends and your application's begins

One rule holds throughout the model: a channel is the only routing mechanism, so PubNub delivers every published payload to the clients subscribed to that channel and to nobody else.

Publishing and subscribing to the same channel​

A publisher sends a payload to a channel by name. A subscriber asks for a channel by name and receives whatever arrives on it. Neither side names the other, and neither side learns anything about the other from the operation itself.

Both halves of the model run through a PubNub SDK configured with a keyset. A keyset is the set of publish, subscribe, and secret keys that identifies your application to the PubNub network. To create a keyset and get those credentials, refer to Set up your account.

The following JavaScript shows the two halves of the model addressing one channel:

1const PubNub = require('pubnub'); // Requires a current SDK version that supports channel entities
2
3const pubnub = new PubNub({
4 publishKey: 'YOUR_PUBLISH_KEY',
5 subscribeKey: 'YOUR_SUBSCRIBE_KEY',
6 userId: 'example-user',
7});
8
9// Subscriber: receives whatever arrives on channel_1
10const subscription = pubnub.channel('channel_1').subscription();
11subscription.onMessage = (messageEvent) => {
12 console.log('Message received:', messageEvent.message);
13};
14
15// Publisher: sends one payload once the connection is established
show all 27 lines

For the complete calls, parameters, and per-language equivalents, refer to Send different message types and Receive messages.

Three consequences follow from publishers and subscribers never addressing each other.

  • Fan-out costs the publisher nothing. A publish call is the same call whether one client or a stadium of clients is subscribed, and the publisher is not told who is listening. The number of subscribers on a PubNub channel is unlimited.
  • One client is usually both. A single SDK instance publishes and receives over the same connection, so a chat participant, a game client, or a device reporting telemetry needs no second connection to talk back.
  • Delivery confirmation is an application concern. A successful publish returns a timetoken confirming that PubNub accepted the payload, not a recipient list. Applications that need read or delivery receipts build them by attaching message actions to the original published message.

Subscription also decides when a client is eligible to receive. PubNub delivers on the live path only to clients subscribed at the moment of publish. The Message Persistence feature, once enabled on your keyset, makes the payload available later to anyone who was not there.

Channels need no setup and no capacity planning​

A channel is a name, not a resource you declare. There is no exchange, topic, queue, or partition to define before traffic flows. Channels are created implicitly the first time they are used and do not require provisioning. That makes your channel-naming scheme a design decision, not a provisioning task, and lets an application invent channel names at runtime as its conversations, matches, or device fleets change.

PubNub channel names are case-sensitive. Channel names cannot exceed 92 UTF-8 characters. For the naming grammar and the conventions that make a name addressable by a pattern, refer to Channels and channel naming.

Two properties of the model shape how applications use that freedom:

  • A publish addresses one channel. No API sends a single call to several channels. To deliver the same payload to several channels, publish separately to each one. Refer to Publish overview.
  • A subscription addresses many channels. One SDK connection multiplexes subscriptions to many channels at once, so per-device connection count stays flat as an application's channel count grows.

Because channels need no provisioning and one connection carries many subscriptions, most applications use many narrow channels rather than a few broad ones, and then use naming to group them. Dot notation such as chat.room.123 gives names a hierarchy, and a wildcard subscription such as chat.* receives every channel matching the pattern. Wildcard depth is bounded, so refer to API limits before designing a deep hierarchy.

A channel group moves that grouping to the server. A channel group is a server-managed, named list of channels that a client subscribes to with a single call. Adding or removing channels in a channel group server-side changes what every subscribed client receives without any client resubscribing. Channel groups support subscribe operations only, so you can't publish to a group. Channel groups require the Stream Controller add-on enabled on the keyset.

When Presence is enabled, each subscribed channel gets a -pnpres companion channel that carries join, leave, and timeout events for that channel.

What travels on a channel​

The model carries two publish types. Both are commonly called "messages" in everyday usage, but the API treats them differently:

  • A message is the general-purpose unit: any JSON-serializable value, including objects, arrays, strings, and integers, which PubNub SDKs serialize for you. The standard message payload size limit is 32 KiB. This includes the channel name and any metadata.
  • A signal is a deliberately smaller unit for high-frequency, transient updates such as typing indicators, cursor positions, or location pings. Signal payloads are limited to 64 bytes. Signals are never stored, cannot trigger mobile push notifications, and cost less per operation than messages.

For the full comparison and the trade-offs between them, refer to Publish overview.

Send signals and messages on separate channels. Mixing them on the same channel interferes with how the SDK recovers missed events after a disconnect.

Messages and signals are not the only events a subscription delivers. One subscription is the delivery path for everything happening on a channel:

What arrivesPlatform typeSourceAdd-on required?
Message0Your publishersNo
Signal—Your publishersNo
File event4File SharingYes
App Context event2App ContextYes
Message Action event3Message ActionsNo
Presence event—Presence (companion channel)Yes

Each type has its own listener handler. File Sharing, App Context, and Presence must each be enabled on your keyset before their events reach a subscriber.

Each event carries the channel it arrived on, a timetoken, and, for most event types, the User ID of the client that triggered it. The exact field set varies by event type. For the complete list of event types and what each one carries, refer to Events.

Message types categorize traffic on a shared channel​

Applications rarely send one kind of payload. A single chat channel might carry text, an image reference, a poll, and an invitation. The platform-assigned type integer in the table above lets a subscriber identify what kind of event arrived before it inspects the payload.

Each message also supports an optional custom_message_type string that you set at publish time, returned as cmt in the subscribe payload. It carries your own business-specific label. The custom string is present only when a publish set it. Give subscribers a default path for untyped traffic rather than assuming the field is present. Messages retrieved from Message Persistence include the custom message type only when the request enables the include_custom_message_type flag, whose name varies across SDKs.

The custom_message_type value accepted by the PubNub Publish, Signal, and File Sharing APIs must be a case-sensitive alphanumeric string of 3 to 50 characters. Dashes (-) and underscores (_) are allowed. The value cannot start with a special character or with the reserved prefixes pn_ or pn-.

For the payload shapes and calls that set a custom message type, refer to Send different message types.

What the model guarantees​

Each guarantee below is stated precisely, so you can design your application to rely on them:

  • every message on a channel carries a timetoken you can order by
  • the live subscribe path is at-most-once on a stable connection
  • replaying whatever a client missed is built into the platform

Message ordering​

Ordering is a property of the message rather than of the delivery path. PubNub assigns every published message a server-side timetoken: a monotonically increasing 17-digit value precise to 100 nanoseconds (10⁻⁷ s), the number of 100-nanosecond intervals since the Unix epoch.

PubNub assigns every message a server-side timetoken when it accepts the publish. The timetoken records when PubNub accepted the message, which can differ from when the client sent it. History fetched through Message Persistence returns a channel's messages in timetoken order.

A subscriber receives live messages in the order they reach it, and each message carries its timetoken. Arrival order can differ from timetoken order and from one subscriber to another. Sorting a channel's messages by timetoken gives every client the same order. Timetoken order applies within a channel, so each channel's messages sort on their own.

That's what allows channels to scale out without any coordination between them.

At-most-once live delivery​

Live delivery to subscribers is at-most-once by default. On a stable connection, a subscriber receives each message at most once. After a reconnect, a replayed message can arrive again with the same timetoken. A subscriber can also miss messages if its buffer overflows or if it's disconnected when someone publishes a message.

Short gaps replay automatically: the SDK sends the last timetoken it received, and the network replays what is still in the message buffer. Longer gaps require a separate fetch from Message Persistence; the subscribe loop does not recover those on its own. For the full model, refer to Connection management.

Publish retry and idempotency​

PubNub does not deduplicate publishes on the server. Publishing the same payload twice always creates two distinct messages with two different timetokens.

By default, PubNub SDKs retry subscribe operations automatically, but not publish operations. So retrying a failed publish is a decision your application makes. It can choose a different response per message type: retry immediately, retry with backoff, surface the failure to the user, or drop it.

Because nothing deduplicates on the server, a retry after an ambiguous failure can produce a duplicate. For at-least-once construction, the REST-only qos parameter, and the SDKs that offer subscribe-side deduplication, refer to Publish overview. For how the network produces these guarantees, refer to How PubNub works.

How other capabilities extend Pub/Sub​

Pub/Sub moves data between clients. Each capability below changes what happens to a published message without changing the publish or subscribe call itself:

  • Message Persistence stores messages so they can be retrieved by timetoken later, which is also what lets a client recover what it missed while offline.
  • Message Actions attach data to a message that is already published, such as a reaction, an edit marker, or a receipt, so those features need no second channel.
  • Mobile Push Notifications turn a published message into an APNs or FCM notification, reaching a device whose client is not connected.
  • Functions run your JavaScript inside the network as a message passes through, so validation, transformation, or enrichment ships once instead of in every client.
  • Presence reports who is currently subscribed to a channel and generates join, leave, and timeout events, which the Pub/Sub model itself does not tell you.
  • Access Manager gates the model with signed, time-limited tokens. The write permission on a channel authorizes publish and signal operations, and the read permission authorizes subscribe. Refer to Operations to permissions mapping.

Next steps​

  • Publish. The publish API, the response timetoken, delivery semantics, and publish metadata.
  • Subscribe. Subscriptions, event listeners, and filtering what a client receives.
  • Quickstart. Publish and receive your first message.
  • Core concepts. Channels, messages, User IDs, timetokens, tokens, memberships, and channel groups.
  • How PubNub works. The network that carries the model: edge routing, latency, scaling, and fault tolerance.

Was this page useful?

Last updated on