CtrlK
CommunityDocumentationLog inGet started
Tessl Logo

pubnub/pubnub-app-developer

Build real-time applications with PubNub pub/sub messaging

Agent Success

Agent success rate when using this tile

94%

Improvement

Agent success rate improvement when using this tile compared to baseline

1.29x

Baseline

Agent success rate without this tile

73%

Overview
Eval results
Skill reviews
Files

publish-subscribe.mdreferences/

PubNub Publish/Subscribe Patterns

Core Concepts

Publish/Subscribe (Pub/Sub) is PubNub's fundamental messaging pattern for real-time communication.

Key Components

ComponentDescription
PublisherClient/server that sends messages to channels
SubscriberClient/server that receives messages from channels
ChannelNamed conduit through which messages are routed
MessageData payload (JSON, string) up to 32KB
PubNub NetworkGlobal broker handling routing and delivery

Decoupling Principles

  • Space Decoupling: Publishers and subscribers don't need to know each other
  • Time Decoupling: Messages can be sent when no subscribers are online
  • Synchronization Decoupling: Publishers don't block waiting for receivers

Publishing Messages

Basic Publish (JavaScript)

const pubnub = new PubNub({
  publishKey: 'pub-c-...',
  subscribeKey: 'sub-c-...',
  userId: 'user-123'
});

// Publish JSON object
await pubnub.publish({
  channel: 'chat-room',
  message: {
    user: 'Alice',
    text: 'Hello, World!',
    timestamp: Date.now()
  }
});

Python SDK

from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub

pnconfig = PNConfiguration()
pnconfig.publish_key = 'pub-c-...'
pnconfig.subscribe_key = 'sub-c-...'
pnconfig.uuid = 'user-123'

pubnub = PubNub(pnconfig)

pubnub.publish().channel('chat-room').message({
    'user': 'Alice',
    'text': 'Hello, World!'
}).sync()

Publish with Callback (Async)

pubnub.publish(
  {
    channel: 'notifications',
    message: { type: 'alert', content: 'New update available' }
  },
  (status, response) => {
    if (!status.error) {
      console.log('Published with timetoken:', response.timetoken);
    } else {
      console.error('Publish error:', status);
    }
  }
);

Subscribing to Messages

Basic Subscribe with Listener

// Add listener BEFORE subscribing
pubnub.addListener({
  message: (event) => {
    console.log('Received:', event.message);
    console.log('Channel:', event.channel);
    console.log('Publisher:', event.publisher);
    console.log('Timetoken:', event.timetoken);
  },
  status: (statusEvent) => {
    if (statusEvent.category === 'PNConnectedCategory') {
      console.log('Connected successfully');
    }
  }
});

// Subscribe to channels
pubnub.subscribe({
  channels: ['chat-room', 'notifications']
});

Python Subscribe

from pubnub.callbacks import SubscribeCallback

class MySubscribeCallback(SubscribeCallback):
    def message(self, pubnub, message):
        print(f'Received: {message.message}')
        print(f'Channel: {message.channel}')

    def status(self, pubnub, status):
        print(f'Status: {status.category}')

pubnub.add_listener(MySubscribeCallback())
pubnub.subscribe().channels(['chat-room']).execute()

Message Delivery Behavior

When No Subscribers Are Present

  • Messages are still accepted by PubNub
  • Short-term cache holds last 100 messages (~20 minutes)
  • With Message Persistence enabled, messages are stored for configured retention
  • Reconnecting clients can catch up using timetokens

Catching Up on Missed Messages

// Subscribe with restore option for automatic catch-up
pubnub.subscribe({
  channels: ['chat-room'],
  withPresence: false
});

// Manual history fetch for longer gaps
const history = await pubnub.fetchMessages({
  channels: ['chat-room'],
  count: 100
});

Best Practices

Message Payload Design

// Good: Small, focused payload
{
  "type": "chat_message",
  "user": "alice",
  "text": "Hello",
  "ts": 1704067200000
}

// Avoid: Large, nested structures
// Keep under 32KB, use concise field names

Error Handling

pubnub.addListener({
  status: (statusEvent) => {
    switch (statusEvent.category) {
      case 'PNConnectedCategory':
        console.log('Connected');
        break;
      case 'PNReconnectedCategory':
        console.log('Reconnected');
        break;
      case 'PNDisconnectedCategory':
        console.warn('Disconnected - will retry');
        break;
      case 'PNNetworkDownCategory':
        console.error('Network down');
        break;
      case 'PNAccessDeniedCategory':
        console.error('Access denied - check permissions');
        break;
    }
  }
});

Unsubscribe and Cleanup

// Unsubscribe from specific channels
pubnub.unsubscribe({
  channels: ['chat-room']
});

// Unsubscribe from all
pubnub.unsubscribeAll();

// Clean up on page unload
window.addEventListener('beforeunload', () => {
  pubnub.unsubscribeAll();
});

Communication Patterns

PatternDescriptionExample
Fan-outOne publisher to many subscribersBroadcast announcements
Fan-inMany publishers to one channelSensor data aggregation
1:1 ChatTwo users, dedicated channelDirect messaging
Group ChatMultiple users, shared channelTeam chat rooms
Request/ResponsePublish request, await replyRPC-style patterns

Performance Guidelines

  • Publish rate: 10-15 messages/second per channel recommended
  • Message size: Keep well under 32KB for optimal delivery
  • Subscriber capacity: Ensure clients can process incoming message rate
  • Use async publishing to avoid blocking
tessl i pubnub/pubnub-app-developer@0.1.4

SKILL.md

tile.json