DataSync API for Kotlin SDK
DataSync 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.
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.
The two meet in the DataSync SDK entities (DataSyncUser, DataSyncChannel, and DataSyncEntity): 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, not through this SDK:
- Entity classes, which back users, channels, and custom entities: list, read, create, replace, and delete. Partial updates aren't implemented; replace the complete class version instead.
- Relationship classes, which back memberships and custom relationships: list, read, create, replace, and delete.
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 each field belongs to, and how long the object lives before it expires. Refer to 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?>.
#
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 for details.
#
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.
danger
filter is not the strongly consistent oneThe 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:
1filterFast = "price < 100" // strongly consistent, single condition
2filterFast = "(price < 100 && stock > 0) || price > 500" // strongly consistent, grouped conditions
3filter = "name LIKE \"*sneaker*\"" // eventually consistent, needs filtering mode "full"
4filter = "!(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 for the two filtering tiers, and 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:
1sort = listOf(PNDataSyncSortField("price", ascending = false)) // single field, descending
2sort = listOf(PNDataSyncSortField("type"), PNDataSyncSortField("price", false)) // type ascending, then price descending
3sort = 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.
#
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 for details.
#
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 for details.
Correct patch forms:
1PNJsonPatchOperation(op = "add", path = "/payload/tags", value = "sale") // adds a value inside payload.tags
2PNJsonPatchOperation(op = "replace", path = "/payload/price", value = 79.99) // replaces payload.price
3PNJsonPatchOperation(op = "remove", path = "/payload/tempFlag") // removes payload.tempFlag
4PNJsonPatchOperation(op = "move", from = "/payload/oldTag", path = "/payload/tag")
5PNJsonPatchOperation(op = "copy", from = "/payload/price", path = "/payload/msrp")
6PNJsonPatchOperation(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().
#
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 for details.
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.
1val channel = pubnub.channel("channelName")
2
3channel.publish("This SDK rules!").async { result ->
4 result.onFailure { exception ->
5 // Handle error
6 }.onSuccess { value ->
7 // Handle successful method result
8 }
9}
Requires Access Manager
DataSync requires that the Access Manager add-on is enabled for your key in the Admin Portal. Read the support page 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 for the concept.
A user is an entity of the built-in User entity class, 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 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)
1pubnub.dataSync.createUser(
2 classVersion: Int,
3 userId: String? = null,
4 className: String? = null,
5 classLevel: PNDataSyncClassLevel? = null,
6 status: String? = null,
7 payload: Any? = null,
8): CreateUser
classVersionrequired#- Version of the user class schema.
userId#- User identifier. Omit to let the server generate a UUID. Max 255 characters.
className#- Name of the entity class this user belongs to. Must be
Useror one of its subclasses. Defaults toUseron the server if omitted. Set at creation and immutable afterward. classLevel#- Class hierarchy level of
className, eitherGLOBALfor a class the service provides orSUBKEYfor one defined on your keyset. Used to disambiguate classes with the same name defined at different levels. Set at creation and immutable afterward. status#- Free-form lifecycle status. Max 100 characters.
payload#- Free-form JSON object holding your application data.
Sample code
1
Response
1{
2 "status": 201,
3 "data": {
4 "id": "user-alice",
5 "entityClass": "User",
6 "entityClassVersion": 1,
7 "entityClassLevel": "Global",
8 "payload": { "name": "Alice", "type": "shopper" },
9 "createdAt": "2026-07-13T09:00:00.000Z",
10 "updatedAt": "2026-07-13T09:00:00.000Z",
11 "eTag": "AbCdEfGhIjKlMn"
12 }
13}
Get user
Returns a single user by userId.
Method(s)
1pubnub.dataSync.getUser(
2 userId: String,
3): GetUser
userIdrequired#- User identifier.
Sample code
1
Response
1{
2 "status": 200,
3 "data": {
4 "id": "user-alice",
5 "entityClass": "User",
6 "entityClassVersion": 1,
7 "entityClassLevel": "Global",
8 "payload": { "name": "Alice", "type": "shopper" },
9 "createdAt": "2026-07-13T09:00:00.000Z",
10 "updatedAt": "2026-07-13T09:00:00.000Z",
11 "eTag": "AbCdEfGhIjKlMn"
12 }
13}
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.
Method(s)
1pubnub.dataSync.getUsers(
2 className: String? = null,
3 classVersion: Int? = null,
4 classLevel: PNDataSyncClassLevel? = null,
5 filterFast: String? = null,
6 filter: String? = null,
7 sort: List<PNDataSyncSortField> = emptyList(),
8 limit: Int? = null,
9 cursor: String? = null,
10): GetUsers
className#- User class to list. Omit to list the Global
Userclass and all of its subclasses. classVersion#- User class version to list. Omit to list users across every version of the class.
classLevel#- Class hierarchy level of
className, eitherGLOBALfor a class the service provides orSUBKEYfor one defined on your keyset. Used to disambiguate a class name defined at both levels. filterFast#- 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
simpleorfull. Cannot be combined withfilter. filter#- 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 withfilterFast. sort#- Order results. Each entry names a property and a direction, for example
PNDataSyncSortField("createdAt", ascending = false). limit#- Maximum number of users per page. Max
100. cursor#- Opaque pagination cursor. Omit for the first page.
Sample code
1
Response
1{
2 "status": 200,
3 "data": [
4 {
5 "id": "user-alice",
6 "entityClass": "User",
7 "entityClassVersion": 1,
8 "entityClassLevel": "Global",
9 "payload": { "name": "Alice", "type": "shopper" },
10 "createdAt": "2026-07-13T09:00:00.000Z",
11 "updatedAt": "2026-07-13T09:00:00.000Z",
12 "eTag": "AbCdEfGhIjKlMn"
13 }
14 ],
15 "meta": {
show all 20 linesOther 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.
1
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.
1
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.
1
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 for ifMatch. For a partial update, use Update user.
Method(s)
1pubnub.dataSync.setUser(
2 userId: String,
3 classVersion: Int,
4 status: String? = null,
5 payload: Any? = null,
6 ifMatch: String? = null,
7): SetUser
userIdrequired#- User identifier.
classVersionrequired#- Version of the user class schema.
status#- Free-form lifecycle status. Max 100 characters.
payload#- Free-form JSON object holding your application data.
ifMatch#- The
eTagfrom a prior read. The update succeeds only if it still matches, otherwise the server returns412.
Sample code
1
Response
1{
2 "status": 200,
3 "data": {
4 "id": "user-alice",
5 "entityClass": "User",
6 "entityClassVersion": 1,
7 "entityClassLevel": "Global",
8 "payload": { "name": "Alice B.", "type": "shopper" },
9 "createdAt": "2026-07-13T09:00:00.000Z",
10 "updatedAt": "2026-07-13T10:15:00.000Z",
11 "eTag": "CdEfGhIjKlMnOp"
12 }
13}
Update user
Applies a partial update to a user with raw JSON Patch operations. Refer to partial update for the operation model.
Method(s)
1pubnub.dataSync.updateUser(
2 userId: String,
3 operations: List<PNJsonPatchOperation>,
4 ifMatch: String? = null,
5): UpdateUser
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
1
Response
1{
2 "status": 200,
3 "data": {
4 "id": "user-alice",
5 "status": "active",
6 "entityClass": "User",
7 "entityClassVersion": 1,
8 "entityClassLevel": "Global",
9 "payload": { "name": "Alice B.", "type": "shopper" },
10 "createdAt": "2026-07-13T09:00:00.000Z",
11 "updatedAt": "2026-07-13T10:20:00.000Z",
12 "eTag": "EfGhIjKlMnOpQr"
13 }
14}
Remove user
Deletes a user by userId.
Method(s)
1pubnub.dataSync.removeUser(
2 userId: String,
3 ifMatch: String? = null,
4): RemoveUser
Sample code
1
Response
1{
2 "status": 200
3}
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 for the concept.
A channel is an entity of the built-in Channel entity class, which the service provides at the Global class level. Subclass it with Create a new entity class to add declared properties, then pass the subclass name as className.