Offline sync
Offline sync lets your app read and write data with or without a connection. The serverpod_offline_sync module keeps that data up to date on the server and on every device that shares it. You mark a table with database: sync and read and write it with the same generated model methods as any other table. To add offline sync to your project, see Set up offline sync.
When to use offline sync
Offline sync settles conflicting edits automatically, and a change takes effect on the device before the server sees it.
Offline sync suits data that users author and own, because nobody needs to approve their edits.
Offline sync doesn't suit data that the server must check before a change counts. Put that data in normal tables behind endpoints, which are server methods your app calls over the network.
This table shows where each kind of data belongs:
| Data | Where it goes | Why |
|---|---|---|
| User-authored data, such as notes, tasks, lists, preferences, and team workspaces | Synced tables | Edits to different columns of one item both survive. On the same column, the newer write wins. |
| Server-checked data, such as balances, stock levels, usernames unique across all users, and anything one user must not overwrite for another | Normal tables behind endpoints | Only the server can enforce the rule, so these features need a connection. |
How sync works
Each device keeps its own copy of the synced tables in the client-side database. Your app reads and writes that local copy. When your app syncs, the device sends its local changes to the server and receives changes made on other devices. Devices don't sync with each other directly, so every change reaches other devices through the server.
Sometimes two devices change the same row before either device has synced. For example, a user renames a task on a phone while a teammate marks the task done on a laptop. Combining the two changes into one result is called a merge. Once all changes have synced, every copy matches. The server and every device apply the same merge rules:
- Columns merge independently, and the newest write wins. In the task example, the task ends up renamed and done. When two devices edit the same column, the write with the newer timestamp wins. The device's clock sets that timestamp when the write happens, not when the device syncs. Without the
relationkeyword, aList,Map,Set, or nested model field counts as one column and is replaced whole. - Deletes hide rows. A deleted row stays in the table, hidden from queries, includes, and watches.
- Merges keep relations valid. A foreign key links a child row to its parent row. When a merge combines changes from two devices, the module repairs any foreign key those changes broke. When one device deletes a parent row while another adds a child row to that parent, the relation's
onDeleteaction decides the outcome. - Merges keep unique values unique. A unique index keeps indexed values distinct across rows. When two rows set the same value, the row that set it first keeps that value. The other row reads a replacement, such as
Groceries__conflict__<rowId>, and stays visible so the user can rename the row.
Because of these rules, a value you read can differ from the value a device wrote, as with a renamed unique value or a cleared foreign key. The written value comes back when the cause goes away, for example when the other row changes its value or the parent row is restored. How merges work covers each case.
Spaces and sharing
Every synced row belongs to one space. A space is either a user's personal space or a shared space that other users are members of. Three things shape how you share data:
- Roles cover the whole space. Sharing data means granting a user membership in a space with a read-only or read-write role. There are no per-row permissions.
- Sharing happens on the server. Your server creates shared spaces and grants membership from your endpoints. Because sharing runs on the server, a device can't start sharing while offline.
- Serverpod adds
spaceIdto every synced table. ThespaceIdfield links each row to its space.
To create shared spaces and grant membership, see Share data with spaces.
Limits
Offline sync has these limits:
- Sync needs a signed-in user with a UUID id. Users who sign in with the authentication module have UUID ids. The legacy auth module gives users integer ids, so projects that still use it can't sync.
- Synced tables have stricter modeling rules. Row ids are UUIDs, relations connect only synced tables, required foreign keys need the
deferredkeyword, and unique indexes are per space. Model synced data covers every rule, andserverpod generatereports most broken rules. - Schema changes stop outdated apps from syncing. After most changes to synced tables, such as a new column, every installed app must update before it can sync again. To plan schema changes for installed apps, see Change a synced schema.
- The module doesn't reconnect. You can sync once, or keep a continuous sync running until your app cancels the sync. A continuous sync ends when the connection drops. When connectivity returns, start a new continuous sync in your app. Set up offline sync shows how.
- Changes from devices don't go through your endpoints. Before applying a change, the module checks that the user is a member of the space with write access. The module also checks that the row belongs to that space. There is no hook to inspect or reject a change before it's applied. Put any validation that needs the server in an endpoint.
- Deleted rows and sync metadata stay in the database. Every written column keeps a timestamp, and a deleted row stays hidden in its table with a record of the delete. For storage and timing overhead, see the Performance section on pub.dev.
Rules for every write
Three rules keep your code from losing another device's edits, writing rows that never sync, or reading other users' rows:
-
Update only the columns that changed. Every column listed in an update gets a new timestamp, even when the column's value didn't change. So a full-row save, which lists every column, can overwrite another device's edit to a column the current user never touched. Pass
columns:toupdateRow, useupdateByIdwithcolumnValues:, or giveupsertRowanupdateColumns:list.await Task.db.updateRow(session,task.copyWith(title: title),columns: (t) => [t.title],); -
Leave
spaceIdto the module, and never write to a synced table with raw SQL. The module setsspaceIdon every insert and rejects writes that changespaceId. A row written with raw SQL has no space and is never synced. -
On the server, read and write synced tables inside
transactionForUser, and pass its transaction to every call. A transaction is a group of database operations that succeed or fail together. CallingtransactionForUserruns a transaction as the user whose id you pass. Reads and writes that receive the transaction stay inside that user's spaces.The module doesn't compare that user id with the signed-in user. Take the id from
session.authenticatedrather than from a value the app sends.A write without the transaction throws. A read without the transaction returns every user's rows, even inside
transactionForUser. Share data with spaces shows the server pattern.
Where to go next
Each page covers one part of working with synced data:
| Page | Use it to |
|---|---|
| Set up offline sync | Add the module, declare synced tables, open the local database, and run the sync. |
| Model synced data | Design tables so concurrent edits merge the way users expect. |
| Share data with spaces | Give several users access to the same rows from your endpoints. |
| Deleted and hidden rows | Show what users deleted, build a trash, and restore rows. |
| How merges work | Predict a merge or explain synced data that looks wrong. |
| Change a synced schema | Change synced tables after the app is in users' hands. |
| Test offline sync | Run offline sync inside withServerpod tests. |
Related
- Client-side database: the local database synced tables live in, with sessions, device migrations, the web files, and
watch. - Tables: the
databasekeyword and its values.