Build an offline-first architecture with SQLite queue, idempotency keys, and conflict policies.
Offline-First Architecture
┌─────────────────────────────────────────────────────────────────────────┐
│ OFFLINE-FIRST DATA FLOW │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ USER ACTION │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Optimistic UI │ ← Instant feedback, update local state │
│ └────────┬────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Local Write │ ← Write to SQLite (source of truth) │
│ │ (SQLite/ │ Store mutation with idempotency key │
│ │ AsyncStorage) │ │
│ └────────┬────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Network Check │ ← If online: sync immediately │
│ └────────┬────────┘ │
│ │ │
│ ┌──────┴──────┐ │
│ ▼ ▼ │
│ ONLINE OFFLINE │
│ │ │ │
│ ▼ ▼ │
│ ┌────────┐ ┌─────────────┐ │
│ │ Sync │ │ Queue in │ │
│ │ Now │ │ SQLite │ │
│ └────┬───┘ └──────┬──────┘ │
│ │ │ │
│ │ ┌──────┴──────┐ │
│ │ ▼ ▼ │
│ │ ┌────────┐ ┌─────────┐ │
│ │ │ App │ │ Network │ │
│ │ │ Fore- │ │ Restore │ │
│ │ │ ground │ │ (sync) │ │
│ │ └────────┘ └────┬────┘ │
│ │ │ │
│ └───────────┬───────┘ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Conflict │ │
│ │ Resolution │ │
│ └────────┬────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Server Wins / │ │
│ │ Client Wins / │ │
│ │ Merge │ │
│ └─────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘
Installation
npx expo install expo-sqlite @react-native-async-storage/async-storageDatabase Schema
// lib/db/schema.ts
import { openDatabaseSync } from 'expo-sqlite';
const db = openDatabaseSync('offline.db');
// Initialize tables
export function initDatabase() {
db.execSync(`
-- Mutation queue for offline writes
CREATE TABLE IF NOT EXISTS mutation_queue (
id TEXT PRIMARY KEY, -- UUID
idempotency_key TEXT UNIQUE NOT NULL, -- Prevent duplicates
mutation_type TEXT NOT NULL, -- 'create' | 'update' | 'delete'
entity_type TEXT NOT NULL, -- 'movie' | 'review' | 'user'
entity_id TEXT, -- For updates/deletes
payload TEXT NOT NULL, -- JSON payload
status TEXT DEFAULT 'pending', -- 'pending' | 'synced' | 'failed' | 'conflict'
retry_count INTEGER DEFAULT 0,
created_at INTEGER NOT NULL, -- Unix ms
updated_at INTEGER NOT NULL,
synced_at INTEGER
);
-- Index for efficient queries
CREATE INDEX IF NOT EXISTS idx_mutation_status ON mutation_queue(status);
CREATE INDEX IF NOT EXISTS idx_mutation_entity ON mutation_queue(entity_type, entity_id);
-- Local data cache (read replicas)
CREATE TABLE IF NOT EXISTS movies_cache (
id TEXT PRIMARY KEY,
data TEXT NOT NULL, -- Full JSON
updated_at INTEGER NOT NULL,
etag TEXT, -- For conditional requests
is_dirty INTEGER DEFAULT 0 -- Has local changes
);
CREATE TABLE IF NOT EXISTS reviews_cache (
id TEXT PRIMARY KEY,
movie_id TEXT NOT NULL,
data TEXT NOT NULL,
updated_at INTEGER NOT NULL,
is_dirty INTEGER DEFAULT 0
);
-- Sync metadata
CREATE TABLE IF NOT EXISTS sync_metadata (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
`);
}
initDatabase();Mutation Queue Operations
// lib/db/mutationQueue.ts
import { db } from './schema';
import { v4 as uuidv4 } from 'uuid';
export interface QueuedMutation {
id: string;
idempotencyKey: string;
mutationType: 'create' | 'update' | 'delete';
entityType: string;
entityId?: string;
payload: any;
status: 'pending' | 'synced' | 'failed' | 'conflict';
retryCount: number;
createdAt: number;
updatedAt: number;
syncedAt?: number;
}
export const mutationQueue = {
// Add mutation to queue
async enqueue(
mutationType: QueuedMutation['mutationType'],
entityType: string,
payload: any,
entityId?: string
): Promise<string> {
const id = uuidv4();
const idempotencyKey = `${entityType}:${mutationType}:${entityId || 'new'}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
const now = Date.now();
db.runSync(
`INSERT INTO mutation_queue (id, idempotency_key, mutation_type, entity_type, entity_id, payload, status, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?)`,
[id, idempotencyKey, mutationType, entityType, entityId || null, JSON.stringify(payload), now, now]
);
return id;
},
// Get pending mutations
async getPending(): Promise<QueuedMutation[]> {
return db.getAllSync<QueuedMutation>(
`SELECT * FROM mutation_queue WHERE status = 'pending' ORDER BY created_at ASC`
);
},
// Get failed mutations for retry
async getFailed(maxRetries = 3): Promise<QueuedMutation[]> {
return db.getAllSync<QueuedMutation>(
`SELECT * FROM mutation_queue WHERE status = 'failed' AND retry_count < ? ORDER BY created_at ASC`,
[maxRetries]
);
},
// Mark as synced
async markSynced(id: string): Promise<void> {
const now = Date.now();
db.runSync(
`UPDATE mutation_queue SET status = 'synced', updated_at = ?, synced_at = ? WHERE id = ?`,
[now, now, id]
);
},
// Mark as failed
async markFailed(id: string, error?: string): Promise<void> {
const now = Date.now();
db.runSync(
`UPDATE mutation_queue SET status = 'failed', retry_count = retry_count + 1, updated_at = ? WHERE id = ?`,
[now, id]
);
},
// Mark as conflict
async markConflict(id: string): Promise<void> {
const now = Date.now();
db.runSync(
`UPDATE mutation_queue SET status = 'conflict', updated_at = ? WHERE id = ?`,
[now, id]
);
},
// Clear old synced mutations (cleanup)
async cleanup(olderThanDays = 7): Promise<void> {
const cutoff = Date.now() - olderThanDays * 24 * 60 * 60 * 1000;
db.runSync(
`DELETE FROM mutation_queue WHERE status = 'synced' AND synced_at < ?`,
[cutoff]
);
},
// Get count by status
async getCounts(): Promise<Record<string, number>> {
const results = db.getAllSync<{ status: string; count: number }>(
`SELECT status, COUNT(*) as count FROM mutation_queue GROUP BY status`
);
return Object.fromEntries(results.map((r) => [r.status, r.count]));
},
};Idempotency Keys
// lib/idempotency.ts
export function generateIdempotencyKey(
entityType: string,
operation: 'create' | 'update' | 'delete',
entityId?: string,
userId?: string
): string {
const parts = [
entityType,
operation,
entityId || 'new',
userId || 'anonymous',
Date.now().toString(36),
Math.random().toString(36).slice(2, 8),
];
return parts.join(':');
}
// Server-side validation (example)
/*
app.post('/api/movies', async (req, res) => {
const idempotencyKey = req.headers['idempotency-key'];
if (!idempotencyKey) {
return res.status(400).json({ error: 'Idempotency-Key required' });
}
// Check if already processed
const existing = await db.query(
'SELECT * FROM processed_keys WHERE key = ?',
[idempotencyKey]
);
if (existing.length > 0) {
return res.status(200).json(existing[0].response);
}
// Process request
const result = await createMovie(req.body);
// Store for future duplicate requests
await db.query(
'INSERT INTO processed_keys (key, response, created_at) VALUES (?, ?, ?)',
[idempotencyKey, JSON.stringify(result), Date.now()]
);
res.status(201).json(result);
});
*/Offline-First Hook
// hooks/useOfflineFirst.ts
import { useState, useEffect, useCallback } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { mutationQueue, QueuedMutation } from '@/lib/db/mutationQueue';
import { api } from '@/lib/api/client';
import { useNetwork } from '@/hooks/useNetwork';
import * as BackgroundFetch from 'expo-background-fetch';
import * as TaskManager from 'expo-task-manager';
const SYNC_TASK = 'offline-sync';
export function useOfflineFirst<TEntity>(
entityType: string,
queryKey: string[],
fetchFn: () => Promise<TEntity[]>
) {
const { isConnected } = useNetwork();
const queryClient = useQueryClient();
const [pendingCount, setPendingCount] = useState(0);
const [syncing, setSyncing] = useState(false);
// Load initial data (from cache + server)
const { data, isLoading, error, refetch } = useQuery({
queryKey,
queryFn: fetchFn,
staleTime: 5 * 60 * 1000,
});
// Update pending count
useEffect(() => {
const updateCount = async () => {
const counts = await mutationQueue.getCounts();
setPendingCount(counts.pending || 0);
};
updateCount();
const interval = setInterval(updateCount, 5000);
return () => clearInterval(interval);
}, []);
// Create mutation with offline support
const createMutation = useMutation({
mutationFn: async (payload: Omit<TEntity, 'id'>) => {
// Generate optimistic ID
const optimisticId = `temp-${Date.now()}-${Math.random().toString(36).slice(2)}`;
const optimisticEntity = { ...payload, id: optimisticId } as TEntity;
// Update cache optimistically
queryClient.setQueryData<TEntity[]>(queryKey, (old) =>
old ? [...old, optimisticEntity] : [optimisticEntity]
);
// Queue for sync
await mutationQueue.enqueue('create', entityType, payload);
// Try immediate sync if online
if (isConnected) {
await syncQueue();
}
return optimisticEntity;
},
onError: (error, variables, context) => {
// Rollback optimistic update
queryClient.invalidateQueries({ queryKey });
},
});
// Update mutation
const updateMutation = useMutation({
mutationFn: async ({ id, ...payload }: Partial<TEntity> & { id: string }) => {
// Optimistic update
queryClient.setQueryData<TEntity[]>(queryKey, (old) =>
old?.map((entity) => (entity.id === id ? { ...entity, ...payload } : entity))
);
// Queue for sync
await mutationQueue.enqueue('update', entityType, payload, id);
if (isConnected) {
await syncQueue();
}
return { id, ...payload };
},
onError: () => {
queryClient.invalidateQueries({ queryKey });
},
});
// Delete mutation
const deleteMutation = useMutation({
mutationFn: async (id: string) => {
// Optimistic delete
queryClient.setQueryData<TEntity[]>(queryKey, (old) =>
old?.filter((entity) => entity.id !== id)
);
// Queue for sync
await mutationQueue.enqueue('delete', entityType, {}, id);
if (isConnected) {
await syncQueue();
}
return id;
},
onError: () => {
queryClient.invalidateQueries({ queryKey });
},
});
// Sync queue with server
const syncQueue = useCallback(async () => {
if (syncing || !isConnected) return;
setSyncing(true);
try {
const pending = await mutationQueue.getPending();
for (const mutation of pending) {
try {
await processMutation(mutation);
await mutationQueue.markSynced(mutation.id);
} catch (error) {
// Check for conflict
if (error instanceof ConflictError) {
await mutationQueue.markConflict(mutation.id);
// Handle conflict resolution
await handleConflict(mutation, error);
} else {
await mutationQueue.markFailed(mutation.id, error.message);
}
}
}
// Also retry failed
const failed = await mutationQueue.getFailed();
for (const mutation of failed) {
try {
await processMutation(mutation);
await mutationQueue.markSynced(mutation.id);
} catch {
await mutationQueue.markFailed(mutation.id);
}
}
// Cleanup old synced
await mutationQueue.cleanup();
// Refresh data from server
queryClient.invalidateQueries({ queryKey });
} finally {
setSyncing(false);
const counts = await mutationQueue.getCounts();
setPendingCount(counts.pending || 0);
}
}, [isConnected, syncing, queryClient, queryKey]);
// Process single mutation
const processMutation = async (mutation: QueuedMutation) => {
const { mutationType, entityType, entityId, payload } = mutation;
switch (mutationType) {
case 'create':
const created = await api.post(`/${entityType}`, payload);
// Replace optimistic ID with real ID in cache
queryClient.setQueryData<TEntity[]>(queryKey, (old) =>
old?.map((e) => (e.id.startsWith('temp-') && JSON.stringify(e) === JSON.stringify(payload))
? created
: e)
);
break;
case 'update':
if (!entityId) throw new Error('Entity ID required for update');
await api.put(`/${entityType}/${entityId}`, payload);
break;
case 'delete':
if (!entityId) throw new Error('Entity ID required for delete');
await api.delete(`/${entityType}/${entityId}`);
break;
}
};
// Conflict resolution
const handleConflict = async (mutation: QueuedMutation, error: ConflictError) => {
// Strategies:
// 1. Server wins (default) - discard local, keep server
// 2. Client wins - force push local
// 3. Merge - combine changes
// 4. Manual - prompt user
const strategy = 'server-wins'; // Configurable
switch (strategy) {
case 'server-wins':
// Invalidate to refetch server version
queryClient.invalidateQueries({ queryKey });
break;
case 'client-wins':
// Retry with force flag
await api.put(`/${mutation.entityType}/${mutation.entityId}`, {
...mutation.payload,
force: true,
});
await mutationQueue.markSynced(mutation.id);
break;
case 'merge':
// Custom merge logic per entity
const merged = await mergeChanges(mutation.entityType, mutation.payload, error.serverData);
await api.put(`/${mutation.entityType}/${mutation.entityId}`, merged);
await mutationQueue.markSynced(mutation.id);
break;
}
};
// Auto-sync when coming online
useEffect(() => {
if (isConnected) {
syncQueue();
}
}, [isConnected, syncQueue]);
// Background sync registration
useEffect(() => {
const registerBackgroundSync = async () => {
await BackgroundFetch.registerTaskAsync(SYNC_TASK, {
minimumInterval: 15 * 60, // 15 minutes
stopOnTerminate: false,
startOnBoot: true,
});
};
registerBackgroundSync();
}, []);
return {
data,
isLoading,
error,
refetch,
create: createMutation.mutate,
update: updateMutation.mutate,
delete: deleteMutation.mutate,
createAsync: createMutation.mutateAsync,
updateAsync: updateMutation.mutateAsync,
deleteAsync: deleteMutation.mutateAsync,
pendingCount,
syncing,
syncNow: syncQueue,
};
}
// Background sync task
TaskManager.defineTask(SYNC_TASK, async () => {
// This runs in background, can't use React hooks
// Use direct database access
try {
// Trigger sync for each entity type
// Return BackgroundFetch.BackgroundFetchResult.NewData if synced
return BackgroundFetch.BackgroundFetchResult.NoData;
} catch {
return BackgroundFetch.BackgroundFetchResult.Failed;
}
});
// Conflict error class
class ConflictError extends Error {
constructor(public serverData: any) {
super('Conflict detected');
this.name = 'ConflictError';
}
}
// Merge function (customize per entity)
async function mergeChanges(entityType: string, local: any, server: any): Promise<any> {
// Simple last-write-wins with timestamp
// In real app, implement field-level merging
return local.updatedAt > server.updatedAt ? local : server;
}Conflict Resolution UI
// components/ConflictResolver.tsx
import { View, Text, Pressable, StyleSheet, Alert } from 'react-native';
import { useOfflineFirst } from '@/hooks/useOfflineFirst';
interface ConflictItem {
id: string;
entityType: string;
localData: any;
serverData: any;
timestamp: number;
}
export function ConflictList() {
// In real app, fetch conflicts from mutation_queue where status = 'conflict'
const conflicts: ConflictItem[] = []; // Placeholder
if (conflicts.length === 0) {
return <View style={styles.empty}><Text>No conflicts</Text></View>;
}
return (
<View style={styles.container}>
<Text style={styles.title}>⚠️ Sync Conflicts ({conflicts.length})</Text>
{conflicts.map((conflict) => (
<View key={conflict.id} style={styles.conflictCard}>
<Text style={styles.entityType}>{conflict.entityType}</Text>
<View style={styles.diff}>
<View style={styles.version}>
<Text style={styles.versionLabel}>Local</Text>
<Text style={styles.versionData}>{JSON.stringify(conflict.localData, null, 2)}</Text>
</View>
<View style={styles.version}>
<Text style={styles.versionLabel}>Server</Text>
<Text style={styles.versionData}>{JSON.stringify(conflict.serverData, null, 2)}</Text>
</View>
</View>
<View style={styles.actions}>
<Pressable style={styles.button} onPress={() => resolveConflict(conflict.id, 'server')}>
<Text>Use Server</Text>
</Pressable>
<Pressable style={styles.buttonPrimary} onPress={() => resolveConflict(conflict.id, 'client')}>
<Text>Use Local</Text>
</Pressable>
<Pressable style={styles.button} onPress={() => resolveConflict(conflict.id, 'merge')}>
<Text>Merge</Text>
</Pressable>
</View>
</View>
))}
</View>
);
}
function resolveConflict(id: string, strategy: 'server' | 'client' | 'merge') {
// Implement resolution
Alert.alert('Resolving', `Using ${strategy} version`);
}Cache Management
// lib/db/cache.ts
import { db } from './schema';
export const cache = {
// Save entity to cache
async set<T>(entityType: string, id: string, data: T, etag?: string): Promise<void> {
const now = Date.now();
db.runSync(
`INSERT OR REPLACE INTO ${entityType}_cache (id, data, updated_at, etag, is_dirty)
VALUES (?, ?, ?, ?, 0)`,
[id, JSON.stringify(data), now, etag || null]
);
},
// Get entity from cache
async get<T>(entityType: string, id: string): Promise<T | null> {
const result = db.getFirstSync<{ data: string }>(
`SELECT data FROM ${entityType}_cache WHERE id = ?`,
[id]
);
return result ? JSON.parse(result.data) : null;
},
// Get all entities from cache
async getAll<T>(entityType: string): Promise<T[]> {
const results = db.getAllSync<{ data: string }>(
`SELECT data FROM ${entityType}_cache ORDER BY updated_at DESC`
);
return results.map((r) => JSON.parse(r.data));
},
// Mark as dirty (has local changes)
async markDirty(entityType: string, id: string): Promise<void> {
db.runSync(
`UPDATE ${entityType}_cache SET is_dirty = 1 WHERE id = ?`,
[id]
);
},
// Clear cache
async clear(entityType: string): Promise<void> {
db.runSync(`DELETE FROM ${entityType}_cache`);
},
// Get dirty entities
async getDirty(entityType: string): Promise<string[]> {
const results = db.getAllSync<{ id: string }>(
`SELECT id FROM ${entityType}_cache WHERE is_dirty = 1`
);
return results.map((r) => r.id);
},
};Network-Aware Sync Component
// components/SyncStatus.tsx
import { View, Text, Pressable, StyleSheet, ActivityIndicator } from 'react-native';
import { useNetwork } from '@/hooks/useNetwork';
import { mutationQueue } from '@/lib/db/mutationQueue';
export function SyncStatus({ onSync }: { onSync: () => Promise<void> }) {
const { isConnected } = useNetwork();
const [pending, setPending] = useState(0);
const [syncing, setSyncing] = useState(false);
const [lastSync, setLastSync] = useState<number | null>(null);
useEffect(() => {
const update = async () => {
const counts = await mutationQueue.getCounts();
setPending(counts.pending + counts.failed + counts.conflict || 0);
};
update();
const interval = setInterval(update, 5000);
return () => clearInterval(interval);
}, []);
const handleSync = async () => {
setSyncing(true);
await onSync();
setLastSync(Date.now());
setSyncing(false);
};
return (
<View style={styles.container}>
<View style={styles.row}>
<View style={[
styles.indicator,
isConnected ? styles.online : styles.offline
]} />
<Text style={styles.statusText}>
{isConnected ? 'Online' : 'Offline'}
</Text>
</View>
{pending > 0 && (
<View style={styles.pending}>
<Text style={styles.pendingText}>
{pending} change{pending !== 1 ? 's' : ''} pending
</Text>
<Pressable
style={styles.syncButton}
onPress={handleSync}
disabled={syncing || !isConnected}
>
{syncing ? (
<ActivityIndicator size="small" color="white" />
) : (
<Text style={styles.syncButtonText}>Sync Now</Text>
)}
</Pressable>
</View>
)}
{lastSync && (
<Text style={styles.lastSync}>
Last sync: {formatTimeAgo(lastSync)}
</Text>
)}
</View>
);
}
function formatTimeAgo(timestamp: number): string {
const diff = Date.now() - timestamp;
if (diff < 60000) return 'just now';
if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
return `${Math.floor(diff / 86400000)}d ago`;
}Try It
1. Create data offline. 2. Verify optimistic UI. 3. Go online. 4. Verify auto-sync. 5. Create conflict (edit same item on two devices). 6. Test resolution.
# Test offline:
# 1. Airplane mode on
# 2. Create/update/delete items
# 3. Airplane mode off
# 4. Watch sync happenBuild offline-first notes app
- Set up SQLite with mutation queue
- Create notes CRUD with optimistic updates
- Implement idempotency keys for all mutations
- Add conflict resolution (server/client/merge)
- Build SyncStatus component
- Register background sync task
- Test: offline create → online sync → conflict → resolve
- Add cache invalidation and ETag support
Offline-first: write to SQLite immediately, sync when online. Use idempotency keys to prevent duplicates. Queue mutations with status tracking. Resolve conflicts with strategies (server/client/merge). Background sync for periodic updates. Keep stale cache visible offline.
Resources
- Expo SQLite: https://docs.expo.dev/versions/latest/sdk/sqlite/
- Background Fetch: https://docs.expo.dev/versions/latest/sdk/background-fetch/
- Idempotency Keys: https://stripe.com/blog/idempotency
- Conflict Resolution Patterns: https://martinfowler.com/articles/patterns-of-distributed-systems/