Skip to main content
Version: 4.2.0

Model synced data

A synced table gets edits from many devices, so the way you model it decides what users see after a merge. Synced tables have rules, and serverpod generate checks most of them. A few patterns, covered in the sections below, also keep edits from being lost, mixed, or duplicated.

Rules for synced tables​

Serverpod adds a spaceId field to every synced table. The field records which space owns the row.

The serverpod generate command reports any synced table model that breaks these rules:

RuleWhat to do
The id is a UUIDLeave id out and Serverpod adds one, or declare id: UuidValue?, defaultPersist=random_v7. The id is generated wherever the row is created, so a row created offline has its id right away.
Relations connect only synced tablesTo point at a row in a table that doesn't sync, store its id in a plain field without relation. Give the field the same type as that table's id.
Required relations are deferredAdd deferred to every relation with a non-nullable foreign key, because a merge can add a child row before its parent.
Unique indexes are per spaceList spaceId in the index's fields, as in fields: spaceId, name. An index made only of nullable foreign keys to synced tables can leave it out, such as the index of a one-to-one relation.
Unique indexes have a field offline sync can replaceInclude a String, a nullable field, or a UuidValue without a relation. When two rows conflict, offline sync gives the losing row a replacement value in that field.
One-to-one relations are optionalMake the foreign key nullable.
Every field reaches every member's deviceKeep secrets and server-only data in tables that don't sync, because synced fields can't use scope=serverOnly.

Two more rules apply, but serverpod generate doesn't check them:

  • Unique indexes can't include JSON fields. That covers List, Map, Set, and nested model fields. The server and the app throw a StateError when they first use the database.
  • Relations can't reach another space. A parent in another space counts as missing, so the child is handled as Relations after a merge describes. To link to a row in another space, store its id in a plain UuidValue field without relation. Look it up with a second query, which can come back empty.

Design for concurrent edits​

Each column merges on its own, and the newest write wins. When two devices change the same column, only the newer change survives. The following patterns stop a merge from losing a change, or from mixing two changes into a wrong value:

To storeUseWhy
A list that several devices add to, such as a recipe's ingredientsChild rows with a relation, not a List fieldA List field is one value, so one device's additions are lost.
An order that users rearrangeA double position on each row, sorted by position and then by id. Give a moved row a value between its new neighbors.With int positions, a move rewrites many rows, so a move from one device can be lost.
A count, such as likesOne row per contributor, counted when you readWhen two devices add 1 at the same time, one addition is lost.
One choice among many, such as a default addressOne nullable reference on the row that owns the choice, such as defaultAddressId on a customerA flag on each row can mix two devices' picks into two defaults.
Values that only make sense together, such as an amount and its currencyOne nested model fieldSeparate columns can mix the amount from one device with the currency from another.

Avoid duplicate rows​

Two devices can create the same thing while offline. Each copy gets its own random id, so the merge keeps both as separate rows. The following patterns turn the copies into one row, or let a person resolve them:

To storeUseWhy
Something two devices might create at once, such as a tag named urgentAn id derived from the data, as in Derive ids from the dataBoth devices create the same id, so the merge keeps one row.
A name that must not repeat, such as a list's titleA unique indexThe row that set the name first keeps it. The other row reads <name>__conflict__<rowId> until someone renames it.

Derive ids from the data​

Derive the id from the data that makes the row unique, such as a tag's name or the two rows a link connects:

UuidValue tagId(UuidValue spaceUuid, String name) =>
const Uuid().v5obj(spaceUuid.uuid, 'tag:${name.trim().toLowerCase()}');

Three rules keep derived ids working:

  • Derive ids only from data that identifies one thing. Rows with the same id merge into one row, so two different tasks that share a title, such as "Buy milk", would become one.
  • Build the id from the space's UUID. An id can belong to only one space. If two spaces derive the same id, the second row is rejected, and the device that synced it can't sync until the row is fixed. Troubleshooting shows how to find the row.
  • Insert with ignoreConflicts: true to skip rows that already exist. Another device may have created the row already. The insert also restores the row if a user deleted it.

Choose onDelete for each relation​

Sometimes one device deletes a parent row while another device adds a child row to it. The merge gives the same result as deleting the parent in a database that already has the new child, so the relation's onDelete action decides it:

RelationshiponDeleteResult after the merge
A child owned by its parent, such as a task in a projectCascadeThe child is hidden with the parent, and comes back if the parent is restored.
A child that must keep its parent, such as a line on an invoiceRestrict, NoAction, or noneThe delete is undone, and the parent reappears with the child. If the children that blocked it are deleted later, the parent is hidden again.
An optional link, such as an assigneeSetNull, with a nullable foreign keyThe child stays, and its foreign key reads null. The foreign key points to the parent again if the parent is restored.
A child that falls back to a default parent, such as a note that moves to an Inbox folderSetDefaultThe child's foreign key reads its default value while the row it points to is visible in the same space. Otherwise the delete is undone.

Deletes on a single device follow normal database rules, as Delete rows describes.

Values your code can't write​

Offline sync uses these values for rows that lose a unique value to another row, or give one up:

  • Text in a unique column that ends in __conflict__, __hidden__, or __park__ followed by a UUID
  • A version 8 UUID in a non-nullable unique UuidValue field without a relation

If your code writes one of these values, for example by copying a title like Groceries__conflict__<rowId> to a new row, the write throws OfflineSyncReservedValueException. You can still save a row that holds one of these values, as long as you don't change that value.