
Learn how to handle WatermelonDB sync conflicts in offline-first apps with a practical push-and-pull implementation guide.
When building offline-first applications like my local habit and budget tracker Nept Track, managing local data is only half the battle. The real challenge begins when your users reconnect to the internet and their locally modified records collide with updates made on the server or another device. If you use WatermelonDB for high-performance offline storage in React Native or web apps, you have likely run into the dreaded sync error: Server changes conflict with local unSynced changes.
Developers often type this error into search engines when their synchronization loop crashes or overwrites critical user data without warning. In this post, I will walk you through why WatermelonDB sync conflicts happen and how to write a robust, step-by-step push-and-pull sync function with proper conflict resolution strategies.
WatermelonDB relies on a synchronized pull-and-push architecture. You call synchronize from @nozbe/watermelondb/sync, passing it a pullChanges function and a pushChanges function.
import { synchronize } from '@nozbe/watermelondb/sync'
await synchronize({
database,
pullChanges: async ({ lastPulledAt }) => {
const res = await fetch(`https://api.example.com/sync?since=${lastPulledAt}`)
return await res.json()
},
pushChanges: async ({ changes, lastPulledAt }) => {
await fetch('https://api.example.com/sync', {
method: 'POST',
body: JSON.stringify({ changes, lastPulledAt }),
})
},
})
Symptoms of a broken sync pipeline include:
pushChanges phase that crash the app background sync service.WatermelonDB tracks changes using local columns like _status (created, updated, deleted) and _changed. When you initiate a sync, WatermelonDB packs all locally modified records into the changes object and sends them to your backend.
Conflicts happen because of a race condition known as the Last-Write-Wins (LWW) dilemma, compounded by clock skew between devices and servers. If Device A updates a record at 10:00 AM offline, and Device B updates the same record on the server at 10:05 AM, the backend must decide which version wins. If your backend blindly accepts whatever the client sends last without checking timestamps or revision numbers, you risk wiping out newer data.
Furthermore, if your backend returns an HTTP 409 (Conflict) or throws an error during pushChanges, WatermelonDB does not automatically resolve it. It aborts the synchronization and leaves local records marked with _status: 'updated', trapping them in a persistent limbo.
To fix sync conflicts, we need to implement a strategy on both the backend and the frontend. We will use a Server-Wins with Client-Merge strategy for non-critical fields, or explicitly log conflicts for user resolution.
Your backend must accept the changes payload, iterate through created, updated, and deleted records, and compare server-side modification timestamps (updated_at) with client-side timestamps.
// Express.js backend example
app.post('/api/sync', async (req, res) => {
const { changes, lastPulledAt } = req.body;
const userId = req.user.id;
// 1. Process incoming changes from client
for (const tableName of Object.keys(changes)) {
const tableChanges = changes[tableName];
// Handle updated records
for (const clientRecord of tableChanges.updated) {
const serverRecord = await db.query(
`SELECT * FROM ${tableName} WHERE id = $1`,
[clientRecord.id]
);
if (serverRecord && serverRecord.updated_at > clientRecord.updated_at) {
// Conflict detected! Server has newer data.
// We can either reject or return server state.
console.log(`Conflict on ${tableName}:${clientRecord.id}`);
} else {
// Safe to update
await db.query(
`UPDATE ${tableName} SET title = $1, updated_at = $2 WHERE id = $3`,
[clientRecord.title, clientRecord.updated_at, clientRecord.id]
);
}
}
}
// 2. Fetch changes from server to send back to client
const serverChanges = await getChangesSince(userId, lastPulledAt);
return res.json({
changes: serverChanges,
timestamp: Date.now(),
});
});
On the client side, wrap your synchronize call inside a robust try-catch block with custom error handling to prevent unhandled rejections.
import { synchronize } from '@nozbe/watermelondb/sync';
import { database } from './model'; // Your WatermelonDB instance
export async function syncDatabase() {
try {
await synchronize({
database,
pullChanges: async ({ lastPulledAt }) => {
const response = await fetch(`https://api.example.com/api/sync?lastPulledAt=${lastPulledAt}`, {
headers: {
'Authorization': `Bearer ${await getToken()}`,
},
});
if (!response.ok) {
throw new Error(`Pull failed with status ${response.status}`);
}
const { changes, timestamp } = await response.json();
return { changes, timestamp };
},
pushChanges: async ({ changes, lastPulledAt }) => {
const response = await fetch('https://api.example.com/api/sync', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${await getToken()}`,
},
body: JSON.stringify({ changes, lastPulledAt }),
});
if (!response.ok) {
const errorBody = await response.text();
throw new Error(`Push failed: ${errorBody}`);
}
},
sendCreatedAsUpdated: true,
});
console.log('Sync completed successfully');
} catch (error) {
console.error('Synchronization error:', error.message);
// Handle offline state gracefully, retry later with exponential backoff
}
}
WatermelonDB automatically marks records as synced (_status: 'sycned', _changed: '') once pushChanges resolves successfully without throwing an error. Ensuring your push function throws on any non-2xx status code is critical; otherwise, WatermelonDB will assume the server accepted corrupted or rejected changes and clear local dirty flags prematurely.
To verify your conflict resolution strategy is functioning correctly:
syncDatabase().const tasksCollection = database.get('tasks');
const task = await tasksCollection.find('your-record-id');
console.log('Current task title after sync:', task.title);
console.log('Sync status:', task._status);
If _status is 'synced' and your conflict logic executed cleanly in your server logs, your pipeline is secure.
Preventing sync headaches in production requires proactive architectural choices:
1, merging them becomes impossible. Always use UUIDv4 or CUIDs generated on the client.Date.now()) or vector clocks for tracking record mutations.Need help architecting an offline-first mobile app or secure API sync pipeline for your product? Get in touch and let us build it together.
Tagged with
Leave a comment