Offline-First Sync in Flutter: Architecture & Code Guide

Learn how to architect, build, and optimize production-ready offline-first data synchronization in Flutter using local databases, transactional sync queues, and robust conflict resolution.

Implementing offline first flutter sync requires shifting from a network-centric model—where the UI waits directly for API responses—to a local-first repository architecture where the local database serves as the single source of truth. In a production Flutter application, every user write action is immediately committed to a local store (such as SQLite via Drift), added to an immutable sync queue, and processed asynchronously in the background. This architecture eliminates loading spinners for data mutations, guarantees data retention during network interruptions, and ensures predictable state synchronization once connectivity is restored.

1. Local Database Selection: Relational vs. Key-Value Stores

Choosing the right persistence engine is foundational for offline data sync. Key-value stores like shared_preferences or basic document stores like Hive lack transactional integrity and robust querying capabilities required for complex data relationships. Production applications with multi-entity data dependencies require relational integrity or strictly typed document models.

For scalable Flutter apps, Drift (formerly Moor), built on top of SQLite, is the preferred choice for relational models due to its compile-time query safety, reactive Dart stream bindings, and built-in migration handling. Isar or Hive can be effective for key-value document access, but struggle when enforcing complex relational constraints during background delta syncs.

Feature / Criterion Drift (SQLite) Isar DB Hive
Data Structure Relational / SQL NoSQL / Document NoSQL / Key-Value
Type Safety Compile-time verified SQL Strongly typed schemas Adapter-based serialization
Transactions ACID compliant ACID compliant Limited batch operations
Complex Queries Full JOIN, Subqueries, Aggregates Indexed composite filters Manual manual filter in memory
Stream Support Built-in reactive query streams Built-in collection watchers Box listenable streams

When building enterprise applications using our custom mobile app development services, we structure local storage using Drift tables to mirror server schemas while adding meta-columns required exclusively for sync state control.

2. Architecting the Pending Mutation Sync Queue

To avoid race conditions and lost user input, never attempt to fire HTTP requests directly from UI events when offline stability is required. Instead, write state changes locally and record an explicit mutation entry inside a dedicated sync_queue table.

Defining the Sync Queue Schema

The synchronization queue records the action type, local entity ID, payload JSON, idempotency token, creation timestamp, retry count, and status flags. Here is a baseline schema implementation in Drift:

import 'package:drift/drift.dart';

enum SyncStatus { pending, inProgress, failed }

class SyncQueue extends Table {
  IntColumn get id => integer().autoIncrement()();
  TextColumn get entityId => text()();
  TextColumn get entityType => text()(); // e.g., 'task', 'user_profile'
  TextColumn get action => text()();     // 'CREATE', 'UPDATE', 'DELETE'
  TextColumn get payload => text()();    // Encoded JSON payload
  TextColumn get clientMutationId => text().unique()(); // Idempotency key
  IntColumn get status => intEnum<SyncStatus>()();
  IntColumn get retryCount => integer().withDefault(const Constant(0))();
  DateTimeColumn get createdAt => dateTime()();
}

The Mutative Operations Lifecycle

  1. User Action: User clicks "Save Task".
  2. Local Persist: The repository initiates a database transaction. It updates or inserts the task into the local Tasks table with an isDirty = true flag and appends an item to the SyncQueue table.
  3. UI Update: The UI instantly re-renders using Drift's watch streams listening to the Tasks table.
  4. Sync Trigger: The Sync Engine detects the new pending item and enqueues a background dispatch task.

3. Deterministic Strategies for Data Conflict Resolution

Conflicts occur when a record is modified locally while offline, but another device or system modified the same record on the backend during the intervening time. Resolving these discrepancies deterministically is the core challenge of any offline first flutter sync pipeline.

Strategy A: Last-Write-Wins (LWW) with Server Timestamps

LWW relies on comparing timestamps to determine the current authority. Because mobile device system clocks can drift or be modified by users, never rely on client-generated system clocks for conflict decisions. Always use reliable server-assigned ISO 8601 UTC timestamps or monotonic sequence integers. If the local pending mutation's base version timestamp matches the server's version timestamp, the server accepts the mutation and updates the version marker.

Strategy B: Field-Level Delta Updates

Instead of sending full entity JSON objects back and forth, compute field-level diffs. If Client A updates the user's phoneNumber offline while Client B updates the user's avatarUrl on the web dashboard, the server can apply both operations safely without overwriting either user field.

// Example field delta payload
{
  "entity_id": "usr_89211",
  "client_mutation_id": "b382d790-21a4-4f8a-93cd-5e729a1b5592",
  "base_version": 14,
  "changes": {
    "phone_number": "+19876543210"
  }
}

Strategy C: Conflict Avoidance via CRDTs

For collaboratively edited structures or multi-device real-time sync (such as live whiteboards or operational state tracking), Conflict-free Replicated Data Types (CRDTs) offer mathematical guarantees of eventual consistency without requiring centralized locking. Modern patterns, as covered in our analysis of architectural patterns in modern Flutter development, increasingly move complex conflict logic down into dedicated local native layers or specialized state structures.

4. Implementing Connectivity Monitoring and Sync Execution

Relying purely on network state changes reported by the OS can lead to false positives (e.g., connected to a Wi-Fi router with no active internet access). A robust synchronization engine combines network state event listeners with actual endpoint ping validation.

Building the Sync Manager Service

import 'dart:async';
import 'package:connectivity_plus/connectivity_plus';
import 'package:http/http.dart' as http;

class SyncEngine {
  final AppDatabase _db;
  final ApiClient _apiClient;
  StreamSubscription? _connectivitySub;
  bool _isSyncing = false;

  SyncEngine(this._db, this._apiClient);

  void initialize() {
    _connectivitySub = Connectivity().onConnectivityChanged.listen((results) {
      if (!results.contains(ConnectivityResult.none)) {
        triggerSync();
      }
    });
  }

  Future<void> triggerSync() async {
    if (_isSyncing) return;
    
    // Validate actual internet reachability
    final hasConnection = await _checkRealInternet();
    if (!hasConnection) return;

    _isSyncing = true;
    try {
      final pendingItems = await _db.getPendingSyncItems();
      for (final item in pendingItems) {
        await _processSyncItem(item);
      }
    } finally {
      _isSyncing = false;
    }
  }

  Future<bool> _checkRealInternet() async {
    try {
      final response = await http.get(
        Uri.parse('https://api.yourdomain.com/health'),
      ).timeout(const Duration(seconds: 3));
      return response.statusCode == 200;
    } catch (_) {
      return false;
    }
  }

  Future<void> _processSyncItem(SyncQueueData item) async {
    // Implementation handles HTTP execution, idempotency, and status updates
  }

  void dispose() {
    _connectivitySub?.cancel();
  }
}

5. Handling Edge Cases: Idempotency, Retries, and Exponential Backoff

Background synchronization will inevitably encounter HTTP 5xx errors, timeouts, and authorization failures. Handling these edge cases prevents repeated requests, corrupted database states, and infinite retry loops.

Enforcing Idempotency Keys

Every queued request MUST be assigned a unique client mutation UUID on creation. Pass this key in HTTP headers (e.g., X-Idempotency-Key: uuid-v4). If a network connection drops *after* the backend processes the mutation but *before* the device receives the HTTP 200 OK response, the client will retry the operation once connectivity returns. Seeing the duplicate idempotency key, the backend safely returns the existing success response without reapplying side effects (such as duplicate payment processing or duplicate record creation).

Exponential Backoff with Jitter

Retrying immediately upon failure overloads servers recovering from an outage. Use an exponential backoff algorithm supplemented with random jitter to distribute client retry intervals smoothly over time.

import 'dart:math';

Duration calculateBackoff(int retryAttempt) {
  const baseDelayMs = 1000; // 1 second
  const maxDelayMs = 320000; // ~5.3 minutes
  
  // Calculate 2^retryAttempt * baseDelayMs
  final exponentialMs = baseDelayMs * pow(2, retryAttempt);
  final cappedMs = min(exponentialMs.toInt(), maxDelayMs);
  
  // Apply jitter: +/- 20% random spread
  final random = Random();
  final jitter = cappedMs * 0.2 * random.nextDouble();
  
  return Duration(milliseconds: cappedMs + jitter.toInt());
}

Distinguishing Retryable vs Unrecoverable Errors

Categorize network errors explicitly during processing:

  • Transient Failures (HTTP 408, 429, 502, 503, 504): Keep the queue item status set to pending, increment the retryCount, and schedule a retry using exponential backoff.
  • Authentication Failure (HTTP 401): Pause queue execution, trigger an asynchronous token refresh flow, and resume execution once credentials update.
  • Validation Errors (HTTP 400, 422): The operation is unrecoverable. Mark the queue status as failed, log the failure to error reporting services, revert or flag local records, and remove the item from active queue execution to prevent pipeline blocking.

Before deploying sync pipelines to production, validate network JSON payloads, verify base64 database states, and inspect formatted API payloads using our accessible free developer tools.

Production Checklist for Offline-First Flutter Apps

  • [ ] Database interactions execute off the main thread or utilize isolates for heavy analytical processing.
  • [ ] All local mutations generate an immutable queue event containing a UUIDv4 idempotency key.
  • [ ] Conflict resolution rules are deterministic, field-aware, and tested against concurrent mutation edge cases.
  • [ ] The background engine distinguishes network disconnects from server error codes (4xx vs 5xx).
  • [ ] Database migrations are covered by automated integration tests to protect cached offline data across app upgrades.
FlutterOffline FirstDartData SyncApp Development