Functions Basics
Function versions
This documentation set focuses on Functions v2 for new users. For information about the legacy Functions v1 (superseded by v2) and differences between versions, see the Functions 1.0 Basics.
PubNub Functions enable real‑time data processing by capturing events on the PubNub platform. You can write code or use integrations to transform, route, augment, filter, and aggregate data across applications.
Benefits include:
- Real‑time processing on a global edge network
- Simple, serverless deployment—no infrastructure to manage
- Flexible triggers and integrations for many use cases
Consider counting votes, analytics events, or any metric that must be accurate across many clients. In a traditional database, you would:
- Get the current count from the database.
- Lock the record.
- Increment the count.
- Write the value back and repeat for each instance.
With PubNub Functions, call incrcounter()
. It increments asynchronously and accurately without overwriting other updates.
Creating and managing Functions
Create and manage PubNub Functions in the PubNub Admin Portal. The Admin Portal lets you develop, test, and deploy quickly. It offers:
- A code editor with syntax highlighting and error checking
- Package and revision management
- Easy deployment across multiple keysets
- Built‑in testing and debugging tools
- Access to pre‑built integrations and templates
For step‑by‑step instructions, see Functions in Admin Portal.
Public Admin Portal demo
Want to browse through the Admin Portal without creating an account? Explore it through the Public Demo that shows examples of most PubNub features for transport and logistics use case.
Using wildcards in Functions
You can target a single channel or many channels with patterns.
PubNub Functions support channel wildcards, so one Function can operate on multiple channels with similar names. When you create a Function, choose one of the following for the channel field:
- Specific channel name: Process messages from one exact channel.
- Wildcard channel pattern: Process messages from multiple related channels and reduce the number of Functions you maintain.
PubNub Functions support up to two levels of wildcards in channel patterns:
channelPrefix.*
matches all channels starting withchannelPrefix.
(for example,chat.*
matcheschat.general
,chat.team1
)prefix.level1.*
matches all channels starting withprefix.level1.
(for example,chat.team1.*
matcheschat.team1.general
,chat.team1.private
)
The wildcard must be at the end of the pattern. Wildcards in the middle aren’t supported. This feature requires the Stream Controller add‑on with Enable Wildcard Subscribe
checked in the Admin Portal.
Wildcards help with chat apps (moderating all team channels), IoT (processing data from similar devices), and multi‑tenant apps (consistent logic across customers).
Functions hosting
You don’t need to run servers or call external services that add latency. Your code runs in PubNub’s environment, giving your app the scale and speed it needs.
Functions modules and API
For modules and API details, see the Functions modules and REST API docs.
Performance and limitations
PubNub Functions have tiers that differ by maximum requests per second (RPS) per Function.
On the Free and Starter plans, typical performance is 15 RPS (for example, one XHR, webhook, or log). RPS is an internal measure and varies by Function type.
Starter plan Functions can scale up to 10× in under 20 seconds. Free plan Functions don’t scale. If load exceeds the RPS limit, Functions may time out or run longer.
Need more RPS or compute? Contact sales.
Event types
PubNub Functions can be triggered by many event types. Categories include:
- Before Publish or Fire: Runs on a message before delivery (synchronous).
- After Publish or Fire: Runs on a copy of the message at delivery time; doesn’t return a timetoken (asynchronous).
- Before Publish File: Runs before files are delivered (synchronous).
- After Publish File: Runs on a copy of file messages at delivery time; doesn’t return a timetoken (asynchronous).
- Before Signal: Runs before signals are delivered (synchronous).
- After Signal: Runs on a copy of signals at delivery time; doesn’t return a timetoken (asynchronous).
- After Presence: Runs after presence events (join, leave) (asynchronous).
- On Request: Runs on HTTP requests (synchronous).
- On Interval: Runs on a schedule in milliseconds (asynchronous).
- Subscribe with On Interval: Combines subscribe and interval behavior.
What Function type to use
Synchronous types, such as Before Publish or Fire, run on the original message before delivery. The Function must finish before the message is sent. This can add delay. Calling third‑party systems increases that delay.
Asynchronous types, such as After Publish or Fire, run on a copy of the message and don’t add latency. They can’t change the original message.
Use a synchronous Function if you need to:
- Block a message
- Change a message or its payload
- Change message metadata
- Re‑route a message to a different channel
For most other work, use an asynchronous Function.
You can also use both on the same channel. For example, change messages (synchronous) and send data to an external system (asynchronous). Keep network I/O out of the synchronous Function to minimize latency.
The following sections describe each type.
Before Publish or Fire Functions
These Functions are synchronous.
Use a Before Publish or Fire Function to change a message in‑flight (add a new attribute or modify an existing one). Examples:
- Translate a message from one language to another
- Convert values from Imperial to Metric
- Detect and censor profanity
- Normalize missing or illegal values
After Publish or Fire Functions
These Functions are asynchronous.
Use an After Publish or Fire Function to pass the original message intact and also trigger other logic (such as logging and message teeing). Examples:
- 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 to trigger code before a file message is published to a channel. Examples:
- Evaluate file contents via third‑party AI/ML
- Route the message to a moderator channel if flagged as inappropriate
- Check for copyright issues via a third‑party service and optionally delete from Message Persistence
After Publish File
These Functions are asynchronous.
Use an After Publish File Function to trigger code after a file message is published. Examples:
- Asynchronous file message logging
- File message auditing
- Business metrics gathering
Before Signal Functions
These Functions are synchronous.
Use a Before Signal Function to change signal data in‑flight. Examples:
- Custom logic based on typing state (for example, alert an agent when a customer resumes typing)
- Add typed letters to a phrase dictionary for suggestions
- Integrate geographic data into chat
After Signal Functions
These Functions are asynchronous.
Use an After Signal Function to pass the original signal intact and also trigger other logic (for example, integration with logging services). Examples:
- Asynchronous third‑party message logging (such as Elasticsearch)
- Save typing state in the user profile
- Save location data in the user profile
After Presence Functions
These Functions are asynchronous and trigger on subscriber presence events, not messages. Presence events occur as users connect and disconnect.
Event | Description |
---|---|
join | A user subscribes to a channel. |
leave | A user unsubscribes from a channel. |
timeout | Triggers when a connection drops and the subscriber isn’t seen for 320 seconds (about 5 minutes). Configurable via heartbeat settings. |
state-change | Triggers when state changes using the state API (signature varies by SDK). |
interval | Sends an occupancy count every 10 seconds (default Presence Interval). |
These presence events are also available as callbacks—webhooks called by the Presence service. The callback URI must be publicly accessible. You can manage the callback logic in your own environment or point it to an On Request Function.
Use an After Presence type to pass a presence event intact and also trigger other logic (such as logging and message teeing). Examples:
- Send an SMS to an offline user when someone on their priority list comes online
- Update a KV store with wait times as JOIN and LEAVE events occur
- Monitor a user’s online/offline time card
On Request Functions
These Functions are synchronous.
On Request Functions let you create publicly accessible REST API methods. You can also call On Request Functions from other Functions (as a replacement for pubnub.fire()
). Benefits include:
- Break a main Function into smaller components
- Define a utility Function called by many other Functions
- Return data to the calling Function
On Interval Functions
These Functions are asynchronous.
On Interval Functions let you run logic automatically at a set interval. This makes it easy to move scheduled work from other systems into PubNub. Examples:
- Periodically update KV store cache data from message history
- Periodically send packaged‑up message data to an external service
- Periodically update 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 isn’t available to all users. If you’d like access, contact support.
Subscribe with On Interval lets you subscribe to traffic and run code at intervals in response. Use it for logic that reacts periodically to subscribe traffic.
Examples:
- Throttle messages and reroute to a different channel that Events & Actions can store for analysis
- Aggregate message reactions and display them on a schedule