Docs Menu
Docs Home
/ /
Atlas Device SDKs
/ /

Write Data to a Synced Realm - Kotlin SDK

On this page

  • Determining What Data Syncs
  • App Services Configuration
  • Client Data Model and Configuration
  • Write to a Synced Realm
  • Successful Writes
  • Compensating Writes
  • Write Doesn't Match the Query Subscription
  • Write Doesn't Match Permissions
  • Compensating Write Error Information
  • Group Writes for Improved Performance

When writing data to a synced realm using Flexible Sync, you can use the same APIs as writing to a local realm. However, there are some differences in behavior to keep in mind as you develop your application.

When you write to a synced realm, your write operations must match both of the following:

  • The sync subscription query

  • The permissions in your App Services App

If you try to write data that doesn't match either the query subscription or the user's permissions, Realm reverts the write with a non-fatal error operation called a compensating write.

To learn more about configuring permissions for your app, see Role-based Permissions and the Device Sync Permissions Guide in the App Services documentation.

To learn more about permission denied errors, compensating write errors, and other Device Sync error types, refer to Sync Errors in the App Services documentation.

The data that you can write to a synced realm is determined by the following:

  • Your Device Sync configuration

  • Permissions in your App

  • The Flexible Sync subscription query used when you open the realm

The examples on this page use an Atlas App Services App with the following Device Sync configuration and a client app with the following Realm SDK data model and subscriptions.

In this example, the client app uses the following object model:

class Item : RealmObject {
@PrimaryKey
var _id: ObjectId = ObjectId()
var ownerId: String = ""
var itemName: String = ""
var complexity: Int = 0
}

Based on the above example object model, Device Sync is configured with the following queryable fields:

  • _id (always included)

  • complexity

  • ownerId

The App Services App has permissions configured to let users read and write only their own data:

{
"roles": [
{
"name": "readOwnWriteOwn",
"apply_when": {},
"document_filters": {
"write": {
"ownerId": "%%user.id"
},
"read": {
"ownerId": "%%user.id"
}
},
"read": true,
"write": true,
"insert": true,
"delete": true,
"search": true
}
]
}

Any object in the Atlas collection where the ownerId does not match the user.id of the logged-in user cannot sync to this realm.

Using the object model, the examples configure the synced realm to synchronize objects matching this subscription query:

val app = App.create(FLEXIBLE_APP_ID)
val user = app.login(credentials)
val flexSyncConfig = SyncConfiguration.Builder(user, setOf(Item::class))
// Add subscription
.initialSubscriptions { realm ->
add(
// Get Items from Atlas that match the Realm Query Language query.
// Uses the queryable field `complexity`.
// Query matches objects with complexity less than or equal to 4.
realm.query<Item>("complexity <= 4"),
"simple-items"
)
}
.build()
val syncRealm = Realm.open(flexSyncConfig)
syncRealm.subscriptions.waitForSynchronization()
Log.v("Successfully opened realm: ${syncRealm.configuration}")

Any object in the Atlas collection where the complexity property's value is greater than 4 cannot sync to this realm.

Writes to Flexible Sync realms may broadly fall into one of two categories, depending on whether the write matches the permissions and the Flexible Sync subscription query:

  • Successful writes: The written object matches both the query subscription and the user's permissions. The object writes successfully to the realm, and syncs successfully to the App Services backend and other devices.

  • Compensating writes: The written object does not match the subscription query or the user does not have sufficient permissions to perform the write. Realm reverts the illegal write with a compensating write operation.

Tip

If you want to write an object that does not match the query subscription, you can open a different realm where the object matches the query subscription. Alternately, you could write the object to a non-synced realm that does not enforce permissions or subscription queries.

When the write matches both user permissions and the query subscription in the client, the Realm Kotlin SDK can successfully write the object to the synced realm. This object syncs with the App Services backend when the device has a network connection.

// Per the Device Sync permissions, users can only read and write data
// where the `Item.ownerId` property matches their own user ID.
val userId = user.id
val newItem = Item().apply {
ownerId = userId
itemName = "This item meets sync criteria"
complexity = 3
}
syncRealm.write {
// `newItem` is successfully written to the realm and synced to Atlas
// because its data matches the subscription query (complexity <= 4)
// and its `ownerId` field matches the user ID.
copyToRealm(newItem)
}

When the write doesn't match either the query subscription or user permissions, Realm reverts the write and throws a CompensatingWriteException.

In more detail, when you write data that is outside the bounds of a query subscription or does not match the user's permissions, the following occurs:

  1. Because the client realm has no concept of "illegal" writes, the write initially succeeds until Realm resolves the changeset with the App Services backend.

  2. Upon sync, the server applies the rules and permissions. The server determines that the user does not have authorization to perform the write.

  3. The server sends a revert operation, called a "compensating write", back to the client.

  4. The client's realm reverts the illegal write operation.

Any client-side writes to a given object between an illegal write to that object and the corresponding compensating write will be lost. In practice, this may look like the write succeeding, but then the object "disappears" when Realm syncs with the App Services backend and performs the compensating write.

When this occurs, you can refer to the App Services logs or use the CompensatingWriteInfo object in the client to get additional information on the error.

Given the configuration for the Flexible Sync realm detailed above, attempting to write this object results in a compensating write error because the object does not match the query subscription:

// The complexity of this item is `7`. This is outside the bounds
// of the subscription query, which triggers a compensating write.
val itemTooComplex = Item().apply {
ownerId = user.id
itemName = "This item is too complex"
complexity = 7
}
syncRealm.write {
copyToRealm(itemTooComplex)
}
[Session][CompensatingWrite(231)] Client attempted a write that is disallowed by permissions, or modifies an object outside the current query, and the server undid the change.

You will see the following error message in the App Services logs:

Error:
Client attempted a write that is outside of permissions or query filters; it has been reverted (ProtocolErrorCode=231)
Details:
{
"Item": {
"63bdfc40f16be7b1e8c7e4b7": "write to \"63bdfc40f16be7b1e8c7e4b7\"
in table \"Item\" not allowed; object is outside of
the current query view"
}
}

Given the permissions in the Device Sync configuration detailed above, attempting to write this object results in a compensating write error because the ownerId property does not match the user.id of the logged-in user:

// The `ownerId` of this item does not match the `user.id` of the logged-in
// user. The user does not have permissions to make this write, which
// triggers a compensating write.
val itemWithWrongOwner = Item().apply {
ownerId = "not the current user"
itemName = "A simple item"
complexity = 1
}
syncRealm.write {
copyToRealm(itemWithWrongOwner)
}
[Session][CompensatingWrite(231)] Client attempted a write that is disallowed by permissions, or modifies an object outside the current query, and the server undid the change.

You will see the following error message in the App Services logs:

Error:
Client attempted a write that is outside of permissions or query filters; it has been reverted (ProtocolErrorCode=231)
Details:
{
"Item": {
"63bdfc40f16be7b1e8c7e4b7": "write to \"63bdfc40f16be7b1e8c7e4b7\"
in table \"Item\" was denied by write filter in role \"readOwnWriteOwn\""
}
}

New in version 1.9.0.

You can get additional information in the client about why a compensating write occurs using the CompensatingWriteInfo object, which provides:

  • The objectType of the object the client attempted to write

  • The primaryKey of the specific object

  • The reason for the compensating write error

This information is the same information you can find in the App Services logs. The Kotlin SDK exposes this object on the client for convenience and debugging purposes.

The following shows an example of how you might log information about compensating write errors:

val syncErrorHandler = SyncSession.ErrorHandler { session, error ->
runBlocking {
if (error is CompensatingWriteException) {
error.writes.forEach { writeInfo ->
val errorMessage = """
A write was rejected with a compensating write error
The write to object type: ${writeInfo.objectType}
With primary key of: ${writeInfo.primaryKey}
Was rejected because: ${writeInfo.reason}
""".trimIndent()
Log.e(errorMessage)
}
}
}
}
A write was rejected with a compensating write error
The write to object type: Item
With primary key of: RealmAny{type=OBJECT_ID, value=BsonObjectId(649f2c38835cc0346b861b74)}
Was rejected because: write to "649f2c38835cc0346b861b74" in table "Item" not allowed; object is outside of the current query view
  • The Item in this message is Item object used in the object model on this page.

  • The primary key is the objectId of the specific object the client attempted to write.

  • The table "Item" refers to the Atlas collection where this object would sync.

  • The reason object is outside of the current query view in this example is because the query subscription was set to require the object's complexity property to be less than or equal to 4, and the client attempted to write an object outside of this boundary.

Every write transaction for a subscription set has a performance cost. If you need to make multiple updates to a Realm object during a session, consider keeping edited objects in memory until all changes are complete. This improves sync performance by only writing the complete and updated object to your realm instead of every change.

Back

Manage Subscriptions