---
source_url: https://www.pubnub.com/docs/sdks/rust/api-reference/configuration
title: Configuration API for Rust SDK
updated_at: 2026-05-20T11:08:14.570Z
sdk_name: PubNub Rust SDK
sdk_version: 0.7.0
---

> 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


# Configuration API for Rust SDK

PubNub Rust SDK, use the latest version: 0.7.0

Install:

```bash
cargo add pubnub@0.7.0
```

Complete API reference for building real-time applications on PubNub with the Rust Software Development Kit (SDK). This page covers configuration, initialization, and event handling with concise, working examples.

##### Available in features

Add any of the following features to `Cargo.toml` to use this API:

```yaml
[dependencies]
# default
pubnub = "0.7.0" 
# full
pubnub = { version = "0.7.0", features = ["full"] }
# Access Manager
pubnub = { version = "0.7.0", features = ["access"] }
# no default features, just Publish 
pubnub = { version = "0.7.0", default-features = false, features = ["publish"] }
# Subscribe
pubnub = { version = "0.7.0", features = ["subscribe"] }
# Presence
pubnub = { version = "0.7.0", features = ["presence"] }
```

For a list of all features, refer to [Available features](https://www.pubnub.com/docs/sdks/rust#available-features).

## Initialization

Use the `PubNubClientBuilder` struct to create and initialize PubNub API clients. The client is transport-agnostic, so you can use any transport that implements the `Transport` trait.

### Method(s)

```rust
let client = PubNubClientBuilder::with_transport(Transport)
    .with_keyset(Keyset {
        publish_key: Some(String),
        subscribe_key: String,
        secret_key: String,
    })
    .with_user_id(String)
    .with_instance_id(Into<String>)
    .with_config(PubNubConfig)
    .with_retry_configuration(RequestRetryConfiguration)
    .with_cryptor(T: CryptoProvider)
    .with_heartbeat_value(u64)
    .with_heartbeat_interval(u64)
    .with_suppress_leave_events(bool)
    .with_filter_expression(String)
    .build()?;
```

To create a PubNub instance, you can use the following methods in the Rust SDK:

| Method | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| with_transport() | Transport | Yes | `with_reqwest_transport()` | Transport layer to use. `with_reqwest_transport()` requires the `reqwest` feature, which is enabled by default. |
| with_keyset() | Keyset | Yes |  | A method that takes the `Keyset` struct with [Admin Portal](https://admin.pubnub.com/) keys as the value. Refer to [Keyset](#keyset) for more information. |
| with_user_id() | String | Yes |  | User ID to use. You should set a unique identifier for the user or the device that connects to PubNub. It's a UTF-8 encoded string of up to 92 alphanumeric characters. If you don't set the User ID, you won't be able to connect to PubNub. |
| with_instance_id() | Into<String> | Optional |  | Client instance ID. |
| with_config() | PubNubConfig | Optional | `Data provided in the builder.` | Struct that allows to overwrite `Keyset` and `user_id` configuration. Useful for working with multiple client builders. |
| with_retry_configuration() | RequestRetryConfiguration | Optional | `RequestRetryConfiguration::None` | Custom reconnection configuration parameters. You can specify one or more [endpoint groups](https://github.com/pubnub/rust/blob/master/src/core/retry_policy.rs) for which the retry policy won't be applied. `RequestRetryConfiguration` is the type of policy to be used. Available values: RequestRetryConfiguration::None, RequestRetryConfiguration::Linear {delay, max_retry, excluded_endpoints}, RequestRetryConfiguration::Exponential {min_delay , max_delay, max_retry, excluded_endpoints} `excluded_endpoints` takes a vector of [enums](https://github.com/pubnub/rust/blob/master/src/core/retry_policy.rs), for example, `excluded_endpoints: Some(vec![Endpoint::Publish])`. For more information, refer to [SDK connection lifecycle](https://www.pubnub.com/docs/general/setup/connection-management#sdk-connection-lifecycle). |
| with_cryptor() | T: | Optional |  | The cryptography module used for encryption and decryption of messages. For detailed encryption configuration and examples, refer to the [Encryption API](https://www.pubnub.com/docs/sdks/rust/api-reference/encryption) page. |
| with_heartbeat_value() | u64 | Optional | `300` | Defines how long the server considers the client alive for presence. This property works similarly to the concept of long polling by sending periodic requests to the PubNub server every `300` seconds by default. These requests ensure the client remains active on subscribed channels. If no heartbeat is received within the timeout period, the client is marked inactive, triggering a "timeout" event on the [presence channel](https://www.pubnub.com/docs/general/presence/overview). The minimum value is `20` seconds. |
| with_heartbeat_interval() | u64 | Optional |  | Specifies how often the client will send heartbeat signals to the server. This property offers more granular control over client activity tracking than `with_heartbeat_value()`. Configure this property to achieve a shorter presence timeout if needed, with the interval typically recommended to be `(with_heartbeat_value() / 2) - 1`. The minimum value is `0` seconds, which means the client doesn't announce itself at all. |
| with_suppress_leave_events() | bool | Optional | `false` | Whether to stop sending presence leave events during the unsubscribe process. |
| with_filter_expression() | String | Optional |  | String used to subscribe with a custom filter. For more information, refer to [Message Filters](https://www.pubnub.com/docs/general/channels/subscribe#message-filters). |
| build() |  | Yes |  | Creates the PubNub instance based on the provided data and returns it. |

#### CryptoModule

CryptoModule implements the `CryptoProvider` trait and encrypts and decrypts messages. From 0.3.0, you can configure the algorithms it uses.

Each SDK includes two options: legacy 128‑bit encryption and recommended 256‑bit AES‑CBC. For background, see [Message Encryption](https://www.pubnub.com/docs/general/setup/data-security#message-encryption).

For configuration details, examples, and partial encryption methods, see [Encryption](https://www.pubnub.com/docs/sdks/rust/api-reference/encryption).

:::note Legacy encryption with 128-bit cipher key entropy
You don't have to change your encryption configuration if you want to keep using the legacy encryption. If you want to use the recommended 256-bit AES-CBC encryption, you must explicitly set that in PubNub config.
:::

#### Keyset

The `Keyset` struct is how you provide your account credentials to the Rust SDK.

| Property | Description |
| --- | --- |
| `publishKey` *Type: `Some(String)` | `publishKey` from the [Admin Portal](https://admin.pubnub.com/). |
| `subscribeKey` *Type: `String` | `subscribeKey` from the Admin Portal. |
| `secretKey`Type: `String` | `secretKey` from the Admin Portal. Required for [Access Manager](https://www.pubnub.com/docs/sdks/rust/api-reference/access-manager) operations. |

### Sample code

:::note Required User ID
Always set the `user_id` to uniquely identify the user or device that connects to PubNub. This `user_id` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `user_id`, you won't be able to connect to PubNub.
:::

```rust
 // to be enabled (default)
 # fn main() -> Result<(), pubnub::core::PubNubError> {
 let pubnub = PubNubClientBuilder::with_reqwest_transport()
    .with_keyset(Keyset {
         publish_key: Some("pub-c-abc123"),
         subscribe_key: "sub-c-abc123",
         secret_key: None,
    })
```

### Returns

A result with PubNub instance or error if the configuration is wrong.

### Other examples

#### Initialize with custom origin

You can initialize the PubNub API client and use a custom domain.

```rust
    let transport = {
        let mut transport = TransportReqwest::default();

        // this is the default server, change it to your custom origin
        transport.set_hostname("https://ps.pndsn.com");

        transport
    };

    let client = PubNubClientBuilder::with_transport(transport)
        .with_keyset(Keyset {
            subscribe_key,
            publish_key: Some(publish_key),
            secret_key: None,
        })
        .with_user_id("user_id")
        .build()?;
```

## Event listeners

PubNub SDKs provide several sources for real-time updates:

* The PubNub client can receive updates from all subscriptions: all channels, channel groups, channel metadata, and users.
* The [Subscription](https://www.pubnub.com/docs/sdks/rust/api-reference/publish-and-subscribe#create-a-subscription) object can receive updates only for the particular object for which it was created: channel, channel group, channel metadata, or user.
* The [SubscriptionsSet](https://www.pubnub.com/docs/sdks/rust/api-reference/publish-and-subscribe#create-a-subscription-set) object can receive updates for all objects for which a list of subscription objects was created.

To work with these sources, the SDK provides local representations of server entities, so you can subscribe and add handlers per entity. For details, see [Publish & Subscribe](https://www.pubnub.com/docs/sdks/rust/api-reference/publish-and-subscribe#event-listeners).

## Terms in this document

* **Access Manager** - A cryptographic, token-based permission administrator that allows you to regulate clients' access to PubNub resources, such as channels, channel groups, and user IDs.
* **Action** - The type of activity (procedure) to execute when a condition is satisfied (for example, sending a message).
* **Billing alert notification** - A means of informing a user that a billing alert has been triggered. Before notifications can happen, a billing alert must be triggered first.
* **Business Object** - A container for data fields and metrics that defines aggregations and data sources.
* **Channel** - A pathway for sending and receiving messages between devices, created automatically when you first use it, that can handle any number of users and messages for different communication needs, like 1-1 text chats, group conversations, and other data streaming.
* **Channel pattern** - A way to group and analyze channel data to track performance metrics like message counts and user engagement over time with PubNub Insights.
* **Condition** - A requirement that must be satisfied or evaluated to true for an action to be executed. Input in a decision table.
* **Cryptor** - An implementation of a specific cryptographic algorithm used for data encryption/decryption that adheres to a standard interface.
* **Dashboard** - A collection of widgets (charts) that give an overview of the metrics one is evaluating.
* **Data fields** - Data you want Illuminate to track. These can be quantitative (measures), like "Number" or "Timestamp" or qualitative (dimensions) values, like "String" that can be used to categorize and segment data. Data fields can be aggregated and calculated.
* **Decision** - A collection (or decision table) of conditions and actions. When conditions are satisfied, the corresponding actions are triggered as per defined rules.
* **End Customer** - A customer of a PubNub partner. End customers do not have direct access to the Admin Portal. Instead, they interact with PubNub products—such as Illuminate—through the partner’s portal, where PubNub services are embedded. They can create PubNub objects only within this partner-provided environment.
* **Entity** - A subscribable object within a PubNub SDK that allows you to perform context-specific operations.
* **Listener** - A function or objectthat reacts to events or messages, like new chat messages or connection updates, letting your app respond in real-time.
* **Mapped/Unmapped** - Whether the data source for a data field has been defined or the action has been configured.
* **MCP Server** - A Model Context Protocol server that coordinates communication and synchronization between AI agents, clients, or services, such as Cursor IDE and Windsurf.
* **Message** - A unit of data transmitted between clients or between a client and a server in PubNub, containing information such as text, binary data, or structured data formats like JSON. Messages are sent over channels and can be tracked for delivery and read status.
* **Metric** - What exactly is evaluated using measures and dimensions (collectively called data fields), as well as aggregation functions.
* **Module** - A Functions v1 container that groups related functions for configuration and deployment on an app’s keysets.
* **Origin** - The subdomain used to establish a connection to the PubNub network that allows your application's traffic to appear like it's coming from your own domain.
* **Package** - A Functions v2 container that groups Functions, tracks Revisions, and is deployed to keysets.
* **Partner** - A PubNub customer who resells PubNub products, such as Illuminate, to their own customers. Partners have access to the Admin Portal, enabling them to create and manage PubNub objects for themselves or on behalf of their end customers.
* **Publish Key** - A unique identifier that allows your application to send messages to PubNub channels. It's part of your app's credentials and should be kept secure.
* **PubNub** - PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including: Message delivery and persistence, Presence detection, Access control, Push notifications, File sharing, Serverless processing with Functions and Events & Actions, Analytics and monitoring with BizOps Workspace, AI-powered insights with Illuminate.
* **Push token** - A device identifier issued by a push provider (APNs or FCM) used to register a device for receiving mobile push notifications.
* **Rule** - A definition (row in a decision table) stating which action should be triggered for which condition.
* **Service Integration** - A machine identity that represents a program or service consuming the Admin API, scoped to your account and authenticated using expirable API keys with configurable permissions.
* **Signal** - A non-persistent message limited to 64 bytes designed for high-volume usecases where the the most recent data is relevant, like GPS location updates.
* **Subscribe Key** - A unique identifier that allows your application to receive messages from PubNub channels. It's part of your app's credentials and should be kept secure.
* **Timetoken** - A unique identifier for each message that represents the number of 100-nanosecond intervals since January 1, 1970, for example, 16200000000000000.
* **Trigger details** - A set of predefined criteria for a given billing alert. When met, billing alert notifications are generated.
* **User** - An individual or entity that interacts with a system, application, or service. In PubNub, a user typically refers to someone who sends or receives messages through the platform, identified by a unique user ID or username.
* **User ID** - UTF-8 encoded, unique string of up to 92 characters used to identify a single client (end user, device, or server) that connects to PubNub.
* **Vibe Coding** - A way to build applications in an intuitive, relaxed, and improvisational manner, using AI tools and natural language descriptions.