---
source_url: https://www.pubnub.com/docs/sdks/kotlin/api-reference/data-sync
title: DataSync API for Kotlin SDK
updated_at: 2026-10-08T04:47:34.000Z
sdk_name: PubNub Kotlin SDK
sdk_version: 14.0.0
---

# DataSync API for Kotlin SDK

PubNub Kotlin SDK, use the latest version: 14.0.0

Install:

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

> For AI agents: documentation index at https://www.pubnub.com/llms-full.txt

[DataSync](https://www.pubnub.com/docs/data-storage/structured-data/overview.md) is PubNub's data layer for storing application state (users, channels, memberships, and any custom object type) and keeping every connected client current through real-time events. Use it to model the objects your application works with and to react the moment they change.

DataSync is the successor to [App Context](https://www.pubnub.com/docs/sdks/kotlin/api-reference/objects.md).

:::note DataSync entities and SDK entities are different things
This page is about **DataSync entities**, the records the service stores and treats as the source of truth for your application state. They are created and read through the `pubnub.dataSync.*` methods documented here.
An **SDK entity** is a local client-side handle such as `pubnub.channel("room-1")`. It carries no stored state of its own, it just gives you a scoped surface for subscribing and calling APIs. Refer to the [Channel SDK entity](https://www.pubnub.com/docs/sdks/kotlin/entities/channel.md).
The two meet in the DataSync SDK entities ([DataSyncUser](https://www.pubnub.com/docs/sdks/kotlin/entities/data-sync-user.md), [DataSyncChannel](https://www.pubnub.com/docs/sdks/kotlin/entities/data-sync-channel.md), and [DataSyncEntity](https://www.pubnub.com/docs/sdks/kotlin/entities/data-sync-entity.md)): SDK entities whose only job is to subscribe to a DataSync object's real-time updates.
:::

The classes that your objects conform to (their types and schemas) are defined through the Admin API or the [Admin Portal](https://admin.pubnub.com/), not through this SDK:

* Entity classes, which back users, channels, and custom entities: [list](https://www.pubnub.com/docs/admin-api/get-all-entity-class-entries.md), [read](https://www.pubnub.com/docs/admin-api/get-entity-class-by-id.md), [create](https://www.pubnub.com/docs/admin-api/create-a-new-entity-class.md), [replace](https://www.pubnub.com/docs/admin-api/update-entity-class-with-complete-resource-replacement.md), and [delete](https://www.pubnub.com/docs/admin-api/delete-entity-class-by-id.md). Partial updates aren't implemented; replace the complete class version instead.
* Relationship classes, which back memberships and custom relationships: [list](https://www.pubnub.com/docs/admin-api/get-all-relationship-classes.md), [read](https://www.pubnub.com/docs/admin-api/get-relationship-class-by-name-and-version.md), [create](https://www.pubnub.com/docs/admin-api/create-a-new-relationship-class.md), [replace](https://www.pubnub.com/docs/admin-api/update-relationship-class-with-complete-resource-replacement.md), and [delete](https://www.pubnub.com/docs/admin-api/delete-relationship-class-by-name-and-version.md).

`User` and `Channel` entity classes and the `Membership` relationship class are predefined on every keyset, so you only need to define classes for your own custom entities and relationships.

A class definition is what decides, for every object of that class, which `payload` fields are filterable and sortable, which [projection](https://www.pubnub.com/docs/sdks/kotlin/api-reference/access-manager.md#grant-token) each field belongs to, and how long the object lives before it expires. Refer to [managing classes](https://www.pubnub.com/docs/data-storage/structured-data/schemas.md#managing-classes) for more information.

Every DataSync method returns an endpoint object, and a successful call yields a result object carrying the HTTP `status`. The `remove*` methods return the status on its own, every other method adds a `data` property holding the object, or the list of objects for a list method. A list method also adds a `next` property holding the pagination state. The SDK does not surface the HATEOAS `links` the service sends. A stored object carries its free-form `status` and its `expiresAt` auto-deletion timestamp (ISO 8601) whenever those are set on it. A failed call surfaces as a `PubNubException` whose `statusCode` is the HTTP status, for example `412`, and whose `pubnubError` is a `DATASYNC_*` category chosen from that status. Read the `DS-` error code with `dataSyncErrorCode()`, or every error item with `dataSyncErrors()`. The raw response body stays in `errorMessage` and `jso`. A response that carries no `DS-` code keeps the generic `HTTP_ERROR` category. You pass `payload` as any value that serializes to a JSON object, such as a `Map`, and read it back as a `Map<String, Any?>`.

### Authorization

Every DataSync request must be [authorized](https://www.pubnub.com/docs/data-storage/structured-data/access-control.md#authorizing-requests) with a token or signature. A request with no credential fails with a `401`; an invalid credential or a credential that doesn't permit the operation fails with a `403`.

A signature means the client is configured with a `secretKey`, and the SDK then signs every request with it automatically. Never put a secret key in a client-side application, use it only on a server you control. Give client-side applications a token from [grantToken()](https://www.pubnub.com/docs/sdks/kotlin/api-reference/access-manager.md#grant-an-authorized-client-access-to-datasync-resources) instead, set with `setToken()`.

### Pagination

DataSync pagination is **forward-only**. There is no previous-page cursor, and `PNDataSyncPage` exposes no `prevCursor` or `hasPrev`. To revisit an earlier page, page from the start again.

All list methods (`getUsers`, `getChannels`, `getMemberships`, `getEntities`, and `getRelationships`) accept `cursor` and `limit` (default `20`, max `100`) and return a `next` property of type `PNDataSyncPage` with `hasNext`, `cursor`, and `limit`. The `next` property is never `null`, it is an empty page when the server sends no pagination details, so read `hasNext` rather than checking `next` for `null`.

To page forward, pass the returned `next.cursor` back as `cursor` on the next call, and stop when `next.hasNext` is `false`. `next.cursor` is `null` on the last page. Refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination) for details.

### Filtering and sorting

All list methods accept two mutually exclusive filter parameters, `filterFast` and `filter`. The SDK sends whatever you pass, so a call that carries both reaches the server and fails there with a `400`.

| Parameter | Consistency | Properties it can read | Expression complexity |
| --- | --- | --- | --- |
| `filterFast` | Strongly consistent, reflects the latest writes | Filtering mode `simple` or `full` | Up to 10 conditions by default (raisable per keyset) |
| `filter` | Eventually consistent, results can briefly lag writes | Filtering mode `full` only | Full expression language |

Reach for `filterFast` when the query has to see an object you just wrote, and for `filter` when you need the full expression language over a `full`-indexed property.

:::warning danger
filter
is not the strongly consistent one
The two names read the wrong way round if you assume `filter` is the basic option. `filterFast` is the strongly consistent, limited one. `filter` is the richer, eventually consistent one.
:::

Both parameters share the same expression language, a string built from a property name, an operator, and a value:

| Operators |  |
| --- | --- |
| Comparison | `==`, `!=`, `<`, `>`, `<=`, `>=` |
| Pattern matching | `LIKE` (case-insensitive), `SLIKE` (case-sensitive), `ILIKE` (case-insensitive, same as `LIKE`) |
| Logical | `&&`, `||`, `!`, and parentheses for grouping |

Values are quoted strings, numbers, `true`, `false`, or `null`. Pattern operators (`LIKE`, `SLIKE`, `ILIKE`) apply to string properties only, and `null` is only valid with `==` and `!=`. Reference a property by its `name`, not its declared `path`, and only properties declared on the class are filterable. To reach a nested `payload` property, declare it as a class property first, then filter by that property's `name`, for example `"price < 100"` for a `product` class that declares `price`.

Some examples:

```kotlin
filterFast = "price < 100"                               // strongly consistent, single condition
filterFast = "(price < 100 && stock > 0) || price > 500" // strongly consistent, grouped conditions
filter = "name LIKE \"*sneaker*\""                       // eventually consistent, needs filtering mode "full"
filter = "!(status == \"discontinued\")"                 // eventually consistent, negated condition
```

Both parameters only work over properties declared on the class, plus the built-in `id`, `createdAt`, `updatedAt`, and `status` fields, which are always filterable and sortable without being declared. `eTag` and `expiresAt` are neither. The `status` exception does not hold if the class redeclares `/status` scoped to projections your token cannot fully reach. When you don't pass `classVersion`, the list includes items of every version, but `filter`, `filterFast`, and `sort` can only use properties declared on the latest version of the class. A property that exists only in an older version is rejected with a `400`. Pass `classVersion` to use properties declared on an older version. Refer to [filtering](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#filtering) for the two filtering tiers, and [property definitions](https://www.pubnub.com/docs/data-storage/structured-data/schemas.md#property-definitions) for how properties are declared.

Use `sort` to order results. Pass a `List<PNDataSyncSortField>` in priority order, where each `PNDataSyncSortField` names a `property` and sets `ascending` (default `true`). The SDK joins the list into a comma-separated request value and appends `:desc` to each descending field. A bare name sorts ascending:

```kotlin
sort = listOf(PNDataSyncSortField("price", ascending = false))                    // single field, descending
sort = listOf(PNDataSyncSortField("type"), PNDataSyncSortField("price", false))  // type ascending, then price descending
sort = listOf(PNDataSyncSortField("createdAt", ascending = true))                 // explicit ascending
```

The `+field` and `-field` prefixes are **not** accepted. A leading `-` is read as part of the property name, so `PNDataSyncSortField("-price")` fails with a `400`. Only properties declared on the class with a filtering mode other than `none` can be sorted on when sorting alone or alongside `filterFast`. Sorting alongside `filter` additionally requires the field to be declared `full`. The built-in fields `id`, `createdAt`, `updatedAt`, and `status` are always sortable without declaring them on the class.

The SDK doesn't validate `filterFast`, `filter`, `sort`, or `limit` locally, it passes them through as-is. An invalid expression, an unsortable field, or an out-of-range `limit` only surfaces as an error response from the server, not as a client-side exception. The only local checks are a blank `sort` property on any list method, a blank `className` (on `createEntity`, `getEntities`, `createRelationship`, and `getRelationships`, or on `createUser`, `getUsers`, `createChannel`, and `getChannels` when you pass one), and a blank resource id. These fail with a `PubNubException` before anything is sent.

### Concurrency (ETag)

Every stored object carries an `eTag`. To guard against concurrent writes, pass the `eTag` you read earlier as `ifMatch` on `set*`, `update*`, and `remove*` calls. The SDK sends it as the `If-Match` request header.

If the server-side value has changed in the meantime, the operation fails with a `412`, and you should re-read the object and retry. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for details.

### Partial updates

The `update*` methods apply a partial update using raw JSON Patch (RFC 6902). Pass a `List<PNJsonPatchOperation>`. Each `PNJsonPatchOperation` has an `op` (`add`, `remove`, `replace`, `move`, `copy`, or `test`, written as a string), a `path` (a full JSON Pointer, for example `/status` or `/payload/price`), and, depending on the operation, a `value` or a `from`.

Each path is a full JSON Pointer (RFC 6901) and is sent as you write it. The SDK does **not** add a `/payload` prefix. To target a field inside `payload`, include the prefix yourself, for example `/payload/price`, not `/price`. A bare `/price` targets a top-level field named `price`, which doesn't exist. Top-level fields like `/status` can be patched directly. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for details.

Correct patch forms:

```kotlin
PNJsonPatchOperation(op = "add", path = "/payload/tags", value = "sale")           // adds a value inside payload.tags
PNJsonPatchOperation(op = "replace", path = "/payload/price", value = 79.99)       // replaces payload.price
PNJsonPatchOperation(op = "remove", path = "/payload/tempFlag")                    // removes payload.tempFlag
PNJsonPatchOperation(op = "move", from = "/payload/oldTag", path = "/payload/tag")
PNJsonPatchOperation(op = "copy", from = "/payload/price", path = "/payload/msrp")
PNJsonPatchOperation(op = "test", path = "/status", value = "active")              // fails the patch if the current value doesn't match
```

`move` and `copy` require `from` (the source pointer) instead of `value`. `test` requires `value` and fails the entire patch if the current value at `path` doesn't match, use it to guard the rest of the operations against a stale read.

Paths address the object's stored property names, the same keys that come back in responses. The class version is `entityClassVersion` on users, channels, and entities, and `relationshipClassVersion` on memberships and relationships. The fields set at creation cannot be patched: `entityClass` and `entityClassLevel` on users, channels, and entities, `relationshipClass`, `entityAId`, and `entityBId` on relationships, and `userId` and `channelId` on memberships.

All operations in the call apply together or not at all.

The `operations` list must contain at least one operation. The SDK checks this before it sends anything and fails the call with a `PubNubException` carrying `JSON_PATCH_OPERATIONS_MISSING` if the list is empty. The exception is thrown by `sync()` and delivered to `onFailure` by `async()`.

### Expiry (TTL)

An object's `expiresAt` is computed once when the object is created, and updates never refresh it. The value is the creation time plus the class TTL, rounded up to the start of the next whole UTC day, so it rarely lands exactly one TTL from the moment you wrote the object.

Entity classes you create default to a 31-day TTL, while the built-in Global `User` and `Channel` classes use 30 days. TTL cannot be disabled. A relationship expires at the earlier expiry time of the two entities it links, fixed when the relationship is created.

Refer to [data expiry](https://www.pubnub.com/docs/data-storage/structured-data/schemas.md#data-expiry-ttl) for details.

:::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
    }
}
```
:::

:::note Requires Access Manager
DataSync 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.
:::

## Users

Users are built-in objects. There are no top-level `name` or `email` fields, all application data lives in the free-form `payload`. Refer to [users](https://www.pubnub.com/docs/data-storage/structured-data/built-in-types.md#users) for the concept.

A user is an entity of the built-in `User` [entity class](https://www.pubnub.com/docs/admin-api/get-all-entity-class-entries.md), which the service provides at the `Global` class level. To give your users their own declared, filterable properties, define a subclass of `User` with [Create a new entity class](https://www.pubnub.com/docs/admin-api/create-a-new-entity-class.md) and pass its name as `className`.

### Create user

Creates a user. Supply a `userId` to control the identifier, or omit it to let the server generate one.

#### Method(s)

```kotlin
pubnub.dataSync.createUser(
    classVersion: Int,
    userId: String? = null,
    className: String? = null,
    classLevel: PNDataSyncClassLevel? = null,
    status: String? = null,
    payload: Any? = null,
): CreateUser
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| classVersion | Int | Yes |  | Version of the user class schema. |
| userId | String | Optional | `server-generated` | User identifier. Omit to let the server generate a UUID. Max 255 characters. |
| className | String | Optional | `User` | Name of the entity class this user belongs to. Must be `User` or one of its subclasses. Defaults to `User` on the server if omitted. Set at creation and immutable afterward. |
| classLevel | PNDataSyncClassLevel | Optional | `service default` | Class hierarchy level of `className`, either `GLOBAL` for a class the service provides or `SUBKEY` for one defined on your keyset. Used to disambiguate classes with the same name defined at different levels. Set at creation and immutable afterward. |
| status | String | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | Any | Optional |  | Free-form JSON object holding your application data. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.createUser(
    userId = "user-alice",
    classVersion = 1,
    payload = mapOf("name" to "Alice", "type" to "shopper")
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Created user ${value.data.id} with eTag ${value.data.eTag}")
    }
}
```

#### Response

```json
{
    "status": 201,
    "data": {
        "id": "user-alice",
        "entityClass": "User",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Alice", "type": "shopper" },
        "createdAt": "2026-07-13T09:00:00.000Z",
        "updatedAt": "2026-07-13T09:00:00.000Z",
        "eTag": "AbCdEfGhIjKlMn"
    }
}
```

### Get user

Returns a single user by `userId`.

#### Method(s)

```kotlin
pubnub.dataSync.getUser(
    userId: String,
): GetUser
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | String | Yes |  | User identifier. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.getUser("user-alice").async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Fetched user ${value.data.id} with payload ${value.data.payload}")
    }
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "user-alice",
        "entityClass": "User",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Alice", "type": "shopper" },
        "createdAt": "2026-07-13T09:00:00.000Z",
        "updatedAt": "2026-07-13T09:00:00.000Z",
        "eTag": "AbCdEfGhIjKlMn"
    }
}
```

### Get all users

Returns a paginated list of users. All parameters are optional, so you can call `getUsers` with no arguments. For pagination, filtering, and sorting, refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination).

#### Method(s)

```kotlin
pubnub.dataSync.getUsers(
    className: String? = null,
    classVersion: Int? = null,
    classLevel: PNDataSyncClassLevel? = null,
    filterFast: String? = null,
    filter: String? = null,
    sort: List<PNDataSyncSortField> = emptyList(),
    limit: Int? = null,
    cursor: String? = null,
): GetUsers
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| className | String | Optional | `all user classes` | User class to list. Omit to list the Global `User` class and all of its subclasses. |
| classVersion | Int | Optional | `all versions` | User class version to list. Omit to list users across every version of the class. |
| classLevel | PNDataSyncClassLevel | Optional | `service default` | Class hierarchy level of `className`, either `GLOBAL` for a class the service provides or `SUBKEY` for one defined on your keyset. Used to disambiguate a class name defined at both levels. |
| filterFast | String | Optional |  | Filter expression evaluated against strongly consistent storage, so it reflects the latest writes. Accepts up to 10 conditions by default (raisable per keyset), over properties declared with filtering mode `simple` or `full`. Cannot be combined with `filter`. |
| filter | String | Optional |  | Filter expression evaluated against eventually consistent storage, so results can briefly lag writes. Supports the full expression language, over properties declared with filtering mode `full`. Cannot be combined with `filterFast`. |
| sort | List<PNDataSyncSortField> | Optional | `empty list` | Order results. Each entry names a property and a direction, for example `PNDataSyncSortField("createdAt", ascending = false)`. |
| limit | Int | Optional | `20` | Maximum number of users per page. Max `100`. |
| cursor | String | Optional |  | Opaque pagination cursor. Omit for the first page. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.getUsers(
    limit = 10
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        value.data.forEach { println(it.id) }
        println("More pages available: ${value.next.hasNext}")
    }
}
```

#### Response

```json
{
    "status": 200,
    "data": [
        {
            "id": "user-alice",
            "entityClass": "User",
            "entityClassVersion": 1,
            "entityClassLevel": "Global",
            "payload": { "name": "Alice", "type": "shopper" },
            "createdAt": "2026-07-13T09:00:00.000Z",
            "updatedAt": "2026-07-13T09:00:00.000Z",
            "eTag": "AbCdEfGhIjKlMn"
        }
    ],
    "meta": {
        "next_cursor": "b2Zmc2V0PTIw",
        "has_next": true,
        "limit": 20
    }
}
```

#### Other examples

##### Filter with filterFast

`filterFast` is evaluated against strongly consistent storage, so it matches an object you just wrote. It runs over properties declared with filtering mode `simple` or `full` and accepts up to 10 conditions by default (raisable per keyset). Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filter`, so only one of the two can be sent per call. The built-in `User` class declares only `name` and `type`, so those, plus the built-in `id`, `createdAt`, `updatedAt`, and `status` fields, are what you can filter on. To filter on other payload fields, such as `email`, define a subclass of `User` that declares them and pass it as `className`.

```kotlin
pubnub.dataSync.getUsers(
    filterFast = "type == \"shopper\"",
    sort = listOf(PNDataSyncSortField(property = "name")),
    limit = 20
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        value.data.forEach { println(it.id) }
        println("More pages available: ${value.next.hasNext}")
    }
}
```

##### Filter with filter

`filter` runs over properties declared with filtering mode `full` and is evaluated against eventually consistent storage, so a very recent write may not be matched yet. Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filterFast`, so only one of the two can be sent per call.

```kotlin
pubnub.dataSync.getUsers(
    filter = "name LIKE \"Alice*\"",
    limit = 20
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        value.data.forEach { println(it.id) }
        println("More pages available: ${value.next.hasNext}")
    }
}
```

##### Page through results with cursor

Pass no `cursor` on the first call. Take `next.cursor` from the result and pass it back as `cursor` on the next call. Stop when `next.hasNext` is `false`.

```kotlin
fun fetchPage(cursor: String?) {
    pubnub.dataSync.getUsers(
        limit = 20,
        cursor = cursor
    ).async { result ->
        result.onFailure { exception ->
            println("Failed: ${exception.message}")
        }.onSuccess { value ->
            value.data.forEach { println(it.id) }
            if (value.next.hasNext) {
                fetchPage(value.next.cursor)
            }
        }
    }
}

fetchPage(cursor = null)
```

### Set user

Replaces a user in full (PUT). Send the complete set of fields, any field you omit is cleared. `className` is immutable after creation and cannot be sent. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for `ifMatch`. For a partial update, use [Update user](#update-user).

#### Method(s)

```kotlin
pubnub.dataSync.setUser(
    userId: String,
    classVersion: Int,
    status: String? = null,
    payload: Any? = null,
    ifMatch: String? = null,
): SetUser
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | String | Yes |  | User identifier. |
| classVersion | Int | Yes |  | Version of the user class schema. |
| status | String | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | Any | Optional |  | Free-form JSON object holding your application data. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The update succeeds only if it still matches, otherwise the server returns `412`. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.setUser(
    userId = "user-alice",
    classVersion = 1,
    payload = mapOf("name" to "Alice B.", "type" to "shopper")
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Replaced user ${value.data.id}, new eTag ${value.data.eTag}")
    }
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "user-alice",
        "entityClass": "User",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Alice B.", "type": "shopper" },
        "createdAt": "2026-07-13T09:00:00.000Z",
        "updatedAt": "2026-07-13T10:15:00.000Z",
        "eTag": "CdEfGhIjKlMnOp"
    }
}
```

### Update user

Applies a partial update to a user with raw JSON Patch operations. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for the operation model.

#### Method(s)

```kotlin
pubnub.dataSync.updateUser(
    userId: String,
    operations: List<PNJsonPatchOperation>,
    ifMatch: String? = null,
): UpdateUser
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | String | Yes |  | User identifier. |
| operations | List<PNJsonPatchOperation> | Yes |  | One or more JSON Patch operations. Must contain at least one item. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The patch succeeds only if it still matches, otherwise the server returns `412`. |

Use a JSON Pointer that starts with `/payload/` to target payload fields, or a root pointer (for example `/status`) to target a top-level field.

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.updateUser(
    userId = "user-alice",
    operations = listOf(
        PNJsonPatchOperation(op = "replace", path = "/payload/name", value = "Alice B.")
    )
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Updated user ${value.data.id}, new eTag ${value.data.eTag}")
    }
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "user-alice",
        "status": "active",
        "entityClass": "User",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Alice B.", "type": "shopper" },
        "createdAt": "2026-07-13T09:00:00.000Z",
        "updatedAt": "2026-07-13T10:20:00.000Z",
        "eTag": "EfGhIjKlMnOpQr"
    }
}
```

### Remove user

Deletes a user by `userId`.

#### Method(s)

```kotlin
pubnub.dataSync.removeUser(
    userId: String,
    ifMatch: String? = null,
): RemoveUser
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | String | Yes |  | User identifier. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The delete succeeds only if it still matches, otherwise the server returns `412`. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.removeUser("user-alice").async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Removed user, HTTP status ${value.status}")
    }
}
```

#### Response

```json
{
    "status": 200
}
```

## Channels

Channels work like users. They have no top-level `name` field, all application data lives in `payload`, and they support the same operations. Refer to [channels](https://www.pubnub.com/docs/data-storage/structured-data/built-in-types.md#channels) for the concept.

A channel is an entity of the built-in `Channel` [entity class](https://www.pubnub.com/docs/admin-api/get-all-entity-class-entries.md), which the service provides at the `Global` class level. Subclass it with [Create a new entity class](https://www.pubnub.com/docs/admin-api/create-a-new-entity-class.md) to add declared properties, then pass the subclass name as `className`.

### Create channel

Creates a channel. Supply a `channelId` to control the identifier, or omit it to let the server generate one.

#### Method(s)

```kotlin
pubnub.dataSync.createChannel(
    classVersion: Int,
    channelId: String? = null,
    className: String? = null,
    classLevel: PNDataSyncClassLevel? = null,
    status: String? = null,
    payload: Any? = null,
): CreateChannel
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| classVersion | Int | Yes |  | Version of the channel class schema. |
| channelId | String | Optional | `server-generated` | Channel identifier. Omit to let the server generate a UUID. Max 255 characters. |
| className | String | Optional | `Channel` | Name of the entity class this channel belongs to. Must be `Channel` or one of its subclasses. Defaults to `Channel` on the server if omitted. Set at creation and immutable afterward. |
| classLevel | PNDataSyncClassLevel | Optional | `service default` | Class hierarchy level of `className`, either `GLOBAL` for a class the service provides or `SUBKEY` for one defined on your keyset. Used to disambiguate classes with the same name defined at different levels. Set at creation and immutable afterward. |
| status | String | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | Any | Optional |  | Free-form JSON object holding your application data. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.createChannel(
    channelId = "channel-summer-sale",
    classVersion = 1,
    payload = mapOf("name" to "Summer Sale", "type" to "promotion")
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Created channel ${value.data.id} with eTag ${value.data.eTag}")
    }
}
```

#### Response

```json
{
    "status": 201,
    "data": {
        "id": "channel-summer-sale",
        "entityClass": "Channel",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Summer Sale", "type": "promotion" },
        "createdAt": "2026-07-13T09:05:00.000Z",
        "updatedAt": "2026-07-13T09:05:00.000Z",
        "eTag": "GhIjKlMnOpQrSt"
    }
}
```

### Get channel

Returns a single channel by `channelId`.

#### Method(s)

```kotlin
pubnub.dataSync.getChannel(
    channelId: String,
): GetChannel
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | String | Yes |  | Channel identifier. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.getChannel("channel-summer-sale").async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Fetched channel ${value.data.id} with payload ${value.data.payload}")
    }
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "channel-summer-sale",
        "entityClass": "Channel",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Summer Sale", "type": "promotion" },
        "createdAt": "2026-07-13T09:05:00.000Z",
        "updatedAt": "2026-07-13T09:05:00.000Z",
        "eTag": "GhIjKlMnOpQrSt"
    }
}
```

### Get all channels

Returns a paginated list of channels. All parameters are optional, so you can call `getChannels` with no arguments. For pagination, filtering, and sorting, refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination).

#### Method(s)

```kotlin
pubnub.dataSync.getChannels(
    className: String? = null,
    classVersion: Int? = null,
    classLevel: PNDataSyncClassLevel? = null,
    filterFast: String? = null,
    filter: String? = null,
    sort: List<PNDataSyncSortField> = emptyList(),
    limit: Int? = null,
    cursor: String? = null,
): GetChannels
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| className | String | Optional | `all channel classes` | Channel class to list. Omit to list the Global `Channel` class and all of its subclasses. |
| classVersion | Int | Optional | `all versions` | Channel class version to list. Omit to list channels across every version of the class. |
| classLevel | PNDataSyncClassLevel | Optional | `service default` | Class hierarchy level of `className`, either `GLOBAL` for a class the service provides or `SUBKEY` for one defined on your keyset. Used to disambiguate a class name defined at both levels. |
| filterFast | String | Optional |  | Filter expression evaluated against strongly consistent storage, so it reflects the latest writes. Accepts up to 10 conditions by default (raisable per keyset), over properties declared with filtering mode `simple` or `full`. Cannot be combined with `filter`. |
| filter | String | Optional |  | Filter expression evaluated against eventually consistent storage, so results can briefly lag writes. Supports the full expression language, over properties declared with filtering mode `full`. Cannot be combined with `filterFast`. |
| sort | List<PNDataSyncSortField> | Optional | `empty list` | Order results. Each entry names a property and a direction. |
| limit | Int | Optional | `20` | Maximum number of channels per page. Max `100`. |
| cursor | String | Optional |  | Opaque pagination cursor. Omit for the first page. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.getChannels(
    limit = 10
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        value.data.forEach { println(it.id) }
        println("More pages available: ${value.next.hasNext}")
    }
}
```

#### Response

```json
{
    "status": 200,
    "data": [
        {
            "id": "channel-summer-sale",
            "entityClass": "Channel",
            "entityClassVersion": 1,
            "entityClassLevel": "Global",
            "payload": { "name": "Summer Sale", "type": "promotion" },
            "createdAt": "2026-07-13T09:05:00.000Z",
            "updatedAt": "2026-07-13T09:05:00.000Z",
            "eTag": "GhIjKlMnOpQrSt"
        }
    ],
    "meta": {
        "next_cursor": null,
        "has_next": false,
        "limit": 20
    }
}
```

#### Other examples

##### Filter with filterFast

`filterFast` is evaluated against strongly consistent storage, so it matches an object you just wrote. It runs over properties declared with filtering mode `simple` or `full` and accepts up to 10 conditions by default (raisable per keyset). Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filter`, so only one of the two can be sent per call. The built-in `Channel` class declares only `name` and `type`, so those, plus the built-in `id`, `createdAt`, `updatedAt`, and `status` fields, are what you can filter on. To filter on other payload fields, such as `region`, define a subclass of `Channel` that declares them and pass it as `className`.

```kotlin
pubnub.dataSync.getChannels(
    filterFast = "type == \"promotion\"",
    sort = listOf(PNDataSyncSortField(property = "name")),
    limit = 20
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        value.data.forEach { println(it.id) }
        println("More pages available: ${value.next.hasNext}")
    }
}
```

##### Filter with filter

`filter` runs over properties declared with filtering mode `full` and is evaluated against eventually consistent storage, so a very recent write may not be matched yet. Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filterFast`, so only one of the two can be sent per call.

```kotlin
pubnub.dataSync.getChannels(
    filter = "name LIKE \"Summer*\"",
    limit = 20
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        value.data.forEach { println(it.id) }
        println("More pages available: ${value.next.hasNext}")
    }
}
```

##### Page through results with cursor

Pass no `cursor` on the first call. Take `next.cursor` from the result and pass it back as `cursor` on the next call. Stop when `next.hasNext` is `false`.

```kotlin
fun fetchPage(cursor: String?) {
    pubnub.dataSync.getChannels(
        limit = 20,
        cursor = cursor
    ).async { result ->
        result.onFailure { exception ->
            println("Failed: ${exception.message}")
        }.onSuccess { value ->
            value.data.forEach { println(it.id) }
            if (value.next.hasNext) {
                fetchPage(value.next.cursor)
            }
        }
    }
}

fetchPage(cursor = null)
```

### Set channel

Replaces a channel in full (PUT). Send the complete set of fields, any field you omit is cleared. `className` is immutable after creation and cannot be sent. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for `ifMatch`. For a partial update, use [Update channel](#update-channel).

#### Method(s)

```kotlin
pubnub.dataSync.setChannel(
    channelId: String,
    classVersion: Int,
    status: String? = null,
    payload: Any? = null,
    ifMatch: String? = null,
): SetChannel
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | String | Yes |  | Channel identifier. |
| classVersion | Int | Yes |  | Version of the channel class schema. |
| status | String | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | Any | Optional |  | Free-form JSON object holding your application data. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The update succeeds only if it still matches, otherwise the server returns `412`. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.setChannel(
    channelId = "channel-summer-sale",
    classVersion = 1,
    payload = mapOf("name" to "Summer Sale 2026", "type" to "promotion")
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Replaced channel ${value.data.id}, new eTag ${value.data.eTag}")
    }
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "channel-summer-sale",
        "entityClass": "Channel",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Summer Sale 2026", "type": "promotion" },
        "createdAt": "2026-07-13T09:05:00.000Z",
        "updatedAt": "2026-07-13T11:00:00.000Z",
        "eTag": "IjKlMnOpQrStUv"
    }
}
```

### Update channel

Applies a partial update to a channel with raw JSON Patch operations. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for the operation model.

#### Method(s)

```kotlin
pubnub.dataSync.updateChannel(
    channelId: String,
    operations: List<PNJsonPatchOperation>,
    ifMatch: String? = null,
): UpdateChannel
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | String | Yes |  | Channel identifier. |
| operations | List<PNJsonPatchOperation> | Yes |  | One or more JSON Patch operations. Must contain at least one item. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The patch succeeds only if it still matches, otherwise the server returns `412`. |

Use a JSON Pointer that starts with `/payload/` to target payload fields, or a root pointer (for example `/status`) to target a top-level field.

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.updateChannel(
    channelId = "channel-summer-sale",
    operations = listOf(
        PNJsonPatchOperation(op = "replace", path = "/payload/name", value = "Summer Sale 2026")
    )
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Updated channel ${value.data.id}, new eTag ${value.data.eTag}")
    }
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "channel-summer-sale",
        "status": "active",
        "entityClass": "Channel",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Summer Sale 2026", "type": "promotion" },
        "createdAt": "2026-07-13T09:05:00.000Z",
        "updatedAt": "2026-07-13T11:05:00.000Z",
        "eTag": "KlMnOpQrStUvWx"
    }
}
```

### Remove channel

Deletes a channel by `channelId`.

#### Method(s)

```kotlin
pubnub.dataSync.removeChannel(
    channelId: String,
    ifMatch: String? = null,
): RemoveChannel
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | String | Yes |  | Channel identifier. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The delete succeeds only if it still matches, otherwise the server returns `412`. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.removeChannel("channel-summer-sale").async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Removed channel, HTTP status ${value.status}")
    }
}
```

#### Response

```json
{
    "status": 200
}
```

## Memberships

A membership links a user to a channel and carries its own `payload`. In the running example, Alice is a member of `channel-summer-sale` with the payload `{ "role": "viewer" }`. Refer to [memberships](https://www.pubnub.com/docs/data-storage/structured-data/built-in-types.md#memberships) for the concept.

A membership is a relationship of the built-in Global `Membership` [relationship class](https://www.pubnub.com/docs/admin-api/get-all-relationship-classes.md), whose two sides are surfaced as `channelId` and `userId`. Every membership response includes both `relationshipClass` and `relationshipClassVersion`. The class is assigned by the service, so the `createMembership` and `setMembership` methods take no class parameter.

Relationship classes [don't support inheritance](https://www.pubnub.com/docs/data-storage/structured-data/schemas.md#relationship-class-inheritance), and only the Global `Membership` class produces memberships, so `relationshipClass` is always `Membership` and `relationshipClassVersion` is the only part that varies.

### Create membership

Creates a membership linking a user to a channel. The `userId`/`channelId` pair must be unique for the membership class. A membership that duplicates an existing pair is rejected with a `409`.

#### Method(s)

```kotlin
pubnub.dataSync.createMembership(
    channelId: String,
    userId: String,
    classVersion: Int,
    membershipId: String? = null,
    status: String? = null,
    payload: Any? = null,
): CreateMembership
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | String | Yes |  | Identifier of the channel in the membership. |
| userId | String | Yes |  | Identifier of the user in the membership. |
| classVersion | Int | Yes |  | Version of the Membership relationship class schema. |
| membershipId | String | Optional | `server-generated` | Membership identifier. Omit to let the server generate a UUID. Max 255 characters. |
| status | String | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | Any | Optional |  | Free-form JSON object holding your application data. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.createMembership(
    membershipId = "membership-alice-summer-sale",
    channelId = "channel-summer-sale",
    userId = "user-alice",
    classVersion = 1,
    status = "active",
    payload = mapOf("role" to "viewer")
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Created membership ${value.data.id} with eTag ${value.data.eTag}")
    }
}
```

#### Response

```json
{
    "status": 201,
    "data": {
        "id": "membership-alice-summer-sale",
        "channelId": "channel-summer-sale",
        "userId": "user-alice",
        "relationshipClass": "Membership",
        "relationshipClassVersion": 1,
        "payload": { "role": "viewer" },
        "createdAt": "2026-07-13T09:10:00.000Z",
        "updatedAt": "2026-07-13T09:10:00.000Z",
        "eTag": "MnOpQrStUvWxYz"
    }
}
```

### Get membership

Returns a single membership by `membershipId`.

#### Method(s)

```kotlin
pubnub.dataSync.getMembership(
    membershipId: String,
): GetMembership
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| membershipId | String | Yes |  | Membership identifier. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.getMembership("membership-alice-summer-sale").async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Fetched membership ${value.data.id} with payload ${value.data.payload}")
    }
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "membership-alice-summer-sale",
        "channelId": "channel-summer-sale",
        "userId": "user-alice",
        "relationshipClass": "Membership",
        "relationshipClassVersion": 1,
        "payload": { "role": "viewer" },
        "createdAt": "2026-07-13T09:10:00.000Z",
        "updatedAt": "2026-07-13T09:10:00.000Z",
        "eTag": "MnOpQrStUvWxYz"
    }
}
```

### Get all memberships

Returns a paginated list of memberships. All parameters are optional, so you can call `getMemberships` with no arguments. `userId` and `channelId` can be set independently, together, or omitted entirely. Filter by `userId` to list a user's memberships or by `channelId` to list a channel's members. For pagination, filtering, and sorting, refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination).

#### Method(s)

```kotlin
pubnub.dataSync.getMemberships(
    channelId: String? = null,
    userId: String? = null,
    classVersion: Int? = null,
    filterFast: String? = null,
    filter: String? = null,
    sort: List<PNDataSyncSortField> = emptyList(),
    limit: Int? = null,
    cursor: String? = null,
): GetMemberships
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | String | Optional |  | List only memberships for this channel. |
| userId | String | Optional |  | List only memberships for this user. |
| classVersion | Int | Optional | `all versions` | Membership class version to list. Omit to list memberships across every version of the class. |
| filterFast | String | Optional |  | Filter expression evaluated against strongly consistent storage, so it reflects the latest writes. Accepts up to 10 conditions by default (raisable per keyset), over properties declared with filtering mode `simple` or `full`. Cannot be combined with `filter`. |
| filter | String | Optional |  | Filter expression evaluated against eventually consistent storage, so results can briefly lag writes. Supports the full expression language, over properties declared with filtering mode `full`. Cannot be combined with `filterFast`. |
| sort | List<PNDataSyncSortField> | Optional | `empty list` | Order results. Each entry names a property and a direction. |
| limit | Int | Optional | `20` | Maximum number of memberships per page. Max `100`. |
| cursor | String | Optional |  | Opaque pagination cursor. Omit for the first page. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.getMemberships(
    userId = "user-alice",
    limit = 10
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        value.data.forEach { println(it.id) }
        println("More pages available: ${value.next.hasNext}")
    }
}
```

#### Response

```json
{
    "status": 200,
    "data": [
        {
            "id": "membership-alice-summer-sale",
            "channelId": "channel-summer-sale",
            "userId": "user-alice",
            "relationshipClass": "Membership",
            "relationshipClassVersion": 1,
            "payload": { "role": "viewer" },
            "createdAt": "2026-07-13T09:10:00.000Z",
            "updatedAt": "2026-07-13T09:10:00.000Z",
            "eTag": "MnOpQrStUvWxYz"
        }
    ],
    "meta": {
        "next_cursor": null,
        "has_next": false,
        "limit": 20
    }
}
```

#### Other examples

##### List a channel's members with channelId

Pass `channelId` instead of `userId` to list the members of a channel rather than a user's memberships.

```kotlin
pubnub.dataSync.getMemberships(
    channelId = "channel-summer-sale",
    limit = 50
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        value.data.forEach { println("${it.userId} is a member of ${it.channelId}") }
        println("More pages available: ${value.next.hasNext}")
    }
}
```

##### Filter with filterFast

`filterFast` is evaluated against strongly consistent storage, so it matches an object you just wrote. It runs over properties declared with filtering mode `simple` or `full` and accepts up to 10 conditions by default (raisable per keyset). Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filter`, so only one of the two can be sent per call.

```kotlin
// Membership payload fields such as `role` are not filterable; filter on `status` instead
pubnub.dataSync.getMemberships(
    userId = "user-alice",
    filterFast = "status == \"active\"",
    sort = listOf(PNDataSyncSortField(property = "createdAt", ascending = false)),
    limit = 20
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        value.data.forEach { println(it.id) }
        println("More pages available: ${value.next.hasNext}")
    }
}
```

##### Filter with filter

`filter` runs over properties declared with filtering mode `full` and is evaluated against eventually consistent storage, so a very recent write may not be matched yet. Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filterFast`, so only one of the two can be sent per call.

```kotlin
// Membership payload fields such as `role` are not filterable; filter on `status` instead
pubnub.dataSync.getMemberships(
    userId = "user-alice",
    filter = "status LIKE \"act*\"",
    limit = 20
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        value.data.forEach { println(it.id) }
        println("More pages available: ${value.next.hasNext}")
    }
}
```

##### Page through results with cursor

Pass no `cursor` on the first call. Take `next.cursor` from the result and pass it back as `cursor` on the next call. Stop when `next.hasNext` is `false`.

```kotlin
fun fetchPage(cursor: String?) {
    pubnub.dataSync.getMemberships(
        userId = "user-alice",
        limit = 20,
        cursor = cursor
    ).async { result ->
        result.onFailure { exception ->
            println("Failed: ${exception.message}")
        }.onSuccess { value ->
            value.data.forEach { println(it.id) }
            if (value.next.hasNext) {
                fetchPage(value.next.cursor)
            }
        }
    }
}

fetchPage(cursor = null)
```

### Set membership

Replaces a membership in full (PUT). Send the complete set of fields, any field you omit is cleared. The linked user and channel are immutable, so `setMembership` doesn't expose `channelId`/`userId` at all, there's nothing to resend. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for `ifMatch`. For a partial update, use [Update membership](#update-membership).

#### Method(s)

```kotlin
pubnub.dataSync.setMembership(
    membershipId: String,
    classVersion: Int,
    status: String? = null,
    payload: Any? = null,
    ifMatch: String? = null,
): SetMembership
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| membershipId | String | Yes |  | Membership identifier. |
| classVersion | Int | Yes |  | Version of the Membership relationship class schema. |
| status | String | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | Any | Optional |  | Free-form JSON object holding your application data. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The update succeeds only if it still matches, otherwise the server returns `412`. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.setMembership(
    membershipId = "membership-alice-summer-sale",
    classVersion = 1,
    payload = mapOf("role" to "moderator")
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Replaced membership ${value.data.id}, new eTag ${value.data.eTag}")
    }
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "membership-alice-summer-sale",
        "channelId": "channel-summer-sale",
        "userId": "user-alice",
        "relationshipClass": "Membership",
        "relationshipClassVersion": 1,
        "payload": { "role": "moderator" },
        "createdAt": "2026-07-13T09:10:00.000Z",
        "updatedAt": "2026-07-13T12:00:00.000Z",
        "eTag": "OpQrStUvWxYzAb"
    }
}
```

### Update membership

Applies a partial update to a membership with raw JSON Patch operations. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for the operation model.

#### Method(s)

```kotlin
pubnub.dataSync.updateMembership(
    membershipId: String,
    operations: List<PNJsonPatchOperation>,
    ifMatch: String? = null,
): UpdateMembership
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| membershipId | String | Yes |  | Membership identifier. |
| operations | List<PNJsonPatchOperation> | Yes |  | One or more JSON Patch operations. Must contain at least one item. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The patch succeeds only if it still matches, otherwise the server returns `412`. |

Use a JSON Pointer that starts with `/payload/` to target payload fields, or a root pointer (for example `/status`) to target a top-level field.

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.updateMembership(
    membershipId = "membership-alice-summer-sale",
    operations = listOf(
        PNJsonPatchOperation(op = "replace", path = "/payload/role", value = "moderator")
    )
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Updated membership ${value.data.id}, new eTag ${value.data.eTag}")
    }
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "membership-alice-summer-sale",
        "status": "active",
        "channelId": "channel-summer-sale",
        "userId": "user-alice",
        "relationshipClass": "Membership",
        "relationshipClassVersion": 1,
        "payload": { "role": "moderator" },
        "createdAt": "2026-07-13T09:10:00.000Z",
        "updatedAt": "2026-07-13T12:05:00.000Z",
        "eTag": "QrStUvWxYzAbCd"
    }
}
```

### Remove membership

Deletes a membership by `membershipId`.

#### Method(s)

```kotlin
pubnub.dataSync.removeMembership(
    membershipId: String,
    ifMatch: String? = null,
): RemoveMembership
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| membershipId | String | Yes |  | Membership identifier. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The delete succeeds only if it still matches, otherwise the server returns `412`. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.removeMembership("membership-alice-summer-sale").async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Removed membership, HTTP status ${value.status}")
    }
}
```

#### Response

```json
{
    "status": 200
}
```

## Entities

Entities are instances of the custom [entity classes](https://www.pubnub.com/docs/admin-api/get-all-entity-class-entries.md) you define on your keyset. In the running example, `product` is a class and `product-sneaker-42` is an instance. Use [Create a new entity class](https://www.pubnub.com/docs/admin-api/create-a-new-entity-class.md) to declare a class, and [Get entity class by ID](https://www.pubnub.com/docs/admin-api/get-entity-class-by-id.md) to read the property, filtering, and projection declarations that govern its instances.

Entity classes can extend one another. Listing a class also returns the entities of its subclasses, so `getEntities(className = "product")` returns every `product` plus every instance of a class that extends `product`.

### Create entity

Creates an entity of a given class and version.

#### Method(s)

```kotlin
pubnub.dataSync.createEntity(
    className: String,
    classVersion: Int,
    classLevel: PNDataSyncClassLevel? = null,
    entityId: String? = null,
    status: String? = null,
    payload: Any? = null,
): CreateEntity
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| className | String | Yes |  | Name of the entity class this instance belongs to. Set at creation and immutable afterward. |
| classVersion | Int | Yes |  | Version of the entity class schema. |
| classLevel | PNDataSyncClassLevel | Optional | `service default` | Class hierarchy level of `className`, either `GLOBAL` for a class the service provides or `SUBKEY` for one defined on your keyset. Used to disambiguate classes with the same name defined at different levels. Set at creation and immutable afterward. |
| entityId | String | Optional | `server-generated` | Entity identifier. Omit to let the server generate a UUID. Max 255 characters. |
| status | String | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | Any | Optional |  | Free-form JSON object holding your application data. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.createEntity(
    entityId = "product-sneaker-42",
    className = "product",
    classVersion = 1,
    payload = mapOf("name" to "Retro Sneaker", "price" to 89.99, "stock" to 12)
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Created entity ${value.data.id} with eTag ${value.data.eTag}")
    }
}
```

#### Response

```json
{
    "status": 201,
    "data": {
        "id": "product-sneaker-42",
        "entityClass": "product",
        "entityClassVersion": 1,
        "entityClassLevel": "SubKey",
        "payload": { "name": "Retro Sneaker", "price": 89.99, "stock": 12 },
        "createdAt": "2026-07-13T09:15:00.000Z",
        "updatedAt": "2026-07-13T09:15:00.000Z",
        "eTag": "StUvWxYzAbCdEf"
    }
}
```

### Get entity

Returns a single entity by `entityId`.

#### Method(s)

```kotlin
pubnub.dataSync.getEntity(
    entityId: String,
): GetEntity
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityId | String | Yes |  | Entity identifier. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.getEntity("product-sneaker-42").async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Fetched entity ${value.data.id} with payload ${value.data.payload}")
    }
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "product-sneaker-42",
        "entityClass": "product",
        "entityClassVersion": 1,
        "entityClassLevel": "SubKey",
        "payload": { "name": "Retro Sneaker", "price": 89.99, "stock": 12 },
        "createdAt": "2026-07-13T09:15:00.000Z",
        "updatedAt": "2026-07-13T09:15:00.000Z",
        "eTag": "StUvWxYzAbCdEf"
    }
}
```

### Get all entities

Returns a paginated list of entities within a class. The `className` parameter is required, entities are always listed within the context of their class. For pagination, filtering, and sorting, refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination).

#### Method(s)

```kotlin
pubnub.dataSync.getEntities(
    className: String,
    classVersion: Int? = null,
    classLevel: PNDataSyncClassLevel? = null,
    filterFast: String? = null,
    filter: String? = null,
    sort: List<PNDataSyncSortField> = emptyList(),
    limit: Int? = null,
    cursor: String? = null,
): GetEntities
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| className | String | Yes |  | Name of the entity class to list. |
| classVersion | Int | Optional | `all versions` | Entity class version to list. Omit to list entities across every version of the class. |
| classLevel | PNDataSyncClassLevel | Optional | `service default` | Class hierarchy level of `className`, either `GLOBAL` for a class the service provides or `SUBKEY` for one defined on your keyset. Used to disambiguate a class name defined at both levels. |
| filterFast | String | Optional |  | Filter expression evaluated against strongly consistent storage, so it reflects the latest writes. Accepts up to 10 conditions by default (raisable per keyset), over properties declared with filtering mode `simple` or `full`. Cannot be combined with `filter`. |
| filter | String | Optional |  | Filter expression evaluated against eventually consistent storage, so results can briefly lag writes. Supports the full expression language, over properties declared with filtering mode `full`. Cannot be combined with `filterFast`. |
| sort | List<PNDataSyncSortField> | Optional | `empty list` | Order results. Each entry names a property and a direction. |
| limit | Int | Optional | `20` | Maximum number of entities per page. Max `100`. |
| cursor | String | Optional |  | Opaque pagination cursor. Omit for the first page. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.getEntities(
    className = "product",
    limit = 10
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        value.data.forEach { println(it.id) }
        println("More pages available: ${value.next.hasNext}")
    }
}
```

#### Response

```json
{
    "status": 200,
    "data": [
        {
            "id": "product-sneaker-42",
            "entityClass": "product",
            "entityClassVersion": 1,
            "entityClassLevel": "SubKey",
            "payload": { "name": "Retro Sneaker", "price": 89.99, "stock": 12 },
            "createdAt": "2026-07-13T09:15:00.000Z",
            "updatedAt": "2026-07-13T09:15:00.000Z",
            "eTag": "StUvWxYzAbCdEf"
        }
    ],
    "meta": {
        "next_cursor": null,
        "has_next": false,
        "limit": 20
    }
}
```

#### Other examples

##### Filter with filterFast

`filterFast` is evaluated against strongly consistent storage, so it matches an object you just wrote. It runs over properties declared with filtering mode `simple` or `full` and accepts up to 10 conditions by default (raisable per keyset). Reference a declared property by its `name`, not its `path`, and combine conditions with `&&` and `||`. It shares the same expression language as `filter`, so only one of the two can be sent per call.

```kotlin
// `price` and `stock` must be declared filterable (`simple` or `full`) on the `product` class
pubnub.dataSync.getEntities(
    className = "product",
    filterFast = "price < 100 && stock > 0",
    sort = listOf(PNDataSyncSortField(property = "price")),
    limit = 20
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        value.data.forEach { println(it.id) }
        println("More pages available: ${value.next.hasNext}")
    }
}
```

##### Filter with filter

`filter` runs over properties declared with filtering mode `full` and is evaluated against eventually consistent storage, so a very recent write may not be matched yet. Reference a declared property by its `name`, not its `path`, and combine conditions with `&&` and `||`. It shares the same expression language as `filterFast`, so only one of the two can be sent per call.

```kotlin
// `filter` only accepts properties declared with `full` filtering on the `product` class
pubnub.dataSync.getEntities(
    className = "product",
    filter = "name LIKE \"*Sneaker*\"",
    limit = 20
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        value.data.forEach { println(it.id) }
        println("More pages available: ${value.next.hasNext}")
    }
}
```

##### Page through results with cursor

Pass no `cursor` on the first call. Take `next.cursor` from the result and pass it back as `cursor` on the next call. Stop when `next.hasNext` is `false`.

```kotlin
fun fetchPage(cursor: String?) {
    pubnub.dataSync.getEntities(
        className = "product",
        limit = 20,
        cursor = cursor
    ).async { result ->
        result.onFailure { exception ->
            println("Failed: ${exception.message}")
        }.onSuccess { value ->
            value.data.forEach { println(it.id) }
            if (value.next.hasNext) {
                fetchPage(value.next.cursor)
            }
        }
    }
}

fetchPage(cursor = null)
```

### Set entity

Replaces a entity in full (PUT). Send the complete set of fields, any field you omit is cleared. `className` is immutable after creation and cannot be sent. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for `ifMatch`. For a partial update, use [Update entity](#update-entity).

#### Method(s)

```kotlin
pubnub.dataSync.setEntity(
    entityId: String,
    classVersion: Int,
    status: String? = null,
    payload: Any? = null,
    ifMatch: String? = null,
): SetEntity
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityId | String | Yes |  | Entity identifier. |
| classVersion | Int | Yes |  | Version of the entity class schema. |
| status | String | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | Any | Optional |  | Free-form JSON object holding your application data. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The update succeeds only if it still matches, otherwise the server returns `412`. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.setEntity(
    entityId = "product-sneaker-42",
    classVersion = 1,
    payload = mapOf("name" to "Retro Sneaker", "price" to 79.99, "stock" to 8)
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Replaced entity ${value.data.id}, new eTag ${value.data.eTag}")
    }
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "product-sneaker-42",
        "entityClass": "product",
        "entityClassVersion": 1,
        "entityClassLevel": "SubKey",
        "payload": { "name": "Retro Sneaker", "price": 79.99, "stock": 12 },
        "createdAt": "2026-07-13T09:15:00.000Z",
        "updatedAt": "2026-07-13T13:00:00.000Z",
        "eTag": "UvWxYzAbCdEfGh"
    }
}
```

### Update entity

Applies a partial update to a entity with raw JSON Patch operations. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for the operation model.

#### Method(s)

```kotlin
pubnub.dataSync.updateEntity(
    entityId: String,
    operations: List<PNJsonPatchOperation>,
    ifMatch: String? = null,
): UpdateEntity
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityId | String | Yes |  | Entity identifier. |
| operations | List<PNJsonPatchOperation> | Yes |  | One or more JSON Patch operations. Must contain at least one item. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The patch succeeds only if it still matches, otherwise the server returns `412`. |

Use a JSON Pointer that starts with `/payload/` to target payload fields, or a root pointer (for example `/status`) to target a top-level field.

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.updateEntity(
    entityId = "product-sneaker-42",
    operations = listOf(
        PNJsonPatchOperation(op = "replace", path = "/payload/price", value = 79.99),
        PNJsonPatchOperation(op = "replace", path = "/payload/stock", value = 8)
    )
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Updated entity ${value.data.id}, new eTag ${value.data.eTag}")
    }
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "product-sneaker-42",
        "entityClass": "product",
        "entityClassVersion": 1,
        "entityClassLevel": "SubKey",
        "payload": { "name": "Retro Sneaker", "price": 79.99, "stock": 8 },
        "createdAt": "2026-07-13T09:15:00.000Z",
        "updatedAt": "2026-07-13T13:05:00.000Z",
        "eTag": "WxYzAbCdEfGhIj"
    }
}
```

#### Other examples

##### Combine patch operations, and guard the write with ifMatch

A single `updateEntity` call can mix `add`, `replace`, `remove`, `move`, `copy`, and `test` operations in one `operations` list. All operations in the call apply together or not at all. Add `ifMatch` (the `eTag` from a prior read) to reject the patch with a `412` if the entity changed since you read it, instead of silently overwriting a concurrent change.

```kotlin
pubnub.dataSync.updateEntity(
    entityId = "product-sneaker-42",
    operations = listOf(
        // Fail the whole patch unless the name is still "Retro Sneaker"
        PNJsonPatchOperation(op = "test", path = "/payload/name", value = "Retro Sneaker"),
        // Keep the old price before changing it
        PNJsonPatchOperation(op = "copy", from = "/payload/price", path = "/payload/previousPrice"),
        PNJsonPatchOperation(op = "replace", path = "/payload/price", value = 79.99),
        PNJsonPatchOperation(op = "replace", path = "/payload/stock", value = 8),
        PNJsonPatchOperation(op = "add", path = "/payload/sale", value = true),
        // Rename a field
        PNJsonPatchOperation(op = "move", from = "/payload/sale", path = "/payload/onSale"),
        // The removed field must exist on the entity, otherwise the patch is rejected
        PNJsonPatchOperation(op = "remove", path = "/payload/legacySku")
    ),
    // Use the eTag from an earlier read of the entity, not a literal value
    ifMatch = "a1b2c3d4e5f6"
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Patched ${value.data.id}, new eTag ${value.data.eTag}")
    }
}
```

### Remove entity

Deletes a entity by `entityId`.

#### Method(s)

```kotlin
pubnub.dataSync.removeEntity(
    entityId: String,
    ifMatch: String? = null,
): RemoveEntity
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityId | String | Yes |  | Entity identifier. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The delete succeeds only if it still matches, otherwise the server returns `412`. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.removeEntity("product-sneaker-42").async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Removed entity, HTTP status ${value.status}")
    }
}
```

#### Response

```json
{
    "status": 200
}
```

## Relationships

A relationship links two entities and carries its own `payload`. In the running example, the `ProductOwner` relationship links `seller-bob` to `product-sneaker-42`.

Relationships are instances of the [relationship classes](https://www.pubnub.com/docs/admin-api/get-all-relationship-classes.md) you define on your keyset. A relationship class declares the cardinality the service enforces (`one-to-one`, `one-to-many`, or `many-to-many`) and, optionally, which entity class each side must belong to. Use [Create a new relationship class](https://www.pubnub.com/docs/admin-api/create-a-new-relationship-class.md) to declare a class, and [Get relationship class by name and version](https://www.pubnub.com/docs/admin-api/get-relationship-class-by-name-and-version.md) to read it back.

### Create relationship

Creates a relationship between two entities. The relationship class's cardinality (one-to-one, one-to-many, or many-to-many) is enforced on create. A relationship that violates its class's cardinality is rejected with a `409`.

#### Method(s)

```kotlin
pubnub.dataSync.createRelationship(
    entityAId: String,
    entityBId: String,
    className: String,
    classVersion: Int,
    relationshipId: String? = null,
    status: String? = null,
    payload: Any? = null,
): CreateRelationship
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityAId | String | Yes |  | Identifier of the first linked entity. Immutable after creation. |
| entityBId | String | Yes |  | Identifier of the second linked entity. Immutable after creation. |
| className | String | Yes |  | Name of the relationship class this instance belongs to. Set at creation and immutable afterward. |
| classVersion | Int | Yes |  | Version of the relationship class schema. |
| relationshipId | String | Optional | `server-generated` | Relationship identifier. Omit to let the server generate a UUID. Max 255 characters. |
| status | String | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | Any | Optional |  | Free-form JSON object holding your application data. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.createRelationship(
    relationshipId = "rel-bob-owns-sneaker-42",
    entityAId = "seller-bob",
    entityBId = "product-sneaker-42",
    className = "ProductOwner",
    classVersion = 1,
    payload = mapOf("since" to "2026-07-13")
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Created relationship ${value.data.id} with eTag ${value.data.eTag}")
    }
}
```

#### Response

```json
{
    "status": 201,
    "data": {
        "id": "rel-bob-owns-sneaker-42",
        "entityAId": "seller-bob",
        "entityBId": "product-sneaker-42",
        "relationshipClass": "ProductOwner",
        "relationshipClassVersion": 1,
        "payload": { "since": "2026-07-13" },
        "createdAt": "2026-07-13T09:20:00.000Z",
        "updatedAt": "2026-07-13T09:20:00.000Z",
        "eTag": "YzAbCdEfGhIjKl"
    }
}
```

### Get relationship

Returns a single relationship by `relationshipId`.

#### Method(s)

```kotlin
pubnub.dataSync.getRelationship(
    relationshipId: String,
): GetRelationship
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| relationshipId | String | Yes |  | Relationship identifier. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.getRelationship("rel-bob-owns-sneaker-42").async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Fetched relationship ${value.data.id} with payload ${value.data.payload}")
    }
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "rel-bob-owns-sneaker-42",
        "entityAId": "seller-bob",
        "entityBId": "product-sneaker-42",
        "relationshipClass": "ProductOwner",
        "relationshipClassVersion": 1,
        "payload": { "since": "2026-07-13" },
        "createdAt": "2026-07-13T09:20:00.000Z",
        "updatedAt": "2026-07-13T09:20:00.000Z",
        "eTag": "YzAbCdEfGhIjKl"
    }
}
```

### Get all relationships

Returns a paginated list of relationships within a class. The `className` parameter is required. Filter by `entityAId` or `entityBId` to list a specific entity's links. For pagination, filtering, and sorting, refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination).

#### Method(s)

```kotlin
pubnub.dataSync.getRelationships(
    className: String,
    entityAId: String? = null,
    entityBId: String? = null,
    classVersion: Int? = null,
    filterFast: String? = null,
    filter: String? = null,
    sort: List<PNDataSyncSortField> = emptyList(),
    limit: Int? = null,
    cursor: String? = null,
): GetRelationships
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| className | String | Yes |  | Name of the relationship class to list. |
| entityAId | String | Optional |  | List only relationships whose first entity is this id. |
| entityBId | String | Optional |  | List only relationships whose second entity is this id. |
| classVersion | Int | Optional | `all versions` | Relationship class version to list. Omit to list relationships across every version of the class. |
| filterFast | String | Optional |  | Filter expression evaluated against strongly consistent storage, so it reflects the latest writes. Accepts up to 10 conditions by default (raisable per keyset), over properties declared with filtering mode `simple` or `full`. Cannot be combined with `filter`. |
| filter | String | Optional |  | Filter expression evaluated against eventually consistent storage, so results can briefly lag writes. Supports the full expression language, over properties declared with filtering mode `full`. Cannot be combined with `filterFast`. |
| sort | List<PNDataSyncSortField> | Optional | `empty list` | Order results. Each entry names a property and a direction. |
| limit | Int | Optional | `20` | Maximum number of relationships per page. Max `100`. |
| cursor | String | Optional |  | Opaque pagination cursor. Omit for the first page. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.getRelationships(
    className = "ProductOwner",
    limit = 10
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        value.data.forEach { println(it.id) }
        println("More pages available: ${value.next.hasNext}")
    }
}
```

#### Response

```json
{
    "status": 200,
    "data": [
        {
            "id": "rel-bob-owns-sneaker-42",
            "entityAId": "seller-bob",
            "entityBId": "product-sneaker-42",
            "relationshipClass": "ProductOwner",
            "relationshipClassVersion": 1,
            "payload": { "since": "2026-07-13" },
            "createdAt": "2026-07-13T09:20:00.000Z",
            "updatedAt": "2026-07-13T09:20:00.000Z",
            "eTag": "YzAbCdEfGhIjKl"
        }
    ],
    "meta": {
        "next_cursor": null,
        "has_next": false,
        "limit": 20
    }
}
```

#### Other examples

##### List an entity's incoming links with entityBId

Pass `entityBId` instead of `entityAId` to list relationships where the entity is on the second side of the link.

```kotlin
pubnub.dataSync.getRelationships(
    className = "ProductOwner",
    entityBId = "product-sneaker-42",
    limit = 50
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        value.data.forEach { println("${it.entityAId} owns ${it.entityBId}") }
        println("More pages available: ${value.next.hasNext}")
    }
}
```

##### Filter with filterFast

`filterFast` is evaluated against strongly consistent storage, so it matches an object you just wrote. It runs over properties declared with filtering mode `simple` or `full` and accepts up to 10 conditions by default (raisable per keyset). Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filter`, so only one of the two can be sent per call.

```kotlin
// `tier` and `since` must be declared filterable (`simple` or `full`) on the `ProductOwner` class
pubnub.dataSync.getRelationships(
    className = "ProductOwner",
    filterFast = "tier == \"gold\"",
    sort = listOf(PNDataSyncSortField(property = "since", ascending = false)),
    limit = 20
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        value.data.forEach { println(it.id) }
        println("More pages available: ${value.next.hasNext}")
    }
}
```

##### Filter with filter

`filter` runs over properties declared with filtering mode `full` and is evaluated against eventually consistent storage, so a very recent write may not be matched yet. Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filterFast`, so only one of the two can be sent per call.

```kotlin
// `filter` only accepts properties declared with `full` filtering on the `ProductOwner` class
pubnub.dataSync.getRelationships(
    className = "ProductOwner",
    filter = "tier LIKE \"gold*\"",
    limit = 20
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        value.data.forEach { println(it.id) }
        println("More pages available: ${value.next.hasNext}")
    }
}
```

##### Page through results with cursor

Pass no `cursor` on the first call. Take `next.cursor` from the result and pass it back as `cursor` on the next call. Stop when `next.hasNext` is `false`.

```kotlin
fun fetchPage(cursor: String?) {
    pubnub.dataSync.getRelationships(
        className = "ProductOwner",
        limit = 20,
        cursor = cursor
    ).async { result ->
        result.onFailure { exception ->
            println("Failed: ${exception.message}")
        }.onSuccess { value ->
            value.data.forEach { println(it.id) }
            if (value.next.hasNext) {
                fetchPage(value.next.cursor)
            }
        }
    }
}

fetchPage(cursor = null)
```

### Set relationship

Replaces a relationship in full (PUT). Send the complete set of fields, any field you omit is cleared. `className` is immutable after creation and cannot be sent, and the linked entity ids are immutable too, so `setRelationship` doesn't expose `entityAId`/`entityBId` at all, there's nothing to resend. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for `ifMatch`. For a partial update, use [Update relationship](#update-relationship).

#### Method(s)

```kotlin
pubnub.dataSync.setRelationship(
    relationshipId: String,
    classVersion: Int,
    status: String? = null,
    payload: Any? = null,
    ifMatch: String? = null,
): SetRelationship
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| relationshipId | String | Yes |  | Relationship identifier. |
| classVersion | Int | Yes |  | Version of the relationship class schema. |
| status | String | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | Any | Optional |  | Free-form JSON object holding your application data. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The update succeeds only if it still matches, otherwise the server returns `412`. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.setRelationship(
    relationshipId = "rel-bob-owns-sneaker-42",
    classVersion = 1,
    payload = mapOf("since" to "2026-07-13", "tier" to "gold")
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Replaced relationship ${value.data.id}, new eTag ${value.data.eTag}")
    }
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "rel-bob-owns-sneaker-42",
        "entityAId": "seller-bob",
        "entityBId": "product-sneaker-42",
        "relationshipClass": "ProductOwner",
        "relationshipClassVersion": 1,
        "payload": { "since": "2026-07-13", "tier": "gold" },
        "createdAt": "2026-07-13T09:20:00.000Z",
        "updatedAt": "2026-07-13T14:00:00.000Z",
        "eTag": "AbCdEfGhIjKlMn"
    }
}
```

### Update relationship

Applies a partial update to a relationship with raw JSON Patch operations. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for the operation model.

#### Method(s)

```kotlin
pubnub.dataSync.updateRelationship(
    relationshipId: String,
    operations: List<PNJsonPatchOperation>,
    ifMatch: String? = null,
): UpdateRelationship
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| relationshipId | String | Yes |  | Relationship identifier. |
| operations | List<PNJsonPatchOperation> | Yes |  | One or more JSON Patch operations. Must contain at least one item. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The patch succeeds only if it still matches, otherwise the server returns `412`. |

Use a JSON Pointer that starts with `/payload/` to target payload fields, or a root pointer (for example `/status`) to target a top-level field.

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.updateRelationship(
    relationshipId = "rel-bob-owns-sneaker-42",
    operations = listOf(
        PNJsonPatchOperation(op = "replace", path = "/payload/tier", value = "platinum")
    )
).async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Updated relationship ${value.data.id}, new eTag ${value.data.eTag}")
    }
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "rel-bob-owns-sneaker-42",
        "entityAId": "seller-bob",
        "entityBId": "product-sneaker-42",
        "relationshipClass": "ProductOwner",
        "relationshipClassVersion": 1,
        "payload": { "since": "2026-07-13", "tier": "platinum" },
        "createdAt": "2026-07-13T09:20:00.000Z",
        "updatedAt": "2026-07-13T14:05:00.000Z",
        "eTag": "CdEfGhIjKlMnOp"
    }
}
```

### Remove relationship

Deletes a relationship by `relationshipId`.

#### Method(s)

```kotlin
pubnub.dataSync.removeRelationship(
    relationshipId: String,
    ifMatch: String? = null,
): RemoveRelationship
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| relationshipId | String | Yes |  | Relationship identifier. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The delete succeeds only if it still matches, otherwise the server returns `412`. |

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

```kotlin
val pubnub = PubNub.create(
    PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()
)

pubnub.dataSync.removeRelationship("rel-bob-owns-sneaker-42").async { result ->
    result.onFailure { exception ->
        println("Failed: ${exception.message}")
    }.onSuccess { value ->
        println("Removed relationship, HTTP status ${value.status}")
    }
}
```

#### Response

```json
{
    "status": 200
}
```

## Real-time updates

DataSync objects can publish `create`, `update`, and `delete` events that you receive in real time with a `dataSync` listener on a `Subscription`, a `SubscriptionSet`, or the PubNub client. Create a DataSync SDK entity for the object ([DataSyncUser](https://www.pubnub.com/docs/sdks/kotlin/entities/data-sync-user.md), [DataSyncChannel](https://www.pubnub.com/docs/sdks/kotlin/entities/data-sync-channel.md), or [DataSyncEntity](https://www.pubnub.com/docs/sdks/kotlin/entities/data-sync-entity.md)), subscribe to it, and attach the listener, as described in [Add DataSync listener](https://www.pubnub.com/docs/sdks/kotlin/api-reference/publish-and-subscribe.md#add-datasync-listener).

```kotlin
val subscription = pubnub.channel("product-sneaker-42").subscription()

subscription.addListener(object : EventListener {
    override fun dataSync(pubnub: PubNub, result: PNDataSyncEventResult) {
        when (val message = result.extractedMessage) {
            is PNSetDataSyncUserEventMessage ->
                println("User ${message.data.id} ${message.event}")
            is PNSetDataSyncChannelEventMessage ->
                println("Channel ${message.data.id} ${message.event}")
            is PNSetDataSyncMembershipEventMessage ->
                println("Membership ${message.data.id} ${message.event}")
            is PNSetDataSyncEntityEventMessage ->
                println("Entity ${message.data.id} ${message.event}")
            is PNSetDataSyncRelationshipEventMessage ->
                println("Relationship ${message.data.id} ${message.event}")
            is PNDeleteDataSyncUserEventMessage ->
                println("User ${message.id} deleted at ${message.deletedAt}")
            is PNDeleteDataSyncChannelEventMessage ->
                println("Channel ${message.id} deleted at ${message.deletedAt}")
            is PNDeleteDataSyncMembershipEventMessage ->
                println("Membership ${message.id} deleted at ${message.deletedAt}")
            is PNDeleteDataSyncEntityEventMessage ->
                println("Entity ${message.id} deleted at ${message.deletedAt}")
            is PNDeleteDataSyncRelationshipEventMessage ->
                println("Relationship ${message.id} deleted at ${message.deletedAt}")
            else ->
                println("Unknown DataSync event of type ${message.type}")
        }
    }
})

subscription.subscribe()
```

Each event arrives as a `PNDataSyncEventResult`. Its `extractedMessage` names the object kind in `type` (`user`, `channel`, `membership`, `entity`, or `relationship`) and carries the object state in `data`. A `create` or `update` event is a `PNSetDataSync*EventMessage` whose `event` is `CREATE` or `UPDATE`. For a `delete` event, a `PNDeleteDataSync*EventMessage` carries only the `id` and the `deletedAt` timestamp.

`type` names the object kind directly, while the message class tells you which typed state container the event carries:

| Change to | `type` | On `create` or `update` | On `delete` |
| --- | --- | --- | --- |
| A user | `user` | `PNSetDataSyncUserEventMessage` with `PNDataSyncUserData` | `PNDeleteDataSyncUserEventMessage` |
| A channel | `channel` | `PNSetDataSyncChannelEventMessage` with `PNDataSyncChannelData` | `PNDeleteDataSyncChannelEventMessage` |
| An entity | `entity` | `PNSetDataSyncEntityEventMessage` with `PNDataSyncEntityData` | `PNDeleteDataSyncEntityEventMessage` |
| A membership | `membership` | `PNSetDataSyncMembershipEventMessage` with `PNDataSyncMembershipData` | `PNDeleteDataSyncMembershipEventMessage` |
| A relationship | `relationship` | `PNSetDataSyncRelationshipEventMessage` with `PNDataSyncRelationshipData` | `PNDeleteDataSyncRelationshipEventMessage` |

Branch on the message class with a `when` expression, and always add an `else` branch, because an event the SDK does not recognize arrives as a `PNUnknownDataSyncEventMessage` that keeps the raw `type`, `event`, `metadata`, and `data`. `className` tells you the specific class within a kind, for example which subclass of `User` an event belongs to.

### Where each event is delivered

The channels that receive an event depend on the changed object. A relationship or membership never publishes on a channel named after its own id:

| Change to | On `create` | On `update` or `delete` |
| --- | --- | --- |
| A user | The user's `id` | The user's `id`, plus the `id` of every entity, user, or channel connected to it by a relationship or membership |
| A channel | The channel's `id` | The channel's `id`, plus the `id` of every entity, user, or channel connected to it by a relationship or membership |
| An entity | The entity's `id` | The entity's `id`, plus the `id` of every entity, user, or channel connected to it by a relationship or membership |
| A membership | **Both** the `userId` and the `channelId` of the membership | Same as `create` |
| A relationship | **Both** the `entityAId` and the `entityBId` of the relationship | Same as `create` |

:::note Update and delete also fan out to connected objects
An update or delete on a user, channel, or entity is also delivered on the `id` channel of every other object connected to it by a relationship or membership, in either direction, at the time of the change. A client subscribed to a connected object's channel receives the event too, even though that object itself did not change. A create does not fan out this way, because nothing can be connected to a brand new object yet.
The connected channels are entity, user, and channel ids. Relationships and memberships never get an id channel of their own, so they never appear in this fan-out as a channel name.
:::

So to see memberships appear and disappear for Alice, subscribe to `user-alice` rather than the membership id. A client subscribed to both sides of the same link receives the change twice, once per channel. Deduplicate create and update events on the object's `id` and `updatedAt`, and delete events on `id` and `deletedAt`.

For a membership event, `PNDataSyncMembershipData` carries `channelId` and `userId` directly, so you don't map them onto generic A and B sides. A relationship event carries `entityAId` and `entityBId`.

### Projection channels

Each [projection](https://www.pubnub.com/docs/sdks/kotlin/api-reference/access-manager.md#grant-token) declared on the class gets its own event, published to its own channel, and carrying only that projection's view of the payload:

| Projection | Channel | Payload |
| --- | --- | --- |
| `__default__` (the base projection) | The object's own id, for example `product-sneaker-42` | The fields tagged `__default__` |
| Any named projection, for example `admin` | `__<projection>__<id>`, for example `__admin__product-sneaker-42` | The fields tagged with that projection |

Filtering applies to `payload` and to `status`: each is included in a given projection's event only if the class declares it under that projection, falling back to `__default__` when the class never declares `status`. `id`, `eTag`, `createdAt`, `updatedAt`, and `expiresAt` are never filtered. Every projection's event carries them unchanged.

So one change to an object whose class declares an `admin` projection publishes two events, and a client subscribed only to `product-sneaker-42` never sees the `admin`-only fields:

```kotlin
val entity = pubnub.dataSyncEntity("product-sneaker-42")

val defaultSubscription = entity.subscription()
val adminSubscription = entity.subscription("admin")

defaultSubscription.subscribe()
adminSubscription.subscribe()
```

If the class declares no properties at all there is nothing to filter, so a single unfiltered event is published to the object's own id channel.

:::warning Projection channels need channel grants
Publishing to `__<projection>__<id>` is an ordinary channel publish, and it isn't gated by the projection assignments in a token. Use Access Manager channel grants to control who can subscribe to a projection channel. Anyone who can subscribe there receives the restricted fields. Refer to [Grant token](https://www.pubnub.com/docs/sdks/kotlin/api-reference/access-manager.md#grant-token).
:::

Delete events are never filtered by a projection.

Events are off by default and are enabled per class in the [Admin Portal](https://admin.pubnub.com). Refer to [enabling events](https://www.pubnub.com/docs/data-storage/structured-data/events.md#enable-datasync-events) for how to turn them on, and [receiving events](https://www.pubnub.com/docs/data-storage/structured-data/events.md) for the listener flow.

Last updated at: 2026-10-08T04:47:34.000Z
