MD. NAZMUL ISLAM
HomeServicesPortfolioCase StudiesBlogAboutContact
ResumeLoginSign Up
WatermelonDB Sync Conflict Resolution Guide for Offline Apps
  1. Home
  2. Blog
  3. WatermelonDB Sync Conflict Resolution Guide for Offline Apps
Back to Blog
WatermelonDBOffline FirstReact NativeDatabaseSync

WatermelonDB Sync Conflict Resolution Guide for Offline Apps

November 27, 20266 min read0 views0 comments

Learn how to handle WatermelonDB sync conflicts in offline-first apps with a practical push-and-pull implementation guide.

WatermelonDB Sync Conflict Resolution Guide for Offline Apps

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.

The Problem and Its Symptoms

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:

  • Silent data loss: A user edits a task offline, but when they reconnect, an older server state overwrites their local changes.
  • Infinite sync loops: The client pushes a change, the server rejects it due to an outdated timestamp, and the client tries to push it again indefinitely.
  • Unhandled promise rejections: Uncaught exceptions thrown during the pushChanges phase that crash the app background sync service.

Why It Happens

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.

Step-by-Step Fix: Building a Resilient Sync Handler

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.

Step 1: Prepare Your Backend Endpoint

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(),
  });
});

Step 2: Configure WatermelonDB on the Client

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
  }
}

Step 3: Handle Client-Side Status Clears

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.

How to Check It Worked

To verify your conflict resolution strategy is functioning correctly:

  1. Simulate Offline Edits: Disconnect your device or simulator from the network. Modify a record (e.g., a task title) locally.
  2. Modify Server State: While the client is still offline, update the exact same record via a direct database query or secondary client with a newer timestamp.
  3. Reconnect and Sync: Reconnect your primary device and trigger syncDatabase().
  4. Inspect Local State: Query WatermelonDB directly to verify whether the client respected the server version or gracefully handled the merge without crashing:
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.

How to Prevent It

Preventing sync headaches in production requires proactive architectural choices:

  • Use UUIDs for IDs: Never use auto-incrementing integer IDs in offline-first apps. If two offline devices create a record with ID 1, merging them becomes impossible. Always use UUIDv4 or CUIDs generated on the client.
  • Keep Track of Timestamps Carefully: Rely on millisecond-precision timestamps (Date.now()) or vector clocks for tracking record mutations.
  • Implement Exponential Backoff: Do not bombard your backend with sync retries every second if the network is unstable. Use an exponential backoff utility to retry syncing gracefully.

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

WatermelonDBOffline FirstReact NativeDatabaseSync

Comments

Leave a comment

You must be signed in to comment.

MD. NAZMUL ISLAM

Full-Stack & React Native Developer

Send a project enquiry

Navigation

  • Home
  • About
  • Services
  • Case Studies
  • Blog
  • Contact
  • 한국어 (Korean)

Services

  • Web Development
  • Mobile App Development
  • Custom Software & SaaS
  • SEO & Marketing
  • Domain & Hosting

© 2026 MD. Nazmul Islam. All rights reserved.

Privacy Policy·Terms of Service