Architectural Choices
PubNub provides a high level of resilience and extremely low latency. The right architectural choice to use PubNub in the best possible way depends on your use case.
This document explains the wrong way and the right way to use PubNub. As you read through this document, you'll discover the most common mistakes a customer makes with PubNub.
Send Messages
Sending messages on PubNub is easy. Call the Publish API. This is the starting point of your development adventure.
Inefficient Client-Server Passthrough Publish
Client brokers message to Server. This is inefficient. Your client should be using the PubNub Publish to net the full benefits of PubNub. By using PubNub incorrectly like the diagram above, the client may have multi-second latencies. It introduces your server and a single point of failure. Other nearby clients won't get sub-100 ms round-trip performance This is the inefficient way to use PubNub.
Optimal Client Publish
The client publishes and subscribes to PubNub directly. The client receives a global average latency of 100 ms. Nearby clients are likely to get sub-100 ms latency. During connectivity duress, the client will be routed to the next accessible route. The client should use an authorization token with granted access to Publish on a data channel.
Optimal Client Publish + Synchronous Server Logic
When you need to have your server involved for business logic reasons or data copy reasons. This pattern shows you the best approach for integrating server-side logic with PubNub.
Optimal Client Publish + Asynchronous Server Logic
Often you'll find the need to run business logic on your JSON messages, but without slowing the message delivery down. You can do this by creating an onAfter
event handler. This handler type will allow you to execute server logic on a copy of your JSON message asynchronously while the original JSON message is on it's way to be delivered to the phone.
Optimal Client Publish + HTTP Call to Third-party API Server
You can integrate third-party APIs easily. Enable Functions onBefore
or onAfter
event handlers on your data channels and use the JavaScript code snippets to execute an HTTP call to the external API.
The payload returned from the API server can be used to augment and modify the original JSON message inline. Or you can save the original message to the third-party API using an onAfter event handler.
Optimal Server Sent Events
Server sent events are possible using PubNub. You can notify your users the completion status of a long-running task. If the event is client-initiated, the client must publish
directly to PubNub. Sending events from your server should only be for asynchronous tasks like a timer/cron, system-level events or long-running task status.
Receive Messages
Inefficient Proxy Connection
You may be considering a proxy in-the-middle solution. However this breaks down quickly when encryption and TCP connection duration policies conflict. Poor performance and the loss of reliability for the mobile app's connectivity.
Optimal TCP Connection to Nearest Point of Presence
You must subscribe to a data channel to receive messages using PubNub. This is done by calling the subscribe API using the PubNub SDK. When you invoke subscribe, the mobile app will open a TCP connection to the nearest PubNub data center. The connection is left open forever. When the mobile app is closed, the connection is cleared.
Message Data Copy
You may want to copy messages to your own database for indexing or backup purposes.
Inefficient Forking Messages Doubles Mobile Traffic
Sending data directly to your server from the client is an inefficient way to copy data from PubNub. The optimal way is to publish or fire your message directly to your local PubNub POP. PubNub provides multiple points of presence allowing your client device fast reliable connectivity.
Optimal Event Handler
Using Functions allows you to run the light-weight JavaScript code block directly inside PubNub Platform. You can issue an HTTP call directly inside JavaScript which POSTs the message body to your server. You can use onAfter
event handlers to save the message to your database. Your server will receive the http payload and save the data as needed in your database.
Optimal Offline Backup with Message Persistence
PubNub includes multi-datacenter replicated message persistence. Your messages are configurable to be indexed and stored across multiple PubNub PoPs. This allows you to fetch the history for a data channel on a periodic interval. You can download every message from your app via the Message Persistence paging API. After you have fetched your messages, you can save them to your database and process the messages as you need.
Security
Key Exchange & Rotation
When providing the phone app with API keys (publish key
, subscribe key
, cipher key
) you should never hard-code those keys directly in your production app. You should enable Access Manager to add security to your PubNub environment.
Using Access Manager, your mobile app needs to authenticate itself by calling a secure endpoint with access credentials. To get them, the server needs to first make a grant call to PubNub and request a time-limited token with embedded permissions for the app. The app needs to include the received token in any subsequent request made to PubNub to access various resources (channels, channel groups, or User ID metadata) and perform operations at the access level defined in the token. For more details, read about the authentication flow in Access Manager.
User ID / UUID
User ID is also referred to as UUID
/uuid
in some APIs and server responses but holds the value of the userId
parameter you set during initialization.
Optimal Client Authenticates with your App Server returning API Keys
To authenticate and provide access to PubNub's network for your users, you need to provide them with PubNub's API keys and an access token. The client is able to perform the permitted activities, such as Read/Write/Admin/Manage, on PubNub resources depending on the permissions specified in the token.
This key and token exchange can happen after authentication. There are many ways to authenticate your clients, including having an API endpoint at your server. Functions endpoints offer this as well, as shown in the next example.
Optimal Client Authenticates with Functions Endpoint giving API Keys
Using Functions endpoints, you can run your own lightweight JavaScript code on PubNub. This allows you to provide API keys to your client device programmatically. However, your client-side code or your server will need to call PubNub's grant API to get a token that your app can use to interact with PubNub resources.
Inefficient Client App has Hard-coded API Keys
When you hard code your API keys for access to PubNub, you'll put yourself in a security risk situation. You'll no longer have access to Key Rotation capabilities. It's not easy to implement your own Key Rotation. You'll be stuck in a multi-deploy multi-week work cycle in a process of Key Migration.
This is much more involved and it's better to avoid hard coding in general. If you don't have a web server, you can use Functions endpoints to store your API keys. The endpoint is accessible from your client device via HTTP POST. The endpoint will return access credentials to the client device including a Publish Key and a Subscribe Key. It can also return an access token if the endpoint is secured.
Inefficient Client App with an Embedded Secret Key
The secret key should only be used within a secure server and never exposed to client devices. If the secret key is ever compromised, it can be an extreme security risk to your PubNub account keys. If you suspect your secret key has been compromised, you have the ability to regenerate a new secret key for the existing PubNub keys set.
Regenerating the Secret Key
Please contact PubNub Support for guidance on best practices before you regenerate a secret key for a product PubNub key set. You'll be put in touch with a Solution Architect to determine the best path forward for your use case and requirements.
More Design Patterns
- Design Patterns for Server Message Aggregation
- Design Patterns for Friend Lists and Status Feeds