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%
Publish/Subscribe (Pub/Sub) is PubNub's fundamental messaging pattern for real-time communication.
| Component | Description |
|---|---|
| Publisher | Client/server that sends messages to channels |
| Subscriber | Client/server that receives messages from channels |
| Channel | Named conduit through which messages are routed |
| Message | Data payload (JSON, string) up to 32KB |
| PubNub Network | Global broker handling routing and delivery |
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()
}
});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()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);
}
}
);// 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']
});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()// 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
});// Good: Small, focused payload
{
"type": "chat_message",
"user": "alice",
"text": "Hello",
"ts": 1704067200000
}
// Avoid: Large, nested structures
// Keep under 32KB, use concise field namespubnub.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 from specific channels
pubnub.unsubscribe({
channels: ['chat-room']
});
// Unsubscribe from all
pubnub.unsubscribeAll();
// Clean up on page unload
window.addEventListener('beforeunload', () => {
pubnub.unsubscribeAll();
});| Pattern | Description | Example |
|---|---|---|
| Fan-out | One publisher to many subscribers | Broadcast announcements |
| Fan-in | Many publishers to one channel | Sensor data aggregation |
| 1:1 Chat | Two users, dedicated channel | Direct messaging |
| Group Chat | Multiple users, shared channel | Team chat rooms |
| Request/Response | Publish request, await reply | RPC-style patterns |