Design and implement an offline-first mobile application architecture with local databases, sync engines, conflict resolution, and seamless online/offline transitions.
## ROLE You are a distributed systems engineer specializing in offline-first mobile architectures. You have built sync engines for applications used in low-connectivity environments like field service, healthcare, logistics, and remote work. You understand CRDTs, operational transforms, conflict resolution strategies, and the UX challenges of eventual consistency. ## OBJECTIVE Architect a complete offline-first system for a [APP_TYPE: field service/healthcare/inventory management/note-taking/CRM] mobile application that allows users to work without interruption regardless of network availability. The system must handle data creation, modification, and deletion offline, then reliably synchronize with the server when connectivity is restored, resolving conflicts gracefully. ## TASK ### Step 1: Local Database Design Choose and configure the local persistence layer: - Database engine selection: [DATABASE: SQLite via Room(Android)/GRDB(iOS)/WatermelonDB/Realm/PouchDB] - Schema design mirroring server models with additional sync metadata columns: - local_id (UUID generated client-side) - server_id (nullable until first sync) - updated_at (local modification timestamp) - sync_status: pending | synced | conflict | failed - version (monotonic counter for optimistic concurrency) - is_deleted (soft delete flag for tombstone sync) - Entity definitions for [YOUR_DATA_MODELS] with relationships and indexes - Migration strategy for schema changes across app versions - Data encryption at rest using [ENCRYPTION: SQLCipher/iOS Data Protection/Android EncryptedSharedPreferences] - Storage quota management: maximum [MAX_SIZE_MB] MB with LRU eviction for cached server data ### Step 2: Sync Engine Architecture Build the bidirectional synchronization system: - Sync protocol design: timestamp-based, version vector, or [SYNC_STRATEGY: last-write-wins/merge/CRDT] - Pull sync: fetch server changes since last sync timestamp, apply to local database - Push sync: upload local pending changes to server, update sync_status on success - Delta sync: only transfer changed fields, not entire records - Batch processing: sync [BATCH_SIZE] records per request to avoid timeouts - Sync ordering: respect foreign key dependencies (parent records before children) - Idempotency: every sync operation must be safely re-executable - Exponential backoff for failed sync attempts with maximum [MAX_RETRIES] retries - Background sync using [iOS: BGTaskScheduler / Android: WorkManager] for periodic synchronization ### Step 3: Conflict Resolution Handle concurrent modifications: - Conflict detection: compare local version with server version at push time - Resolution strategies per entity type: - [STRATEGY_1]: Last-write-wins based on timestamp for [LOW_RISK_ENTITIES] - [STRATEGY_2]: Field-level merge for [MERGEABLE_ENTITIES] (non-conflicting field changes auto-merge) - [STRATEGY_3]: User-prompted resolution for [HIGH_VALUE_ENTITIES] with diff view - [STRATEGY_4]: Server-wins for [AUTHORITATIVE_ENTITIES] like pricing or inventory counts - CRDT implementation for collaborative data types: counters, sets, text (if applicable) - Conflict log storage for audit trail and debugging - Automatic conflict resolution rate target: [PERCENTAGE]% without user intervention ### Step 4: Network State Management Handle connectivity transitions: - Network reachability monitoring using [iOS: NWPathMonitor / Android: ConnectivityManager] - Connection quality classification: offline, poor (>2s latency), good, excellent - Automatic sync trigger on connectivity restoration - Request queue with priority ordering: [PRIORITY_ORDER: auth > transactions > content > analytics] - Optimistic UI updates with rollback on sync failure - User-visible sync status indicator: synced, syncing, pending changes, conflict, offline - Bandwidth-aware sync: defer large asset uploads on cellular if user preference ### Step 5: Asset & File Handling Manage binary data offline: - Image/document capture and local storage with [MAX_FILE_SIZE] limit - Thumbnail generation for offline preview - Progressive upload with resume capability for large files - Download-on-demand strategy for server assets with local caching - Cache invalidation based on content hash or ETag - Storage pressure handling: warn at [WARNING_THRESHOLD]%, purge cached (non-local) assets at [CRITICAL_THRESHOLD]% ### Step 6: Data Integrity & Recovery Ensure data safety: - Transaction-based local writes (atomic multi-table operations) - Write-ahead logging for crash recovery - Checksum verification for synced data integrity - Backup strategy: automatic iCloud/Google Drive backup of local database - Data export functionality for user data portability - Corruption detection and automatic database rebuild from server - Comprehensive logging for sync debugging: operation type, entity, status, duration, error ### Step 7: Testing the Offline System Validate reliability: - Network condition simulation: Charles Proxy throttling, Network Link Conditioner (iOS), Android emulator network settings - Chaos testing: kill app during sync, toggle airplane mode during write, force low storage - Conflict scenario test cases with deterministic resolution verification - Sync performance benchmarks: time to sync [RECORD_COUNT] records on [CONNECTION_TYPE] - Battery impact measurement of background sync operations - End-to-end test suite using [TEST_FRAMEWORK] covering all offline workflows Provide the complete architecture with code for the local database, sync engine, and conflict resolution system.
Or press ⌘C to copy
Replace these placeholders with your own content before using the prompt.
[YOUR_DATA_MODELS][MAX_SIZE_MB][BATCH_SIZE][MAX_RETRIES][STRATEGY_1][LOW_RISK_ENTITIES][STRATEGY_2][MERGEABLE_ENTITIES][STRATEGY_3][HIGH_VALUE_ENTITIES][STRATEGY_4][AUTHORITATIVE_ENTITIES][PERCENTAGE][MAX_FILE_SIZE][WARNING_THRESHOLD][CRITICAL_THRESHOLD][RECORD_COUNT][CONNECTION_TYPE][TEST_FRAMEWORK]