---
source_url: https://www.pubnub.com/docs/serverless/functions/overview
title: Functions Basics
updated_at: 2026-05-21T15:48:11.948Z
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Functions 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.

Functions are included in every [PubNub plan](https://www.pubnub.com/pricing/) and offer the following benefits:

* Real‑time processing on a global edge network
* Simple, serverless deployment—no infrastructure to manage
* Flexible triggers and integrations for many use cases

##### Watering digital plants, quenching real problems!

Edward, the engineering lead, was tasked with a unique marketing challenge that truly put his skills to the test. The mission involved a digital billboard in Metropolis, part of a game on the company's website. It displayed a wilting plant that players could attempt to revive using a virtual plastic bottle or a well (the latter being an eco-friendlier choice). The company's aim was to reward players who chose the well and engaged with it for at least five minutes with water purifier vouchers. The major hurdle, however, was the automatic tracking of game time and voucher distribution.

Considering potential solutions, Edward thought of PubNub and their Functions. He shared his idea with Bianca, a colleague well-acquainted with PubNub's real-time communication platform from previous projects. She was convinced that they could reliably gather game-time data and handle reward distribution at scale.

"Could we integrate this with our system?" - asked Bianca.

Edward replied, "Yes. They seem to have an abundance of [integrations](https://www.pubnub.com/integrations/)."

With a shared sense of purpose and understanding, they dove into the docs, driven by the image of the wilting plant as a potent reminder of their mission's significance.

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()](https://www.pubnub.com/docs/serverless/functions/functions-apis/kvstore-module#counters). It increments asynchronously and accurately without overwriting other updates.

## Creating and managing Functions

Create and manage PubNub Functions in the [PubNub Admin Portal](https://www.pubnub.com/docs/serverless/functions/functions-in-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](https://www.pubnub.com/docs/serverless/functions/functions-in-admin-portal).

:::tip Public Admin Portal demo
Want to browse through the Admin Portal without creating an account? Explore it through the [Public Demo](https://demo-admin.pubnub.com/) 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 with `channelPrefix.` (for example, `chat.*` matches `chat.general`, `chat.team1`)
* `prefix.level1.*` matches all channels starting with `prefix.level1.` (for example, `chat.team1.*` matches `chat.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](https://www.pubnub.com/docs/general/channels/subscribe#configuration) checked in the Admin Portal.

[Wildcards](https://www.pubnub.com/docs/general/channels/subscribe#wildcard-subscribe) help with chat apps (moderating all team channels), IoT (processing data from similar devices), and multi‑tenant apps (consistent logic across customers).

###### Get more from Functions with channel naming conventions

The channel pattern you assign to a Function determines which messages trigger it. Design your [channel naming conventions](https://www.pubnub.com/docs/general/channels/channel-naming) with dot-delimited prefixes so that wildcard bindings group related channels naturally. For example, naming chat channels `chat.team1`, `chat.team2` lets a single Function bound to `chat.*` process all team messages. See [Channel Basics](https://www.pubnub.com/docs/general/channels/overview) for channel creation, limits, and types.

## 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.

:::note Functions modules and API
For modules and API details, see the [Functions modules](https://www.pubnub.com/docs/serverless/functions/functions-apis/functions-libraries) and [REST API](https://www.pubnub.com/docs/serverless/functions/functions-rest-api/functions-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](https://www.pubnub.com/pricing/), 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](https://www.pubnub.com/company/contact-sales/).

## Export Functions logs

Any running Function publishes its logs to an internal channel following the pattern `output-rev-{{functionRevisionId}}-key-{{keysetId}}`, like `output-rev-NSPiAuYKsWSxJl4yBn30-key-abc123` (you can find this channel name in the Console output).

A Function publishes only the first 250 log lines per replica. By default, there is 1 replica in each region, and there are 5 regions, which gives a total of up to 1250 log lines.

To retain logs, export them with [Events & Actions](https://www.pubnub.com/docs/serverless/events-and-actions/overview) via [Webhook](https://www.pubnub.com/docs/serverless/events-and-actions/actions/create-webhook-action) or [S3](https://www.pubnub.com/docs/serverless/events-and-actions/actions/create-s3-action).

To do that, follow these steps:

1. Set up an event listener to listen for events on the internal channel. Provide the following configuration and enter the correct output-rev-* channel from the Console output in the Condition value field.
2. Create either a Webhook or S3 action and add the created event listener to it. When configuring this action, you can use the Batching feature to send multiple events in a single request.

## Event types

PubNub Functions can be triggered by many event types. Categories include:

###### Process published messages with Functions

The most common Function triggers act on [messages](https://www.pubnub.com/docs/general/messages/overview). Before Publish Functions intercept messages in flight for transformation, validation, or enrichment. After Publish Functions process a copy of delivered messages for logging, forwarding, or aggregation. See [Message Publish](https://www.pubnub.com/docs/general/messages/publish) for how messages and metadata are structured and [Message Types](https://www.pubnub.com/docs/general/messages/type) for conventions that enable conditional processing within your Function code.

* **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.

###### Understand timetoken behavior in synchronous and asynchronous Functions

Before Publish Functions execute synchronously and return a timetoken to the publishing client upon completion. After Publish Functions run asynchronously on a copy of the delivered message and do not return a timetoken. The message's timetoken is available in the [Function execution context](https://www.pubnub.com/docs/serverless/functions/functions-apis/pubnub-module) for both types, letting your code reference the exact publish time for logging, routing, or conditional logic.

### What Function type to use

Synchronous types, such as [Before Publish or Fire](#before-publish-or-fire-functions), 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](#after-publish-or-fire-functions), 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

###### Personalize Function logic with User IDs

Every After Presence event includes the [User ID](https://www.pubnub.com/docs/general/setup/users-and-devices) of the subscriber who joined, left, or timed out. Your Function code can use this identifier to personalize responses, update per-user state in the [KV store](https://www.pubnub.com/docs/serverless/functions/functions-apis/kvstore-module), or route notifications to user-specific channels. For user identity strategy and multi-device considerations, see [Users & Devices](https://www.pubnub.com/docs/general/setup/users-and-devices).

### 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

:::note 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](https://www.pubnub.com/docs/general/setup/users-and-devices#set-the-user-id).
:::

### Subscribe with On Interval Functions

These Functions are asynchronous.

:::note Limited availability
This Function type isn’t available to all users. If you’d like access, contact [support](https://www.pubnub.com/docs/mailto:support@pubnub.com).
:::

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](https://www.pubnub.com/docs/serverless/events-and-actions/overview) can store for analysis
* Aggregate message reactions and display them on a schedule