---
source_url: https://www.pubnub.com/docs/sdks/kotlin/api-reference/configuration
title: Configuration API for Kotlin SDK
updated_at: 2026-05-27T17:02:48.777Z
sdk_name: PubNub Kotlin SDK
sdk_version: 13.3.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 Kotlin SDK

PubNub Kotlin SDK, use the latest version: 13.3.0

Install:

```bash
Add PubNub dependency to your build@13.3.0
```

:::warning Breaking changes in v9.0.0
PubNub Kotlin SDK version 9.0.0 unifies the codebases for Kotlin and [Java](https://www.pubnub.com/docs/sdks/java) SDKs, introduces a new way of instantiating the PubNub client, and changes asynchronous API callbacks and emitted [status events](https://www.pubnub.com/docs/sdks/kotlin/status-events). These changes can impact applications built with previous versions (< `9.0.0` ) of the Kotlin SDK.
For more details about what has changed, refer to [Java/Kotlin SDK migration guide](https://www.pubnub.com/docs/sdks/kotlin/migration-guides/kotlin-v9-migration-guide).
:::

Kotlin complete API reference for building real-time applications on PubNub, including basic usage and sample code.

:::tip Request execution
Most PubNub Kotlin SDK method invocations return an Endpoint object, which allows you to decide whether to perform the operation synchronously or asynchronously.
You must invoke the `.sync()` or `.async()` method on the Endpoint to execute the request, or the operation **will not** be performed.
```kotlin
val channel = pubnub.channel("channelName")
channel.publish("This SDK rules!").async { result ->
    result.onFailure { exception ->
        // Handle error
    }.onSuccess { value ->
        // Handle successful method result
    }
}
```
:::

## Configuration

`PNConfiguration` instance is storage for user-provided information which describes further PubNub client behavior. The configuration instance contains additional set of properties which allow performing precise PubNub client configuration.

:::warning Immutable configuration
Once a configuration object has been passed to the PubNub constructor, you can't change its properties.
If you require changing values dynamically consider using [value overrides](#value-override).
:::

### Method(s)

```kotlin
val builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
    // config options
}
val pubnub = PubNub.create(builder.build())
```

To create a `pnConfiguration` instance you can use the following properties in the Kotlin SDK:

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| subscribeKey | String | Yes |  | `subscribeKey` from the Admin Portal. |
| publishKey | String | Optional |  | `publishKey` from the Admin Portal (only required if publishing). |
| secretKey | String | Optional |  | `secretKey` (only required for access operations, keep away from Android). |
| userId | UserId | Yes |  | `userId` to use. The `UserId` object takes `String` as an argument. 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 `userId`, you won't be able to connect to PubNub. |
| customLoggers | List<CustomLogger> | Optional |  | Your custom logger implementations. See [Logging](https://www.pubnub.com/docs/sdks/kotlin/logging). |
| cacheBusting | Boolean | Optional | `false` | If operating behind a misbehaving proxy, allow the client to shuffle the subdomains. |
| secure | Boolean | Optional | `true` | When `true`, TLS is enabled. |
| connectTimeout | Int | Optional | `5` | Maximum time to establish a connection, in seconds. |
| subscribeTimeout | Int | Optional | `310` | Subscribe request timeout, in seconds. |
| nonSubscribeRequestTimeout | Int | Optional | `10` | Non-subscribe request timeout, in seconds. |
| filterExpression | String | Optional |  | Subscribe with a custom filter expression. |
| heartbeatNotificationOptions | PNHeartbeatNotificationOptions | Optional | `PNHeartbeatNotificationOptions.FAILURES` | Heartbeat notification options. By default, the SDK alerts on failed heartbeats (equivalent to `PNHeartbeatNotificationOptions.FAILURES`). Other options including all heartbeats (`PNHeartbeatNotificationOptions.ALL`) and no heartbeats (`PNHeartbeatNotificationOptions.NONE`). |
| origin | String | Optional |  | Custom origin if needed. To request a custom domain, contact support and follow the [request process](https://www.pubnub.com/docs/general/setup/data-security#request-process). |
| presenceTimeout | Int | Optional | `300` | How long the server considers the client alive for presence. The client sends periodic heartbeats to stay active. If no heartbeat arrives within the timeout, the client is marked inactive and a "timeout" event is emitted on the [presence channel](https://www.pubnub.com/docs/general/presence/overview). Minimum `20` seconds. Updates `heartbeatInterval` when set. |
| heartbeatInterval | Int | Optional | `0` | How often the client sends heartbeats. To shorten presence timeout, set roughly to `(presenceTimeout / 2) - 1`. Minimum `3`. Default `0` (disabled). |
| proxy | Proxy | Optional |  | Instructs the SDK to use a proxy configuration when communicating with PubNub servers. For more details refer to [Oracle documentation.](https://docs.oracle.com/javase/7/docs/api/java/net/Proxy.html) |
| proxySelector | ProxySelector | Optional |  | Sets Java ProxySelector. For more details, refer to [Oracle documentation](https://docs.oracle.com/javase/7/docs/api/java/net/ProxySelector.html). |
| proxyAuthenticator | Authenticator | Optional |  | Sets Java Authenticator. For more details refer to [Oracle documentation](https://docs.oracle.com/javase/7/docs/api/java/net/Authenticator.html) |
| googleAppEngineNetworking | Boolean | Optional |  | Enable Google App Engine networking. |
| suppressLeaveEvents | Boolean | Optional | `false` | When `true` the SDK doesn't send out the `leave` requests. []() |
| retryConfiguration | RetryConfiguration | Optional | `RetryConfiguration.Exponential (subscribe only)` | Custom reconnection configuration parameters. You can specify one or more [endpoint groups](https://github.com/pubnub/kotlin/blob/master/pubnub-kotlin/pubnub-kotlin-core-api/src/commonMain/kotlin/com/pubnub/api/retry/RetryableEndpointGroup.kt) for which the retry policy won't be applied. `RetryConfiguration` is the type of policy to be used. Available values: RetryConfiguration.None, RetryConfiguration.Linear(delayInSec, maxRetryNumber, excludedOperations, RetryConfiguration.Exponential(minDelayInSec, maxDelayInSec, maxRetryNumber, excludedOperations `excludedOperations` takes a list of `RetryableEndpointGroup` [enums](https://github.com/pubnub/kotlin/blob/master/pubnub-kotlin/pubnub-kotlin-core-api/src/commonMain/kotlin/com/pubnub/api/retry/RetryableEndpointGroup.kt), for example, `RetryableEndpointGroup.SUBSCRIBE`. For more information, refer to [SDK connection lifecycle](https://www.pubnub.com/docs/general/setup/connection-management#sdk-connection-lifecycle). |
| maintainPresenceState | Boolean | Optional | `true` | Whether the custom presence state information set using [pubnub.setPresenceState()](https://www.pubnub.com/docs/sdks/kotlin/api-reference/presence#set-state) should be sent every time the SDK sends a subscribe call. |
| cryptoModule | CryptoModule.createAesCbcCryptoModule(cipherKey) | Optional | `None` | The cryptography module used for encryption and decryption of messages and files. Takes the `cipherKey` parameter as argument. For more information, refer to the [cryptoModule](#cryptomodule) section. |
| includeInstanceIdentifier | Boolean | Optional | `false` | Whether to include a `PubNubCore.instanceId` with every request. |
| includeRequestIdentifier | Boolean | Optional | `true` | Whether to include a `PubNubCore.requestId` with every request. |
| maximumConnections | Int? | Optional |  | Configures the maximum number of inbound concurrent connections that PubNub will handle. |
| connectionPoolMaxIdleConnections | Int | Optional | `5` | Maximum number of idle connections to keep in the HTTP connection pool. When set to `0`, connection pooling is disabled and connections are closed immediately after use. Refer to [OkHttp's ConnectionPool documentation](https://square.github.io/okhttp/5.x/okhttp/okhttp3/-connection-pool/index.html) for more details. |
| connectionPoolKeepAliveDuration | Int | Optional | `300` | How long to keep idle connections alive in the HTTP connection pool before evicting them, in seconds. Refer to [OkHttp's ConnectionPool documentation](https://square.github.io/okhttp/5.x/okhttp/okhttp3/-connection-pool/index.html) for more details. |
| certificatePinner | CertificatePinner | Optional |  | Manages SSL certificates for HTTPS requests. For more details, see [OkHttp's CertificatePinner documentation](https://square.github.io/okhttp/3.x/okhttp/okhttp3/CertificatePinner.html). |
| sslSocketFactory | SSLSocketFactory | Optional |  | Custom SSLSocketFactory used for HTTPS connections. |
| x509ExtendedTrustManager | X509ExtendedTrustManager | Optional |  | Custom X509ExtendedTrust Manager to manage which X509 certificates may be used to authenticate the remote side of a secure socket. |
| connectionSpec | ConnectionSpec | Optional |  | Specifies which TLS versions and cipher suites are supported for HTTPS. See [ConnectionSpec](https://square.github.io/okhttp/5.x/okhttp/okhttp3/-connection-spec/index.html). |
| hostnameVerifier | HostnameVerifier | Optional |  | Hostname Verifier, checks whether the hostname is allowed within an SSL session. |
| dedupOnSubscribe | Boolean | Optional |  | Indicates if message deduplication feature is enabled on subscription. |
| maximumMessagesCacheSize | Int | Optional |  | Specifies the maximum size of the messages cache. |
| pnsdkSuffixes | Map<String, | Optional |  | Maps custom suffixes for SDK identification headers. |
| managePresenceListManually | Boolean | Optional |  | Enables explicit manual management of presence list. Used with ACL on the server-side. |
| authKey | String | Optional |  | This parameter is deprecated. Refer to [Manage Access](https://www.pubnub.com/docs/general/security/access-control) to understand the permission authorization flow and to Kotlin [Access Manager API](https://www.pubnub.com/docs/sdks/kotlin/api-reference/access-manager) for an overview of the API. If Access Manager v2 is utilized, client will use this authKey in all restricted requests. |

#### cryptoModule

`cryptoModule` encrypts and decrypts messages and files. From 7.6.0, you can configure the algorithms it uses. By default, encryption is disabled.

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) and [File Encryption](https://www.pubnub.com/docs/general/setup/data-security#file-encryption).

For configuration details, utilities, and examples, see [Encryption](https://www.pubnub.com/docs/sdks/kotlin/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.
:::

### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

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

```kotlin
import com.pubnub.api.UserId
import com.pubnub.api.crypto.CryptoModule
import com.pubnub.api.enums.PNHeartbeatNotificationOptions
import com.pubnub.api.logging.CustomLogger
import com.pubnub.api.logging.LogMessage
import com.pubnub.api.retry.RetryConfiguration
import com.pubnub.api.v2.PNConfiguration

fun main() {
    println("PubNub Configuration Example")
    println("============================")

    // Create a basic configuration
    val basicConfig = createBasicConfig()
    println("\n1. Basic Configuration (Required Parameters)")
    printConfigDetails(basicConfig)

    // Create an advanced configuration
    val advancedConfig = createAdvancedConfig()
    println("\n2. Advanced Configuration (With Optional Parameters)")
    printConfigDetails(advancedConfig)

    // Create a configuration with encryption
    val encryptedConfig = createEncryptedConfig()
    println("\n3. Configuration with Encryption")
    printConfigDetails(encryptedConfig)

    println("\nNote: In a real application, you would use:")
    println("val pubnub = PubNub.create(config)")
    println("to create the PubNub instance with your configuration.")
}

/**
 * Creates a basic PubNub configuration with only the required parameters
 */
fun createBasicConfig(): PNConfiguration {
    val userId = UserId("basic-user-id")
    val builder = PNConfiguration.builder(userId, "demo").apply {
        // The publishKey is required if you want to publish messages
        publishKey = "demo"

        // These are the minimum required parameters to initialize PubNub
    }
    return builder.build()
}

/**
 * Creates an advanced PubNub configuration with various optional parameters
 */
fun createAdvancedConfig(): PNConfiguration {
    val userId = UserId("advanced-user-id")
    val builder = PNConfiguration.builder(userId, "demo").apply {
        // Basic parameters
        publishKey = "demo"

        // Connection parameters
        connectTimeout = 10 // Connection timeout in seconds
        subscribeTimeout = 310 // Subscribe request timeout in seconds
        nonSubscribeReadTimeout = 10 // Timeout for non-subscribe operations

        // Security parameter
        secure = true // Enable TLS (true by default)

        // Presence parameters
        presenceTimeout = 300 // How long the server considers client alive for presence
        heartbeatInterval = 150 // How often client sends heartbeat signals
        suppressLeaveEvents = false // Whether to send leave events when disconnecting

        // Debugging parameters
        customLoggers = listOf(MyCustomLoggerImpl()) // Add custom loggers if needed

        // Retry configuration (for reconnection)
        retryConfiguration = RetryConfiguration.Linear(
            delayInSec = 3, // Retry with fixed delay of 3 seconds
            maxRetryNumber = 5 // Maximum 5 retry attempts
        )

        // Notification options
        heartbeatNotificationOptions = PNHeartbeatNotificationOptions.ALL
    }
    return builder.build()
}

/**
 * When config options of slf4j implementation of your choice like logback or log4j don't meet you logging requirements implement CustomLogger and pass implementation to PNConfiguration.customLoggers
 */
class MyCustomLoggerImpl : CustomLogger {
    override val name: String = "MyCustomLoggerImpl"

    override fun trace(message: String?) {
        stringMessages.add(message ?: "")
    }

    override fun trace(message: LogMessage) {
        logMessages.add(message)
    }

    override fun debug(message: String?) {
        stringMessages.add(message ?: "")
    }

    override fun debug(logMessage: LogMessage) {
        logMessages.add(logMessage)
    }

    companion object {
        val stringMessages = mutableListOf<String>()
        val logMessages = mutableListOf<LogMessage>()

        fun clear() {
            stringMessages.clear()
            logMessages.clear()
        }
    }
}

/**
 * Creates a PubNub configuration with encryption enabled
 */
fun createEncryptedConfig(): PNConfiguration {
    val userId = UserId("encrypted-user-id")
    val builder = PNConfiguration.builder(userId, "demo").apply {
        publishKey = "demo"

        // Enable message encryption with 256-bit AES-CBC (recommended)
        cryptoModule = CryptoModule.createAesCbcCryptoModule("my-secret-key")

        // Alternatively, for legacy compatibility:
        // cryptoModule = CryptoModule.createLegacyCryptoModule("my-secret-key")
    }
    return builder.build()
}

/**
 * Prints the details of a configuration object
 */
fun printConfigDetails(config: PNConfiguration) {
    println("  • User ID: ${config.userId}")
    println("  • Subscribe Key: ${config.subscribeKey}")
    println("  • Publish Key: ${config.publishKey}")
    println("  • Secure: true (default)")

    // Determine if encryption is enabled
    val encryptionEnabled = config.cryptoModule != null
    if (encryptionEnabled) {
        println("  • Encryption: Enabled")
    } else {
        println("  • Encryption: Disabled")
    }

    // Note: We can't access all configuration properties directly
    // as some are private within the PNConfiguration object
}
```

### Value override

You can provide updated values for certain configuration options for a single request to any supported API with `overrideConfiguration`.

```kotlin
// publish
pubNub.publish("myChannel", "mymessage").overrideConfiguration {
    publishKey = "overridePublishKey"
}.sync()
```

The configuration options you can override include:

* `subscribeKey`
* `publishKey`
* `secretKey`
* `retryConfiguration`
* `userId`
* `includeInstanceIdentifier`
* `includeRequestIdentifier`
* `cryptoModule`
* `connectTimeout`
* `nonSubscribeReadTimeout`

## Initialization

Add PubNub to your project using one of the procedures in [Getting Started](https://www.pubnub.com/docs/sdks/kotlin).

### Description

Initialize the PubNub Client API before using any APIs. This sets account-level credentials such as `publishKey` and `subscribeKey`.

### Methods

Initialize PubNub with:

```kotlin
val builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
    publishKey = "publishKey"
}

val pubnub = PubNub.create(builder.build())
```

| Parameter | Description |
| --- | --- |
| `builder` *Type: `PNConfiguration` | Refer to [configuration](#configuration) for more details. |

### Sample code

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

```kotlin
val builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
    publishKey = "publishKey"
}

val pubnub = PubNub.create(builder.build())
```

### Returns

Returns the PubNub instance to call APIs such as `publish()`, `subscribe()`, `history()`, and `hereNow()`.

### Other examples

#### Initialize a non-secure client

```kotlin
val builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
    publishKey = "publishKey"
    secure = false
}
val pubnub = PubNub.create(builder.build())
```

#### Initialization for a Read-Only client

```kotlin
val builder = PNConfiguration.builder(UserId("abc"), "subscribeKey")
val pubnub = PubNub.create(builder.build())
```

#### Initializing with SSL enabled

This example demonstrates how to enable PubNub Transport Layer Encryption with `SSL`. Just initialize the client with `secure` set to `true`. The hard work is done, now the PubNub API takes care of the rest. Just subscribe and publish as usual and you are good to go.

```kotlin
val builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
    publishKey = "publishKey"
    secretKey = "SecretKey"
    secure = true
}
val pubnub = PubNub.create(builder.build())
```

#### Initializing with Access Manager

:::note Requires Access Manager add-on
This method requires that the *Access Manager* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

:::note Secure your secretKey
Anyone with the `secretKey` can grant and revoke permissions to your app. Never let your `secretKey` be discovered, and to only exchange it / deliver it securely. Only use the `secretKey` on secure server-side platforms.
When you init with `secretKey`, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.
:::

For applications that will administer Access Manager permissions, the API is initialized with the `secretKey` as in the following example:

```kotlin
val builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
    publishKey = "publishKey"
    secretKey = "SecretKey"
    secure = true
}
val pubnub = PubNub.create(builder.build())
```

Now that the `pubnub` object is instantiated the client will be able to access the Access Manager functions. The `pubnub` object will use the secretKey to sign all Access Manager messages to the PubNub Network.

#### How to set proxy

```kotlin
val builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
    publishKey = "publishKey"
    secretKey = "SecretKey"
    proxy = Proxy(
        Proxy.Type.HTTP,
        InetSocketAddress("http://mydomain.com", 8080)
    )
}
val pubnub = PubNub.create(builder.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 metadata.
* The [Subscription](https://www.pubnub.com/docs/sdks/kotlin/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/kotlin/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/kotlin/api-reference/publish-and-subscribe#event-listeners).

## UserId

These functions are used to set/get a user ID on the fly.

### Method(s)

To set/get `userId` you can use the following method(s) in the Kotlin SDK:

```kotlin
// Getting the userId
val userId = pubnub.configuration.userId.value
```

```kotlin
// Setting the userId during initialization
val builder = PNConfiguration.builder(UserId("abc"), "subscribeKey")
val pubnub = PubNub.create(builder.build())

// Setting the userId after initialization
val pnConfigurationWithModifiedUserId: PNConfiguration = PNConfigurationOverride.from(pubnub.configuration).apply {
    userId = UserId("new-user-id")
}.build()
```

| Parameter | Description |
| --- | --- |
| `userId` *Type: `UserId`Default: n/a | `userId` to be used as a device identifier. The `UserId` object takes `String` as an argument. If you don't set the `userId`, you won't be able to connect to PubNub. |

### Sample code

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

#### Set UserId

```kotlin
// Setting the userId during initialization
val builder = PNConfiguration.builder(UserId("abc"), "subscribeKey")
val pubnub = PubNub.create(builder.build())

// Setting the userId after initialization
val pnConfigurationWithModifiedUserId: PNConfiguration = PNConfigurationOverride.from(pubnub.configuration).apply {
    userId = UserId("new-user-id")
}.build()
```

#### Get UserId

```kotlin
val builder = PNConfiguration.builder(UserId("abc"), "subscribeKey")
val pubnub = PubNub.create(builder.build())

val userId: UserId = pubnub.configuration.userId
```

## Filter expression

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

Stream filtering allows a subscriber to apply a filter to only receive messages that satisfy the conditions of the filter. The message filter is set by the subscribing client(s) but it is applied on the server side thus preventing unwanted messages (those that do not meet the conditions of the filter) from reaching the subscriber.

To set or get message filters, you can use the following method. To learn more about filtering, refer to the [Publish Messages](https://www.pubnub.com/docs/general/messages/publish) documentation.

### Method(s)

```kotlin
val builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
    publishKey = "publishKey"
    filterExpression = "such=wow"
}
val pubnub = PubNub.create(builder.build())
```

| Parameter | Description |
| --- | --- |
| `filterExpression` *Type: `String` | PSV2 feature to `subscribe` with a custom filter expression. |

### Sample code

```kotlin
val builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
    publishKey = "publishKey"
    filterExpression = "such=wow"
}
val pubnub = PubNub.create(builder.build())
```

## Terms in this document

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