Functions Basics
PubNub provides Functions to capture events that are happening on the PubNub Platform. Functions let you write code or leverage existing integrations to transform, re-route, augment, filter, and even aggregate data.
Let's consider an example of counting candidate or ballot votes, client or server analytics, or another metric that has to have an accurate count from a distributed set of contributing endpoints. In a traditional database, you would have to:
- Get the current count value from the database.
- Lock that record.
- Increment the count.
- Write the incremented value back to the database - and repeat that for every instance.
With Functions, all you need to do is to use incrcounter()
which does all this asynchronously and accurately, without overwriting other vote increments.
Functions on Admin Portal
For more information, refer to the Admin Portal docs.
Functions Hosting
Functions doesn't require you to spin up your servers or incur increased latency through call-outs to external server/serverless technology; the code you write or leverage runs within PubNub's operational environment, giving you the scale and speed that you need for your applications.
Functions API
For more information about the Functions API, check out the Functions API documentation.
Performance and Limitations
Functions have several performance tiers, which differ by the maximum requests per second (RPS) a Function can make.
For our Free and Starter plan users, the typical achievable performance is 15 RPS (one standard XHR call, Webhook, Log, etc.). It's important to note that RPS is not a simple measure of requests. Instead, it's our internal adaptation of RPS, which can vary across different types of Functions.
Functions run on the Starter plan can scale up to 10 times in less than 20 seconds, which significantly increases the computing power for your Functions should their load increase. Functions run on the Free plan do not scale, so if your Functions load exceeds the RPS limit, they will either time out or take a long time to execute.
You may consider increasing the computing power if your Function has performance issues or requires more RPS. The hardware Functions run on comes in various tiers. If you are interested in increasing the computing power for your Functions, contact sales.
Event Types
There are numerous event types:
-
Before Publish or Fire: operates on a message before the message is distributed to subscribers/users (synchronous)
-
After Publish or Fire: operates on a copy of a message simultaneously with the original message being distributed to subscribers/users, and doesn't return a timetoken (asynchronous)
-
Before Publish File: operates on a message before files are distributed to subscribers/users (synchronous)
-
After Publish File: operates on a copy of a message simultaneously with files being distributed to subscribers/users, and doesn't return a timetoken (asynchronous)
-
Before Signal: operates on a message before signals are distributed to subscribers/users (synchronous)
-
After Signal: operates on a copy of a message simultaneously with the signal being distributed to subscribers/users, and doesn't return a timetoken (asynchronous)
-
After Presence: code logic runs after presence events (join, leave) (asynchronous)
-
On Request: code logic runs upon URI request, such as from curl or a Web application (synchronous)
-
On Interval: code logic runs every time interval, specified in
milliseconds
(asynchronous) -
Subscribe with On Interval: a combination of functions that allows users to subscribe to channels with an ability to react to these subscribes in intervals.
What Function Type to Use
Synchronous (blocking) event types, such as Before Publish or Fire, operate on the original message, before it's delivered. The logic of the Function must complete before the message is released to continue its trip to the subscribers, which introduces a delivery delay (from microseconds for simple arithmetic, to potentially hundreds or thousands of milliseconds if interacting with a third-party system).
Asynchronous (non-blocking) event types, such as After Publish or Fire, operate on a copy of the message that includes any processing by synchronous functions, and don't increase latency. Asynchronous Functions can't change the original message, the message received by the client is always identical to the message that triggered the Function.
Use a synchronous function if you need to do any of the following:
- Block a message
- Alter a message or its payload
- Alter a message's meta information
- Re-route a message to a different channel
For most other operations, you can use an asynchronous function.
You can also use both function types on a given channel. For example, if you want to change messages (synchronous), and also want to send data to an external system about them (asynchronous), split the logic between two functions, and keep the network I/O operations out of the synchronous function. This will keep the synchronous function's latency as low as possible, for the best user experience.
The following sections describe these function types in greater detail.
Before Publish or Fire Functions
These functions are synchronous.
Use a Before Publish or Fire function if you want to change a message in-flight (add a new attribute or modify an existing attribute). Some applications of Before Publish or Fire include:
- Translating a message from one language to another
- Conversion of values from Imperial to Metric
- Detecting (and censoring) profanity
- Detecting (and normalization) of missing or illegal values
After Publish or Fire Functions
These functions are asynchronous.
Use an After Publish or Fire function if you want to pass the original message through the PubNub Platform intact, and also use it as a trigger to execute other logic (such as logging and message teeing). Some applications of After Publish or Fire include:
- Asynchronous third-party message logging (such as ElasticSearch)
- Mentions, keywords, and other string triggers
- Message teeing and forwarding
Before Publish File
These functions are synchronous.
Use a Before Publish File function if you want to trigger code before the file message is published to a channel. Some applications of Before Publish File include:
- Evaluating file contents via a third party AI/ML capabilities.
- Routing the message to a moderator channel if the service marks the file as inappropriate.
- Checking the file for copyright infringements via a third party service and possibly deleting the file from Message Persistence.
After Publish File
These functions are asynchronous.
Use an After Publish File function if you want to trigger code after the file message is published to a channel. Some applications of After Publish File include:
- Asynchronous file message logging
- File message auditing
- Business metrics gathering
Before Signal Functions
These functions are synchronous.
Use a Before Signal function if you want to change signal data (a small message sent using the Signal API) in-flight, either by adding a new attribute or modifying an existing attribute. Some applications of Before Signal include:
- Custom logic based on user typing; for example, when a customer starts typing after many minutes in a call center chat, send an urgent message to the agent letting them know the customer has re-engaged
- Pass letters as they're being typed into a phrase dictionary for automatic suggestion/completion functionality
- Integrate geographic data into the overall chat application experience
After Signal Functions
These functions are asynchronous.
Use an After Signal function if you want to pass the original signal data through the PubNub Platform intact, and also use it as a trigger to execute other logic, such as integration with logging services. Some applications of After Signal include:
- Asynchronous third-party message logging (such as ElasticSearch)
- Saving typing state into user real-time profile
- Saving location data into user profile
After Presence Functions
These functions are asynchronous, and trigger on subscriber (user) presence events, not messages. Presence events occur as users connect and disconnect from the real-time application. For example, when a user enters a chat room, a join
event is triggered, and when they leave the chat room, a leave
event occurs. The following Presence events are available:
Event | Description |
---|---|
join | A user subscribes to a channel. |
leave | A user unsubscribes from a channel. |
timeout | A timeout event is fired when a connection to a channel is severed and the subscriber hasn't been seen in 320 seconds (just over 5 minutes). This timeout interval can be customized using the heartbeat and heartbeat interval settings (SDK v3.6 or later). |
state-change | A state-change event will be fired anytime the state is changed using the state API (function signature varies by SDK). |
interval | An occupancy count is sent every 10 seconds (the default setting for the Presence Interval property, which is also configurable in the Presence add-on panel in your account admin portal). |
This presence events are also available as Callbacks, webhooks that can be called directly from the Presence service when these events occurred. Configured in your account admin portal, the HTTP callback URI must be publicly accessible. The callback logic could be managed by yourself, in your own environment in a non-PubNub service, or it could be pointing to an On Request Function (see below).
Use an After Presence event type if you want to pass a presence event through the PubNub Platform intact, and also use it as a trigger to execute other logic (such as logging and message teeing). Some applications of After Presence include:
- Sending an SMS to an offline user when a member of their priority buddy-list comes online
- Updating an on-hold wait time KV store as JOIN and LEAVE events occur
- Monitor a user's online/offline time card as they JOIN and LEAVE an app
On Request Functions
These functions are synchronous.
On Request functions let you create publicly accessible REST API methods. In addition to providing a lightweight approach to publicly accessing your PubNub code, you can also use on-request functions in your other functions as a replacement for pubnub.fire()
. This offers several advantages, such as:
- Breaking your main function into smaller components for ease of maintainability
- Defining a utility function that you'll call from many other functions
- Returning data to the calling function for any number of reasons
On Interval Functions
These functions are asynchronous.
On Interval functions let you create functionality that will execute automatically at the specified time interval. This functionality makes it easy to add logic that would otherwise be located in other systems and servers, whether non-PubNub cloud or on-premises. The execution environment provides easy access to PubNub functionality and data. Some applications of On Interval include:
- Periodically updating KV store cache data based on message data stored in history
- Periodically sending packaged-up message data for use in an external service
- Periodically updating User ID metadata based on message activity
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.
Subscribe with On Interval Functions
These functions are asynchronous.
Limited availability
This function type is not available to all users. If you'd like to use it, contact support.
Subscribe with On Interval function lets you create custom functionality that allows you to subscribe to the traffic and execute additional code in intervals as a reaction to these subscribes. This lets you implement complex logic that involves periodic reactions to the subscribe traffic.
Some applications of the Subscribe with On Interval include:
- Throttling the messages with rerouting to a different channel which can be listened to in Events & Actions to be stored for later analysis.
- Aggregation of message reactions to be periodically displayed on screen.