TL;DR: This guide demonstrates how to architect an offline-first Flutter application using
sqfliteto handle spotty network conditions in enterprise field apps. It details how to implement an outbox-stylesync_queuetable to track local data mutations and explains why client-generated UUIDs are essential to prevent primary key collisions during Node.js backend synchronization.
Key Takeaways
- Restructure your data flow to
UI -> Local DB -> Sync Queue -> APIso the local device acts as the primary source of truth and users never wait on network requests. - Use the
sqflitepackage'sdb.batch()method to efficiently create both your business entity tables and your sync queue tables during database initialization. - Implement an outbox-style
sync_queuetable that tracks specific actions (INSERT,UPDATE,DELETE) and JSON payloads to give the backend granular context for conflict resolution. - Generate universally unique identifiers (UUIDs) on the client for all business entities instead of using auto-incrementing integers to prevent primary key collisions when multiple offline devices sync.
- Wrap local UI state updates and
sync_queuerecord insertions inside a single SQLite transaction (db.transaction) so a change is never saved without its queued sync operation, or the reverse.
Field workers evaluating construction sites, delivering packages to concrete basements, or repairing remote cellular towers all share one operational reality: spotty, unreliable network coverage.
Apps that call the API for every action struggle in these environments. When a worker updates a task status while disconnected, the app either shows a spinner until the request times out or fails and loses the change. A read cache over HTTP requests does not fix writes, and when connectivity returns, changes made on different devices can overwrite each other.
The alternative is an offline-first Flutter application. In this paradigm, the local device is treated as the primary source of truth. The UI reads and writes instantly to a local database, while an asynchronous background queue handles data synchronization with a Node.js server.
In this guide, we will walk through a Flutter offline-first architecture, build a local database sync queue, and implement deterministic conflict resolution on the backend.
Designing the Offline-First Local Database Architecture
An offline-first architecture fundamentally changes how data flows through your app. Instead of UI -> API -> Local Cache, the flow becomes UI -> Local DB -> Sync Queue -> API. The user never waits for a network request to complete.
In Flutter, we use sqflite (2.4.x at the time of writing; it supports Android, iOS and macOS) for local storage. The schema has two parts: the business entities (e.g., tasks) and a sync_queue that records every pending mutation, similar to the transactional outbox pattern.
Here is how you structure the local database initialization:
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
class LocalDatabase {
static final LocalDatabase instance = LocalDatabase._init();
static Database? _database;
LocalDatabase._init();
Future<Database> get database async {
if (_database != null) return _database!;
_database = await _initDB('field_app.db');
return _database!;
}
Future<Database> _initDB(String filePath) async {
final dbPath = await getDatabasesPath();
final path = join(dbPath, filePath);
return await openDatabase(
path,
version: 1,
onCreate: _createDB,
);
}
Future<void> _createDB(Database db, int version) async {
// Run table creation in a batch for efficiency
final batch = db.batch();
// Business data table
batch.execute('''
CREATE TABLE tasks (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
status TEXT NOT NULL,
updated_at INTEGER NOT NULL
)
''');
// Sync queue to track mutations
batch.execute('''
CREATE TABLE sync_queue (
id INTEGER PRIMARY KEY AUTOINCREMENT,
entity_id TEXT NOT NULL,
entity_type TEXT NOT NULL,
action TEXT NOT NULL, -- 'INSERT', 'UPDATE', 'DELETE'
payload TEXT NOT NULL, -- JSON representation of the change
created_at INTEGER NOT NULL,
retry_count INTEGER DEFAULT 0
)
''');
await batch.commit();
}
}
Production Note: Never use auto-incrementing integers for primary keys on business entities in an offline-first app. Two disconnected devices might both create a task locally with
id: 5. When they sync, the second insert fails with a primary key violation, or worse, overwrites the other device's record. Always use universally unique identifiers (UUIDs) generated on the client.
Implementing the Action-Based Sync Queue
When a user modifies a task while offline, we execute two operations in a single SQLite transaction: we update the tasks table so the UI reflects the change immediately, and we insert a record into the sync_queue table.
By syncing actions rather than whole database snapshots, the server learns what changed and in what order, which is what conflict resolution needs. If you need a team to build this kind of sync layer, see our Flutter mobile app development services.
Here is the Dart implementation for pushing to and processing the sync queue. Note that inside db.transaction every call must use txn, not db; sqflite documents that using db there deadlocks.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:sqflite/sqflite.dart';
import 'package:http/http.dart' as http;
class SyncManager {
final LocalDatabase _dbHelper = LocalDatabase.instance;
bool _isSyncing = false;
// 1. Transactionally update data and queue the sync
Future<void> updateTaskStatus(String taskId, String newStatus) async {
final db = await _dbHelper.database;
final timestamp = DateTime.now().millisecondsSinceEpoch;
await db.transaction((txn) async {
// Update local UI state
await txn.update(
'tasks',
{'status': newStatus, 'updated_at': timestamp},
where: 'id = ?',
whereArgs: [taskId],
);
// Queue the action
final payload = jsonEncode({'status': newStatus, 'updated_at': timestamp});
await txn.insert('sync_queue', {
'entity_id': taskId,
'entity_type': 'task',
'action': 'UPDATE',
'payload': payload,
'created_at': timestamp,
});
});
// Attempt sync immediately without making the UI wait for it
unawaited(processQueue());
}
// 2. Process the queue sequentially, one run at a time
Future<void> processQueue() async {
if (_isSyncing) return; // Avoid sending the same operation twice
_isSyncing = true;
try {
final db = await _dbHelper.database;
// Fetch pending operations in the order they were made
final pendingOps = await db.query(
'sync_queue',
orderBy: 'id ASC',
limit: 50,
);
for (final op in pendingOps) {
final response = await _sendToServer(op)
.timeout(const Duration(seconds: 15));
if (response.statusCode == 200 || response.statusCode == 409) {
// Success, or conflict resolved by adopting server state (see below)
await handleSyncResponse(response, op);
} else {
// Server error: count the retry and stop to preserve ordering
await db.rawUpdate(
'UPDATE sync_queue SET retry_count = retry_count + 1 WHERE id = ?',
[op['id']],
);
break;
}
}
} on SocketException {
// Network error: stop and wait for the next connectivity event
} on TimeoutException {
// Slow or captive network: try again later
} finally {
_isSyncing = false;
}
}
Future<http.Response> _sendToServer(Map<String, dynamic> operation) async {
return await http.post(
Uri.parse('https://api.yourdomain.com/sync'),
headers: {
'Content-Type': 'application/json',
// Add your auth header, e.g. a bearer token read from secure storage
},
body: jsonEncode(operation),
);
}
}
Handling Connectivity and Background Sync
Attempting to process the queue when the device is offline wastes battery. Listen to network state changes with the connectivity_plus package (7.x at the time of writing, whose stream emits a List<ConnectivityResult>) to trigger the SyncManager when the device reconnects. On Android 8.0 and later, connectivity changes are not delivered while the app is in the background, so also run processQueue() when the app resumes and on app start.
import 'package:connectivity_plus/connectivity_plus.dart';
import 'dart:async';
class NetworkListener {
final SyncManager _syncManager = SyncManager();
StreamSubscription<List<ConnectivityResult>>? _subscription;
void initialize() {
_subscription = Connectivity().onConnectivityChanged.listen((List<ConnectivityResult> results) {
// Modern devices can have multiple active connections.
// We check if at least one valid connection exists.
if (!results.contains(ConnectivityResult.none)) {
print("Network restored. Triggering sync queue...");
_syncManager.processQueue();
}
});
}
void dispose() {
_subscription?.cancel();
}
}
Warning: A connection type does not prove internet access. A device might be on a Wi-Fi network behind a captive portal or with no uplink. That is why
processQueueuses a timeout and catchesSocketExceptionandTimeoutExceptionto stop the sync loop cleanly.
Node.js Backend: Conflict Resolution Strategies
The hardest part of handling offline data sync and conflict resolution in Flutter apps is the backend logic. Imagine Worker A and Worker B both go offline. They both update Task 123. Worker A reconnects at 2:00 PM and syncs. Worker B reconnects at 3:00 PM and syncs. How does the server know whose update is valid?
Conflict-free Replicated Data Types (CRDTs) merge concurrent edits automatically and suit collaborative editing, but they add complexity that many form-style field apps do not need. Here we use a Last-Write-Wins (LWW) strategy based on the timestamp of each change. LWW discards the losing write, so use it only for fields where that is acceptable.
In this Node.js Express route, we examine the updated_at timestamp provided by the client's payload. If the client's timestamp is older than the database's current timestamp, the server rejects the update as a conflict.
const express = require('express');
const router = express.Router();
// A configured node-postgres Pool
const pool = require('../db');
router.post('/sync', async (req, res) => {
const { entity_id, entity_type, action, payload } = req.body;
let parsedPayload;
try {
parsedPayload = JSON.parse(payload);
} catch {
return res.status(400).json({ error: 'Invalid payload' });
}
const clientUpdatedAt = Number.parseInt(parsedPayload.updated_at, 10);
if (typeof entity_id !== 'string' || !Number.isFinite(clientUpdatedAt)) {
return res.status(400).json({ error: 'Invalid sync operation' });
}
// A transaction must run on a single client, not pool.query
const client = await pool.connect();
try {
await client.query('BEGIN');
if (entity_type === 'task' && action === 'UPDATE') {
// 1. Fetch current server state and lock the row
const { rows } = await client.query(
'SELECT status, updated_at FROM tasks WHERE id = $1 FOR UPDATE',
[entity_id],
);
const serverTask = rows[0];
if (!serverTask) {
await client.query('ROLLBACK');
return res.status(404).json({ error: 'Task not found' });
}
// 2. Conflict Resolution: Last-Write-Wins (LWW)
if (Number.parseInt(serverTask.updated_at, 10) > clientUpdatedAt) {
// Conflict detected: the server has a newer version.
await client.query('ROLLBACK');
return res.status(409).json({
status: 'conflict',
message: 'Server has a newer version of this entity.',
server_state: serverTask,
});
}
// 3. Apply the update
await client.query('UPDATE tasks SET status = $1, updated_at = $2 WHERE id = $3', [
parsedPayload.status,
clientUpdatedAt,
entity_id,
]);
}
await client.query('COMMIT');
res.status(200).json({ status: 'success' });
} catch (error) {
await client.query('ROLLBACK');
console.error('Sync Error:', error);
res.status(500).json({ error: 'Internal server error' });
} finally {
client.release();
}
});
module.exports = router;
The change made most recently on a device wins, regardless of which device reconnects first, as long as device clocks are roughly correct (see clock skew below). Because a retried request carries the same timestamp, re-sending an operation after a lost response applies the same value again, so the endpoint is safe to retry. Validate and authorize every operation on the server: the client is untrusted, so check that the user may edit this task and that status is an allowed value.
Managing Sync States and Client-Side Reversals
When the Node.js backend returns a 409 Conflict, the Flutter client has to handle the rejection. It shouldn't retry the failed operation infinitely. Instead, the client must reconcile its local database with the server's source of truth.
The handleSyncResponse method called from processQueue interprets the response, overwrites the local SQLite row with the server's newer state on a conflict, and removes the operation from the sync queue.
import 'dart:convert';
import 'package:http/http.dart' as http;
extension ConflictHandler on SyncManager {
Future<void> handleSyncResponse(http.Response response, Map<String, dynamic> operation) async {
final db = await LocalDatabase.instance.database;
final int opId = operation['id'];
if (response.statusCode == 200) {
// Success: Remove operation from queue
await db.delete('sync_queue', where: 'id = ?', whereArgs: [opId]);
}
else if (response.statusCode == 409) {
// Conflict: Server rejected our update. We must adopt the server's truth.
final responseBody = jsonDecode(response.body);
final serverState = responseBody['server_state'];
await db.transaction((txn) async {
// 1. Revert local UI state to match server
await txn.update(
'tasks',
{
'status': serverState['status'],
'updated_at': serverState['updated_at']
},
where: 'id = ?',
whereArgs: [operation['entity_id']],
);
// 2. Discard the failed sync operation
await txn.delete('sync_queue', where: 'id = ?', whereArgs: [opId]);
});
// Optional: Dispatch a UI event notifying the user their change was overwritten
print("Warning: Local changes to task ${operation['entity_id']} were overridden by a newer server update.");
}
}
}
Essential Trade-offs and Production Considerations
Building a robust Flutter local database sync and Node.js backend architecture involves managing several critical trade-offs:
-
Client-Side Identity Generation: As emphasized earlier, relying on the backend database to assign IDs breaks offline-first systems. You must generate UUIDv4 strings locally before saving to SQLite.
-
Payload Batching: Sending 50 separate HTTP requests for 50 queued operations adds latency and keeps the radio awake longer, which costs battery. In production, consolidate your sync queue into a bulk array and expose a
/sync/batchendpoint on your Node.js backend. -
Clock Skew: LWW relies entirely on timestamps. If a field worker's phone is manually set to the year 2030, their offline updates will incorrectly overwrite all future data on the server. To mitigate this, capture the server's time during authentication and calculate an offset drift to apply to local timestamps.
-
Poison operations: A 4xx response other than 409 (for example 400 or 404) will never succeed on retry. Move such operations to a dead-letter table and surface them to the user instead of blocking the queue.
Here is client-side identity generation in Dart using the uuid package (4.x):
import 'package:uuid/uuid.dart';
class TaskService {
final _uuid = const Uuid();
final LocalDatabase _db = LocalDatabase.instance;
Future<String> createOfflineTask(String title) async {
final db = await _db.database;
// Generate UUIDv4 instantly on the client
final taskId = _uuid.v4();
final timestamp = DateTime.now().millisecondsSinceEpoch;
await db.insert('tasks', {
'id': taskId,
'title': title,
'status': 'PENDING',
'updated_at': timestamp,
});
// In real code, insert the task and its INSERT sync_queue row
// inside one db.transaction, as in updateTaskStatus above.
return taskId;
}
}
With the local database as the source of truth, a transactional sync queue, client-generated IDs and explicit conflict handling on the Node.js backend, field apps stay responsive regardless of network conditions, and you decide exactly what happens when two offline edits collide.
Sources
- sqflite on pub.dev (supported platforms, transactions and batches,
txndeadlock warning) - connectivity_plus on pub.dev (
List<ConnectivityResult>stream, internet-access and Android background caveats) - node-postgres: Transactions (use one client per transaction, not
pool.query)
Need help building this in production?
SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.
Get a Free ConsultationFrequently Asked Questions
Why shouldn't I use auto-incrementing integers for primary keys in an offline-first Flutter app?
Using auto-incrementing integers can lead to primary key collisions when multiple disconnected devices create records simultaneously and later sync with the server. Instead, you should always generate Universally Unique Identifiers (UUIDs) on the client side to ensure every record remains unique across distributed devices.
How does data flow differ in an offline-first architecture compared to traditional API-driven apps?
In a traditional app, the flow is typically UI -> API -> Local Cache, which blocks the user or fails if the network drops. In an offline-first architecture, the flow changes to UI -> Local DB -> Sync Queue -> API, meaning the user interacts instantly with the local SQLite database while network requests happen asynchronously in the background.
What is the purpose of the sync_queue table in the SQLite schema?
The sync_queue table acts as an action-based ledger inspired by Event Sourcing, recording every mutation (INSERT, UPDATE, DELETE) made while the device is offline. By syncing these specific actions rather than the raw database state, the backend server gains granular context to process changes in the correct order.
How can I ensure my offline-first sync queue doesn't suffer from race conditions during batch synchronization?
Write the local change and its queue entry in a single SQLite transaction so they are recorded atomically, allow only one queue-processing run at a time, and process operations in order, stopping on the first server error.
How does the Node.js backend handle data conflicts when multiple offline devices reconnect?
The backend processes each operation in a transaction, locks the affected row, and compares the client's change timestamp with the stored one. With last-write-wins, an older change is rejected with a 409 and the current server state, which the client then adopts.
How do offline-first apps prevent the UI from freezing during network outages?
By treating the local SQLite database as the primary source of truth, the UI reads and writes data instantly without waiting for HTTP requests to resolve. The actual network synchronization is deferred to an asynchronous background queue, so the user is not left waiting on spinners or losing changes during spotty connectivity.
