{"id":3951,"date":"2026-11-18T12:00:58","date_gmt":"2026-11-18T09:00:58","guid":{"rendered":"https:\/\/niteducation.com\/resources\/?p=3951"},"modified":"2026-11-18T12:16:55","modified_gmt":"2026-11-18T09:16:55","slug":"offline-first-mobile-app-safe-sync","status":"publish","type":"post","link":"https:\/\/niteducation.com\/resources\/offline-first-mobile-app-safe-sync\/","title":{"rendered":"Offline-First Mobile App: How to Sync Data Safely"},"content":{"rendered":"\n<article class=\"nit-article\" aria-label=\"How to Design an Offline-First Mobile App That Syncs Safely\">\n  <div class=\"nit-hero nit-hero--software\">\n    <div class=\"nit-software-hero__grid\">\n      <div class=\"nit-software-hero__copy\">\n        <p class=\"nit-hero__eyebrow\">NIT Practical Mobile Development Guide <\/p>\n        <div class=\"nit-hero__title\" role=\"heading\" aria-level=\"2\">How to Design an <span>Offline-First Mobile App<\/span> That Syncs Safely<\/div>\n        <p class=\"nit-hero__summary\">Build for weak networks, interrupted uploads and two phones editing the same record. Learn how to save work locally, sync it reliably and show users what really happened.<\/p>\n        <div class=\"nit-badge-row\">\n          <span class=\"nit-badge\">Flutter-friendly<\/span>\n          <span class=\"nit-badge\">Real field-survey example<\/span>\n          <span class=\"nit-badge\">Failure tests included<\/span>\n        <\/div>\n        <div class=\"nit-hero__actions\">\n          <a class=\"nit-button nit-button--primary\" href=\"#worked-example\">Follow the example<\/a>\n          <a class=\"nit-button nit-button--secondary\" href=\"#failure-tests\">See the safety tests<\/a>\n        <\/div>\n      <\/div>\n      <div class=\"nit-code-window\" role=\"img\" aria-label=\"Example offline synchronization states: a visit saved locally, queued, uploaded and confirmed\">\n        <div class=\"nit-code-window__bar\" aria-hidden=\"true\">\n          <span class=\"nit-code-window__dot\"><\/span>\n          <span class=\"nit-code-window__dot\"><\/span>\n          <span class=\"nit-code-window__dot\"><\/span>\n          <span class=\"nit-code-window__file\">FIELD VISITS \u00b7 SYNC MONITOR<\/span>\n        <\/div>\n        <div class=\"nit-code-window__body\">\n          <span class=\"nit-code-line\"><span class=\"nit-code-comment\">\/\/ No connection required to save<\/span><\/span>\n          <span class=\"nit-code-line\">Visit ID: <span class=\"nit-code-string\">VISIT-184<\/span><\/span>\n          <span class=\"nit-code-line\">Local write: <span class=\"nit-code-string\">SAVED<\/span><\/span>\n          <span class=\"nit-code-line\">Outbox: <span class=\"nit-code-number\">1 pending operation<\/span><\/span>\n          <span class=\"nit-code-line\">Reconnect: <span class=\"nit-code-keyword\">RETRY SAME ID<\/span><\/span>\n          <span class=\"nit-code-line\">Server: <span class=\"nit-code-string\">ACKNOWLEDGED<\/span><\/span>\n          <span class=\"nit-code-line\">Device: <span class=\"nit-code-string\">SYNC CONFIRMED<\/span><\/span>\n        <\/div>\n      <\/div>\n    <\/div>\n  <\/div>\n  <div class=\"nit-article__body\">\n    <p><strong>For:<\/strong> ICT students, Flutter learners, mobile developers and software teams. <strong>Last reviewed:<\/strong> 17 November 2026. <strong>Illustration:<\/strong> fictional farm-inspection records; no real personal data.<\/p>\n    <section class=\"nit-quick-answer\" aria-labelledby=\"quick-answer-title\">\n      <div class=\"nit-quick-answer__head\">\n        <div>\n          <p class=\"nit-quick-answer__label\">The quick answer<\/p>\n          <h2 class=\"nit-quick-answer__kicker\" id=\"quick-answer-title\">What makes an offline-first mobile app safe?<\/h2>\n        <\/div>\n      <\/div>\n      <div class=\"nit-quick-answer__body\">\n        <p class=\"nit-quick-answer__text\">An offline-first mobile app keeps essential work usable when the internet is unavailable. For safe synchronization, save each edit locally and record its pending operation in one transaction; retry the same operation ID until the server acknowledges it; check record versions before merging; and show the user whether work is saved locally, confirmed remotely or needs review. Reconnecting to the internet does not mean syncing succeeded.<\/p>\n      <\/div>\n    <\/section>\n    <nav class=\"nit-toc\" aria-label=\"Contents\">\n      <h2>In this guide<\/h2>\n      <ol>\n        <li><a href=\"#what-is-offline-first\">Meaning and design choices<\/a><\/li>\n        <li><a href=\"#architecture\">Five-part architecture<\/a><\/li>\n        <li><a href=\"#worked-example\">Farm visit example<\/a><\/li>\n        <li><a href=\"#local-database\">Local database design<\/a><\/li>\n        <li><a href=\"#write-locally\">Atomic offline writes<\/a><\/li>\n        <li><a href=\"#push-pull\">Push and pull sync<\/a><\/li>\n        <li><a href=\"#idempotency\">Prevent duplicate effects<\/a><\/li>\n        <li><a href=\"#conflicts\">Conflict resolution<\/a><\/li>\n        <li><a href=\"#deletions\">Photos and deletions<\/a><\/li>\n        <li><a href=\"#security\">Security and privacy<\/a><\/li>\n        <li><a href=\"#flutter-example\">Flutter implementation<\/a><\/li>\n        <li><a href=\"#failure-tests\">Failure testing checklist<\/a><\/li>\n        <li><a href=\"#faq\">Frequently asked questions<\/a><\/li>\n      <\/ol>\n    <\/nav>\n\n    <section id=\"what-is-offline-first\" aria-labelledby=\"offline-first-heading\">\n      <h2 id=\"offline-first-heading\">1. What Is an Offline-First Mobile App?<\/h2>\n      <p>Imagine visiting a farm where your phone has no mobile signal. You open your inspection app, complete a form, save the visit and close the phone. Later, when you reach a place with coverage, the record appears on the organisation&#8217;s server without needing to type it again.<\/p>\n      <p>That is the central idea of an <strong>offline-first app<\/strong>: important tasks can work using data stored on the device, and a connection is used to share and reconcile changes when available. This does not mean every feature must work without internet. Some actions, especially those needing central approval, may correctly remain online-only. Google&#8217;s Android and Flutter guidance both make that distinction. <a href=\"https:\/\/developer.android.com\/topic\/architecture\/data-layer\/offline-first\" target=\"_blank\" rel=\"noopener noreferrer\">[1]<\/a> <a href=\"https:\/\/docs.flutter.dev\/app-architecture\/design-patterns\/offline-first\" target=\"_blank\" rel=\"noopener noreferrer\">[2]<\/a><\/p>\n      <div class=\"nit-concept-grid\">\n        <div class=\"nit-concept-card\"><h3>Online-only app<\/h3><p>Must contact a server before completing most tasks. With no usable connection, the form may fail or become unavailable.<\/p><\/div>\n        <div class=\"nit-concept-card\"><h3>Cached app<\/h3><p>Can display previously loaded information but may not reliably store new changes for later delivery.<\/p><\/div>\n        <div class=\"nit-concept-card\"><h3>Offline-first app<\/h3><p>Reads and saves essential work locally, then manages later synchronization and possible conflicts.<\/p><\/div>\n      <\/div>\n      <div class=\"nit-callout nit-callout--warning\"><p class=\"nit-callout__title\">Important distinction<\/p><p>\u201cSaved on this phone\u201d and \u201creceived by the server\u201d are two different guarantees. The interface must not label a record \u201csynced\u201d until the app has obtained and durably recorded a valid server acknowledgement.<\/p><\/div>\n    <\/section>\n\n    <section id=\"architecture\" aria-labelledby=\"architecture-heading\">\n      <h2 id=\"architecture-heading\">2. The Five Parts of a Reliable Offline-First Architecture<\/h2>\n      <p>Start with a small system you can explain. The app interface should read from local storage rather than waiting for every network request. The repository coordinates that storage with a background synchronization service.<\/p>\n      <div class=\"nit-concept-grid\">\n        <div class=\"nit-concept-card\"><h3>1 \u00b7 Local database<\/h3><p>Holds the current records and lets screens work when the device is disconnected.<\/p><\/div>\n        <div class=\"nit-concept-card\"><h3>2 \u00b7 Data repository<\/h3><p>Provides one controlled place for reading, editing and coordinating local and remote state.<\/p><\/div>\n        <div class=\"nit-concept-card\"><h3>3 \u00b7 Durable outbox<\/h3><p>Stores a record of changes waiting to be transmitted; survives restarts.<\/p><\/div>\n        <div class=\"nit-concept-card\"><h3>4 \u00b7 Sync worker<\/h3><p>Pushes pending operations, receives acknowledgements, downloads changes and retries failures.<\/p><\/div>\n        <div class=\"nit-concept-card\"><h3>5 \u00b7 Backend API<\/h3><p>Authenticates users, checks permissions, deduplicates operations, assigns record versions and publishes changes.<\/p><\/div>\n        <div class=\"nit-concept-card\"><h3>Design principle<\/h3><p>The server decides authoritative shared state; the local database is the immediate source for the app&#8217;s display.<\/p><\/div>\n      <\/div>\n      <p><strong>Architecture path:<\/strong> Form \u2192 local database and outbox (one transaction) \u2192 sync worker \u2192 authenticated API \u2192 server database. Server changes then flow through the sync worker back into local storage and onto the screen.<\/p>\n      <p>For a first project, prefer a single repository and one carefully designed synchronization path. Adding many background jobs before the data model is correct makes failure handling harder to understand.<\/p>\n      <h3>Five rules that must never become false<\/h3>\n      <p>The application can stop at any moment. These five <strong>invariants<\/strong>\u2014conditions that remain true after each successful transaction\u2014make the design testable.<\/p>\n      <ol class=\"nit-list\">\n        <li><strong>No orphaned write:<\/strong> A locally committed edit has a corresponding durable pending operation, or its accepted server outcome is already recorded.<\/li>\n        <li><strong>No changed retry:<\/strong> Once an operation may have left the phone, its operation ID and meaning never change. A new edit needs a new ID.<\/li>\n        <li><strong>No false confirmation:<\/strong> An older acknowledgement cannot mark a newer revision as synchronized.<\/li>\n        <li><strong>No silent conflict:<\/strong> A server-version mismatch preserves the local proposal for review.<\/li>\n        <li><strong>No skipped change page:<\/strong> Remote changes and the cursor that covers them commit together, or neither commits.<\/li>\n      <\/ol>\n      <p>These are design targets\u2014not a guarantee that a destroyed device can never lose unsent data. Plan recovery and backups when work is irreplaceable.<\/p>\n    <\/section>\n\n    <section id=\"worked-example\" aria-labelledby=\"worked-heading\">\n      <h2 id=\"worked-heading\">3. A Realistic Example: A Farm Inspection App<\/h2>\n      <p>Our fictional field officer, Amina, visits a farm in Migori County. She creates visit <strong>VISIT-184<\/strong>, records crop observations, and attaches a photo. The phone has no coverage.<\/p>\n      <div class=\"nit-table-wrap\">\n        <table class=\"nit-table\">\n          <thead><tr><th scope=\"col\">Action<\/th><th scope=\"col\">What the phone does<\/th><th scope=\"col\">What the officer sees<\/th><\/tr><\/thead>\n          <tbody>\n            <tr><td>Save with no signal<\/td><td>Commits the visit and a pending outbox operation locally<\/td><td>Saved on this device \u00b7 Pending sync<\/td><\/tr>\n            <tr><td>Close and reopen<\/td><td>Loads the same record from the database<\/td><td>Record remains available<\/td><\/tr>\n            <tr><td>Connection returns<\/td><td>Retries the queued operation using its existing ID<\/td><td>Syncing<\/td><\/tr>\n            <tr><td>Server accepts<\/td><td>Records the acknowledgement and server version<\/td><td>Synced \u00b7 Time of confirmation<\/td><\/tr>\n            <tr><td>Another device changed it<\/td><td>Preserves the local work and displays the conflict<\/td><td>Needs review \u00b7 Nothing discarded<\/td><\/tr>\n          <\/tbody>\n        <\/table>\n      <\/div>\n      <p class=\"nit-table-note\">On a phone, swipe sideways within the table to read every column.<\/p>\n      \n      <div class=\"nit-quote\"><p>The harder test comes after Save: Amina loses the network, reopens the app, edits again, and learns that someone else changed the same visit. The system must preserve both sets of work.<\/p><\/div>\n      <h3>Decide which actions may happen offline<\/h3>\n      <p>Good offline-first products set limits deliberately. Notes, drafts and inspections can often be saved locally. A payment transfer, inventory reservation or irreversible approval may need a server response before the UI can truthfully claim that the business action succeeded.<\/p>\n      <div class=\"nit-concept-grid\">\n        <div class=\"nit-concept-card\"><h3>Offline allowed<\/h3><p>Draft visit, edit notes, capture a photo, browse previously downloaded assignments.<\/p><\/div>\n        <div class=\"nit-concept-card\"><h3>Pending confirmation<\/h3><p>Submit visit, upload attachments and assign a server-issued receipt number.<\/p><\/div>\n        <div class=\"nit-concept-card\"><h3>Online-only where required<\/h3><p>Financial settlement, shared stock commitment and centrally authorised decisions.<\/p><\/div>\n      <\/div>\n    <\/section>\n\n    <section id=\"local-database\" aria-labelledby=\"database-heading\">\n      <h2 id=\"database-heading\">4. Design Local Storage Before the Sync Logic<\/h2>\n      <p>A structured database such as SQLite is suitable for many mobile applications because it can persist related records and support transactions. Choose an appropriate Flutter database integration and ensure its storage, migrations and encryption meet your application&#8217;s needs. Plain SQLite is not automatically an encrypted database.<\/p>\n      <p>For our illustration, we need <strong>visits<\/strong> and <strong>outbox<\/strong> tables. The outbox is a durable record of work the device still needs to send. The <strong>server_version<\/strong> describes the last confirmed server revision; <strong>local_revision<\/strong> increments whenever the person changes the device copy. Those numbers answer different questions. A later server reply must not erase a higher local revision.<\/p>\n    <\/section>\n\n    <div class=\"nit-code-window\" role=\"region\" aria-label=\"local-schema.sql example\">\n      <div class=\"nit-code-window__bar\" aria-hidden=\"true\">\n        <span class=\"nit-code-window__dot\"><\/span>\n        <span class=\"nit-code-window__dot\"><\/span>\n        <span class=\"nit-code-window__dot\"><\/span>\n        <span class=\"nit-code-window__file\">local-schema.sql<\/span>\n      <\/div>\n      <div class=\"nit-code-window__body\">\n        <span class=\"nit-code-line\">CREATE TABLE visits (<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">id TEXT PRIMARY KEY,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">farm_name TEXT NOT NULL,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">notes TEXT NOT NULL,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">server_version INTEGER,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">local_revision INTEGER NOT NULL DEFAULT 0,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">sync_state TEXT NOT NULL DEFAULT &#x27;pending&#x27;<\/span>\n        <span class=\"nit-code-line\">);<\/span>\n        <span class=\"nit-code-line\">CREATE TABLE outbox (<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">operation_id TEXT PRIMARY KEY,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">entity_id TEXT NOT NULL,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">action TEXT NOT NULL,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">payload_json TEXT NOT NULL,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">base_version INTEGER,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">local_revision INTEGER NOT NULL,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">state TEXT NOT NULL DEFAULT &#x27;pending&#x27;,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">FOREIGN KEY (entity_id) REFERENCES visits(id)<\/span>\n        <span class=\"nit-code-line\">);<\/span>\n        <span class=\"nit-code-line\">&#160;<\/span>\n        <span class=\"nit-code-line\"><span class=\"nit-code-comment\">&#8212; Example: preserve server_version on update<\/span><\/span>\n        <span class=\"nit-code-line\">INSERT INTO visits(id, farm_name, notes, local_revision)<\/span>\n        <span class=\"nit-code-line\">VALUES(&#8216;VISIT-184&#8217;, &#8216;Example Farm&#8217;, &#8216;First note&#8217;, 1)<\/span>\n        <span class=\"nit-code-line\">ON CONFLICT(id) DO UPDATE SET<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">farm_name = excluded.farm_name,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">notes = excluded.notes,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">local_revision = visits.local_revision + 1,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">sync_state = &#8216;pending&#8217;;<\/span>\n      <\/div>\n    <\/div>\n\n    <div class=\"nit-callout nit-callout--info\"><p><strong>Read the example:<\/strong> Each visit uses a stable client-generated ID. The outbox keeps a separate operation ID, its payload, the server version it was based on, and whether delivery is still pending. Production schemas also need indexes, schema migrations, and account or tenant isolation (for example, separate per-account databases or tenant-qualified keys). Enable and test foreign-key enforcement in the chosen SQLite integration. The SQL upsert shown here changes only the visit row; the outbox insert must be made inside the <em>same transaction<\/em> as illustrated next.<\/p><\/div>\n\n    <section id=\"write-locally\" aria-labelledby=\"write-heading\">\n      <h2 id=\"write-heading\">5. Save the Record and Queue the Change Atomically<\/h2>\n      <p>When Amina taps Save, do <strong>two local writes inside one database transaction<\/strong>: update the visit and insert the outbox operation. If either write fails, roll back both. Without this rule, the app might show a saved visit that has no corresponding operation to upload. An existing visit must be <strong>updated<\/strong> rather than inserted as a second record; in SQLite, <strong>INSERT \u2026 ON CONFLICT DO UPDATE<\/strong> is one option. <a href=\"https:\/\/www.sqlite.org\/lang_upsert.html\" target=\"_blank\" rel=\"noopener noreferrer\">[5]<\/a><\/p>\n      <p>Here is Flutter-style pseudocode. The <strong>findVisit<\/strong>, <strong>upsertVisit<\/strong>, <strong>addOutbox<\/strong> and <strong>newOperationId<\/strong> helpers stand for repository methods you must implement with your selected SQLite library. The important part is that the current local revision is read and incremented <em>inside<\/em> the transaction; a screen-supplied revision could already be stale.<\/p>\n    <\/section>\n\n    <div class=\"nit-code-window\" role=\"region\" aria-label=\"visit_repository.dart \u00b7 Flutter-style pseudocode example\">\n      <div class=\"nit-code-window__bar\" aria-hidden=\"true\">\n        <span class=\"nit-code-window__dot\"><\/span>\n        <span class=\"nit-code-window__dot\"><\/span>\n        <span class=\"nit-code-window__dot\"><\/span>\n        <span class=\"nit-code-window__file\">visit_repository.dart \u00b7 Flutter-style pseudocode<\/span>\n      <\/div>\n      <div class=\"nit-code-window__body\">\n        <span class=\"nit-code-line\">Future&lt;void&gt; saveVisitOffline(Visit draft) async {<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">await db.transaction((txn) async {<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">final saved = await txn.findVisit(draft.id);<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">final revision = (saved?.localRevision ?? 0) + 1;<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">final opId = newOperationId();<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">await txn.upsertVisit(<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">draft, localRevision: revision, state: &#x27;pending&#x27;);<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">await txn.addOutbox({<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">&#x27;operation_id&#x27;: opId,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">&#x27;entity_id&#x27;: draft.id,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">&#x27;action&#x27;: saved == null ? &#x27;create&#x27; : &#x27;update&#x27;,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">&#x27;payload_json&#x27;: draft.toJsonString(),<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">&#x27;base_version&#x27;: saved?.serverVersion,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">&#x27;local_revision&#x27;: revision,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">&#x27;state&#x27;: &#x27;pending&#x27;,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">});<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">});<\/span>\n        <span class=\"nit-code-line\">}<\/span>\n      <\/div>\n    <\/div>\n\n    <div class=\"nit-callout nit-callout--info\"><p><strong>Read the example:<\/strong> If the visit already exists, update its local row instead of attempting a duplicate insert. The example creates a new logical operation for each edit. For one record, send edits in a defined order; coalesce only <em>unsent<\/em> edits if your rules allow it, and track any dependent later change until the preceding operation has been acknowledged. Once an operation has been transmitted, preserve its ID and payload on retries.<\/p><\/div>\n\n    <div class=\"nit-callout nit-callout--info\"><p class=\"nit-callout__title\">Why the transaction matters<\/p><p>If the phone runs out of space halfway through saving, either both the visit and the outbox entry should commit or neither should. Example: Amina edits VISIT-184 twice while offline. Both edits remain represented by durable local state and pending operations; a later acknowledgement for edit 1 must not mark edit 2 as synced. Keep each acknowledged operation separate from the current local record revision.<\/p><\/div>\n    <div class=\"nit-callout nit-callout--info\"><p class=\"nit-callout__title\">When the user edits again before syncing finishes<\/p><p>Imagine local revision 3 was sent and Amina has already created revision 4. The server acknowledges revision 3 as server version 8. The device records that result against revision 3, but keeps revision 4 pending. It must not replace the displayed revision 4 with the older server response. Before transmitting the next <em>unsent<\/em> update, base it on the acknowledged server version 8. Sequence later edits after their prerequisite operations, or combine edits that have definitely never been sent. Never modify the payload of an operation already submitted under the same ID.<\/p><\/div>\n\n    <section id=\"push-pull\" aria-labelledby=\"sync-heading\">\n      <h2 id=\"sync-heading\">6. Design a Safe Push-and-Pull Synchronization Cycle<\/h2>\n      <p>Synchronization is not one giant \u201cupload everything\u201d command. Treat it as a repeatable sequence that can stop halfway and start again without losing information.<\/p>\n      <ol class=\"nit-list\">\n        <li><strong>Check eligibility:<\/strong> Is the user authenticated, the network actually reachable, and the local store unlocked?<\/li>\n        <li><strong>Push pending operations:<\/strong> Send a bounded batch using original operation IDs. Keep one in-flight mutation per record unless the server contract supports another ordering model. Create the visit before sending its photograph.<\/li>\n        <li><strong>Process individual results:<\/strong> Persist each acknowledgement or rejection durably. Keep transient failures for later retries. Handle an older operation acknowledgement without resetting newer local edits to \u201csynced.\u201d<\/li>\n        <li><strong>Pull server changes:<\/strong> Request changes since the last durable cursor; include updated records and deletion markers.<\/li>\n        <li><strong>Apply and checkpoint atomically:<\/strong> Apply each server change page and its next cursor in one local transaction. Do not overwrite locally pending edits with an older remote snapshot; store the incoming version for conflict review when needed.<\/li>\n        <li><strong>Repeat carefully:<\/strong> Run another pass if new work arrived. Apply bounded exponential backoff with jitter for transient failures; do not endlessly retry a rejected permission or invalid-data request without intervention.<\/li>\n      <\/ol>\n      <p>Internet connectivity indicators are only hints: being connected to Wi-Fi does not guarantee that the application&#8217;s API is reachable. A request and valid response provide better evidence of availability. <strong>Timeout or temporary server failure:<\/strong> retry later with the same operation. <strong>Expired login:<\/strong> pause protected work and seek re-authentication. <strong>Version conflict:<\/strong> preserve the edit for review. <strong>Permanent validation failure:<\/strong> show the error and allow correction rather than silently deleting the operation.<\/p>\n      <h3>A simple synchronization API contract<\/h3>\n      <p>Keep endpoints explicit. For example, <strong>POST \/sync\/operations<\/strong> can accept mutations, while <strong>GET \/sync\/changes?cursor=\u2026<\/strong> returns versioned changes and an opaque <strong>nextCursor<\/strong>. The server defines ordering, authorization scope and page boundaries. After applying a page and storing that cursor in the same transaction, restart safely from the saved cursor. If the server reports an expired cursor, re-bootstrap remote data while preserving all pending local operations.<\/p>\n          <h3>A two-edit race: follow the exact versions<\/h3>\n      <p>Suppose Amina edits a visit again <strong>after the first request has left the phone but before its acknowledgement arrives<\/strong>.<\/p>\n      <div class=\"nit-table-wrap\">\n        <table class=\"nit-table\">\n          <thead><tr><th scope=\"col\">Moment<\/th><th scope=\"col\">Client state<\/th><th scope=\"col\">Safe action<\/th><\/tr><\/thead>\n          <tbody>\n            <tr><td>Save #1<\/td><td>Local revision 1; OP-1 pending<\/td><td>Persist record and OP-1 together<\/td><\/tr>\n            <tr><td>Send OP-1<\/td><td>OP-1 durably marked ever attempted<\/td><td>Freeze ID, action, payload and base version<\/td><\/tr>\n            <tr><td>Save #2<\/td><td>Local revision 2; OP-2 queued<\/td><td>Preserve revision 2; wait for OP-1<\/td><\/tr>\n            <tr><td>Server accepts OP-1<\/td><td>Server version 1 returned<\/td><td>Acknowledge only OP-1; keep OP-2 pending<\/td><\/tr>\n            <tr><td>Before first send of OP-2<\/td><td>OP-2 definitely never transmitted<\/td><td>Rebase to server version 1; then freeze and send<\/td><\/tr>\n            <tr><td>Server accepts OP-2<\/td><td>Server version 2 returned<\/td><td>Mark synced only when no newer edit remains<\/td><\/tr>\n          <\/tbody>\n        <\/table>\n      <\/div>\n      <p class=\"nit-table-note\">On a phone, swipe sideways within the table to read every column.<\/p>\n      <div class=\"nit-callout nit-callout--info\"><p><strong>Critical:<\/strong> Store that an operation <em>may have been sent<\/em> before issuing its HTTP request. Only an operation proven never sent may be rebased in place. If one was attempted, retry the exact request or resolve a conflict using a new operation ID.<\/p><\/div>\n      <p>Serialize dependent edits for the same record; independent records may sync with bounded concurrency.<\/p>\n<\/section>\n\n    <div class=\"nit-code-window\" role=\"region\" aria-label=\"POST \/sync\/operations \u00b7 example JSON example\">\n      <div class=\"nit-code-window__bar\" aria-hidden=\"true\">\n        <span class=\"nit-code-window__dot\"><\/span>\n        <span class=\"nit-code-window__dot\"><\/span>\n        <span class=\"nit-code-window__dot\"><\/span>\n        <span class=\"nit-code-window__file\">POST \/sync\/operations \u00b7 example JSON<\/span>\n      <\/div>\n      <div class=\"nit-code-window__body\">\n        <span class=\"nit-code-line\">{<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">&quot;operationId&quot;: &quot;OP-7f6b&quot;,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">&quot;entityId&quot;: &quot;VISIT-184&quot;,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">&quot;action&quot;: &quot;update&quot;,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">&quot;baseVersion&quot;: 7,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">&quot;payload&quot;: {<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">&quot;farmName&quot;: &quot;Example Farm&quot;,<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">&quot;notes&quot;: &quot;Inspect irrigation line&quot;<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">}<\/span>\n        <span class=\"nit-code-line\">}<\/span>\n      <\/div>\n    <\/div>\n\n    <div class=\"nit-callout nit-callout--info\"><p><strong>Read the example:<\/strong> This is an <em>update<\/em> to an existing visit, so its base version is 7. A newly created visit instead uses its own unique entity ID and no prior server version. If the request times out, the client retries with the same operationId and unchanged payload. A different user edit should become a new operation with a new ID; do not mutate the meaning of an existing operation.<\/p><\/div>\n\n    <section id=\"idempotency\" aria-labelledby=\"idempotency-heading\">\n      <h2 id=\"idempotency-heading\">7. Prevent Duplicate Effects When an Upload Is Retried<\/h2>\n      <p>Here is a dangerous but ordinary failure: the server saves VISIT-184 and sends its response, but the phone loses connection before the response arrives. The phone cannot tell whether the operation succeeded. It must retry.<\/p>\n      <p>Reliable systems normally use <strong>retryable, at-least-once requests with idempotent server processing<\/strong>: one logical operation may be transmitted several times while the server commits its effect once within the documented deduplication window. Do not confuse this with exactly-once network delivery.<\/p>\n      <div class=\"nit-concept-grid\">\n        <div class=\"nit-concept-card\"><h3>First attempt<\/h3><p>Server validates the operation, applies its effect and records the operation ID and response in the same transaction.<\/p><\/div>\n        <div class=\"nit-concept-card\"><h3>Response lost<\/h3><p>The phone never records the acknowledgement, so the operation remains pending.<\/p><\/div>\n        <div class=\"nit-concept-card\"><h3>Same-ID retry<\/h3><p>Server recognizes the previously accepted operation and returns the recorded outcome without applying the effect again.<\/p><\/div>\n      <\/div>\n      <p>The server&#8217;s deduplication ledger must be durable, scoped to the correct tenant or authorized account, and protected by a unique constraint so simultaneous retries cannot both apply the effect. The operation and its stored outcome must commit together. If the same ID arrives with a different payload, reject it; document how long the server retains deduplication records, because retries after expiry can otherwise reapply an effect. These practices align with the emerging IETF Idempotency-Key draft, which is still a draft rather than a finalized standard. <a href=\"https:\/\/datatracker.ietf.org\/doc\/html\/draft-ietf-httpapi-idempotency-key-header-08\" target=\"_blank\" rel=\"noopener noreferrer\">[6]<\/a><\/p>\n    <\/section>\n\n    <div class=\"nit-code-window\" role=\"region\" aria-label=\"server-operation.txt \u00b7 transaction outline example\">\n      <div class=\"nit-code-window__bar\" aria-hidden=\"true\">\n        <span class=\"nit-code-window__dot\"><\/span>\n        <span class=\"nit-code-window__dot\"><\/span>\n        <span class=\"nit-code-window__dot\"><\/span>\n        <span class=\"nit-code-window__file\">server-operation.txt \u00b7 transaction outline<\/span>\n      <\/div>\n      <div class=\"nit-code-window__body\">\n        <span class=\"nit-code-line\">BEGIN TRANSACTION<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">authenticate and authorize request<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">look up operation ID in durable receipt ledger<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">if already completed: return stored result<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">verify request payload and base version<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">apply operation or record a conflict result<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">store operation ID, payload hash and result<\/span>\n        <span class=\"nit-code-line\">COMMIT<\/span>\n        <span class=\"nit-code-line\">return stored result<\/span>\n      <\/div>\n    <\/div>\n\n    <div class=\"nit-callout nit-callout--info\"><p><strong>Read the example:<\/strong> This is language-independent algorithm notation, not executable SQL. The receipt record and business mutation must be committed atomically. The real system also needs explicit error classes, concurrent-request locking and a documented deduplication-retention policy.<\/p><\/div>\n\n    <h3>What the server must commit in one transaction<\/h3>\n    <p>For each <strong>authorized tenant and operation ID<\/strong>, serialize competing first attempts, compare a stable request fingerprint, conditionally change the record and store its result in the same database transaction. A unique receipt constraint or transaction-level lock must prevent concurrent retries from both applying the effect. If a duplicate arrives while the first is in flight, it can wait or receive a documented processing response; it must not execute the mutation again.<\/p>\n    <p>A version check may use a conditional statement such as <strong>UPDATE visits SET notes = ?, version = version + 1 WHERE id = ? AND version = ?<\/strong> and inspect its affected-row count, with tenant and authorization enforced separately. No match means conflict, not permission to overwrite. Actual concurrency behavior depends on the database and isolation design.<\/p>\n    <div class=\"nit-callout nit-callout--warning\"><p><strong>Two Save taps are different from a retry.<\/strong> If a double tap creates two new operation IDs, an idempotency receipt does not automatically merge them. Prevent unintended repeat actions in the UI or enforce a business-level uniqueness rule.<\/p><\/div>\n\n    <section id=\"conflicts\" aria-labelledby=\"conflicts-heading\">\n      <h2 id=\"conflicts-heading\">8. Handle Two Phones Editing the Same Record<\/h2>\n      <p>Suppose Amina opens visit version <strong>7<\/strong> while offline. Another officer, Otieno, edits the same visit online and creates version <strong>8<\/strong>. Amina later submits an edit based on version 7. Simply replacing version 8 with her record would silently discard Otieno&#8217;s work.<\/p>\n      <p>A safer general approach is <strong>optimistic version checking<\/strong>. The client sends its base version. The server conditionally applies the change only while that version is current, or performs a documented domain-specific merge. If the version no longer matches, it returns the latest server record and a conflict result; the original local proposal remains available. A separate later operation can submit the reviewed result against the new server version.<\/p>\n      <div class=\"nit-table-wrap\">\n        <table class=\"nit-table\">\n          <thead><tr><th scope=\"col\">Conflict strategy<\/th><th scope=\"col\">Appropriate use<\/th><th scope=\"col\">Main danger<\/th><\/tr><\/thead>\n          <tbody>\n            <tr><td>Last write wins<\/td><td>Low-consequence data where overwriting is acceptable and ordering rules are defined<\/td><td>Silent loss of another user&#8217;s edit; device clock disagreements<\/td><\/tr>\n            <tr><td>Reject on version mismatch<\/td><td>Important shared records that need explicit review<\/td><td>User needs a clear recovery path<\/td><\/tr>\n            <tr><td>Field-level merge<\/td><td>Independent fields with known safe merge rules<\/td><td>Apparently separate fields may contain related business meaning<\/td><\/tr>\n            <tr><td>Manual conflict review<\/td><td>High-consequence or ambiguous competing edits<\/td><td>Requires good interface design and audit evidence<\/td><\/tr>\n          <\/tbody>\n        <\/table>\n      <\/div>\n      <p class=\"nit-table-note\">On a phone, swipe sideways within the table to read every column.<\/p>\n      \n      <div class=\"nit-callout nit-callout--warning\"><p class=\"nit-callout__title\">Never treat timestamps as a universal solution<\/p><p>Device clocks can be wrong, two edits can have different business priority, and overwriting a record may have real consequences. Choose conflict policies per type of data, not as a single global default.<\/p><\/div>\n      <h3>What Amina should see<\/h3>\n      <p>Show both versions, their authors where appropriate, and the fields that differ. Offer actions such as <strong>keep server version<\/strong>, <strong>submit a reviewed merge<\/strong> or <strong>save as separate draft<\/strong>. Keep the rejected local proposal intact until the selected resolution is durably stored. If Amina merges her irrigation note with Otieno&#8217;s crop observation, create a <em>new operation ID<\/em> based on the current server version instead of rewriting the rejected operation.<\/p>\n    <\/section>\n\n    <section id=\"deletions\" aria-labelledby=\"deletions-heading\">\n      <h2 id=\"deletions-heading\">9. Deleted Records, Photos and Interrupted Attachments<\/h2>\n      <h3>Use deletion markers rather than silently removing history<\/h3>\n      <p>If the server simply removes a record, a phone that was offline may never learn that it was deleted. Many systems therefore publish a <strong>tombstone<\/strong>\u2014a versioned deletion marker\u2014through their change feed. Devices apply that marker as part of incremental sync. If a phone has been offline longer than the server retains these markers, it may need a complete, safe re-bootstrap. A re-bootstrap must reconcile authoritative server deletions with unsent edits; simply clearing the local database first could destroy the user&#8217;s only copy of pending work.<\/p>\n      <h3>Treat file uploads separately from record acknowledgement<\/h3>\n      <p>Amina&#8217;s visit metadata might sync successfully while the photograph is still uploading. Track attachment state independently, reference files using a stable attachment ID, check upload integrity, and retry incomplete transfers safely. Do not mark the photo \u201cuploaded\u201d merely because the visit row reached the server.<\/p>\n      <div class=\"nit-concept-grid\">\n        <div class=\"nit-concept-card\"><h3>Record state<\/h3><p>Saved locally \u2192 Pending \u2192 Sent \u2192 Acknowledged or Conflict.<\/p><\/div>\n        <div class=\"nit-concept-card\"><h3>Attachment state<\/h3><p>Local file \u2192 Upload pending \u2192 Uploading \u2192 Verified or Failed.<\/p><\/div>\n        <div class=\"nit-concept-card\"><h3>Deletion state<\/h3><p>Delete requested \u2192 Server tombstone \u2192 Devices remove or archive local copies as policy permits.<\/p><\/div>\n      <\/div>\n      <p>Before deleting local media, confirm the server has the right bytes and any required processing is complete. For large files, use a supported resumable upload protocol and verify file size or checksum where practical. A visit being marked \u201csynced\u201d does not imply its photograph is verified. Retention and legal-deletion requests need deliberate policies so permanent offline copies do not linger unnoticed.<\/p>\n    <\/section>\n\n    <section id=\"security\" aria-labelledby=\"security-heading\">\n      <h2 id=\"security-heading\">10. Protect Local Data and the Sync API<\/h2>\n      <p>Offline-first expands the places where information exists. A secure server does not compensate for a phone that exposes personal records, photos or long-lived credentials. OWASP MASVS provides a recognised set of mobile storage-security requirements. <a href=\"https:\/\/mas.owasp.org\/MASVS\/05-MASVS-STORAGE\/\" target=\"_blank\" rel=\"noopener noreferrer\">[3]<\/a><\/p>\n      <ul class=\"nit-list\">\n        <li><strong>Protect the database:<\/strong> Minimise sensitive local data, use appropriate encryption and platform-backed secret management, and avoid storing API tokens in ordinary unprotected preferences.<\/li>\n        <li><strong>Use authenticated HTTPS:<\/strong> Authenticate every sync request and authorize every record operation on the server. A client-supplied entity ID must never bypass tenant or user permissions.<\/li>\n        <li><strong>Plan for expired sessions:<\/strong> Pause protected uploads until re-authentication; keep legitimate unsynced work securely stored rather than silently dropping it.<\/li>\n        <li><strong>Separate accounts:<\/strong> Do not show one user&#8217;s local cache after another user signs in. Give careful warnings and a safe handoff or recovery policy before destructive logout actions.<\/li>\n        <li><strong>Reduce leakage:<\/strong> Avoid private records, tokens, full request payloads and GPS histories in debug logs, analytics or backups.<\/li>\n        <li><strong>Make sync auditable:<\/strong> Record a minimal history of local creation, server acceptance, conflicting versions and resolved decisions without exposing unnecessary personal details.<\/li>\n      <\/ul>\n      <p>For Kenyan applications processing personal information, the Office of the Data Protection Commissioner describes principles including purpose limitation, data minimisation, storage limitation and confidentiality. Use these to guide what the app collects, caches and retains. This tutorial is technical education, not an exhaustive legal-compliance assessment. <a href=\"https:\/\/www.odpc.go.ke\/wp-content\/uploads\/2024\/02\/PERSONAL-DATA-PROTECTION-HANDBOOK.pdf\" target=\"_blank\" rel=\"noopener noreferrer\">[4]<\/a><\/p>\n      <h3>Cursor and permission rules for real accounts<\/h3>\n      <p>Each sync cursor belongs to an <strong>authenticated account, tenant, dataset and change-feed contract<\/strong>. Never reuse a cursor after switching accounts. An authorized change feed must also handle deletions and changes in access, with a safe re-bootstrap path when retained history expires.<\/p>\n      <p>A phone that remains offline cannot instantly receive an administrator&#8217;s access revocation. The server must reject unauthorized operations when connectivity returns, while the device follows a defined local-cache and session policy. Do not promise immediate remote wipe while the phone is disconnected.<\/p>\n    <\/section>\n\n    <section id=\"flutter-example\" aria-labelledby=\"flutter-heading\">\n      <h2 id=\"flutter-heading\">11. How to Assemble the Example in Flutter<\/h2>\n      <p>Flutter&#8217;s official offline-first guide explains a repository that coordinates local and remote services. Use the same conceptual layering for our field-survey app. <a href=\"https:\/\/docs.flutter.dev\/app-architecture\/design-patterns\/offline-first\" target=\"_blank\" rel=\"noopener noreferrer\">[2]<\/a><\/p>\n      <ol class=\"nit-list\">\n        <li><strong>Form:<\/strong> Validate the visit fields and submit to a repository, not directly to an HTTP function.<\/li>\n        <li><strong>Repository:<\/strong> Save locally and enqueue the operation in one transaction.<\/li>\n        <li><strong>Storage layer:<\/strong> Persist visits, outbox operations, sync cursor, conflicts and attachment state.<\/li>\n        <li><strong>Sync coordinator:<\/strong> Serialize work per entity where needed, persist retry decisions and process server responses without overwriting newer local edits.<\/li>\n        <li><strong>UI state:<\/strong> Observe the local database and display precise pending, confirmed and conflict statuses.<\/li>\n      <\/ol>\n      <p>The next snippet is a control-flow sketch, not a complete Dart package. The <strong>store<\/strong> and <strong>api<\/strong> services stand for interfaces you implement. In particular, recording acknowledgements and merging pulled pages must each use correct local transactions; a scheduler must prevent overlapping sync workers.<\/p>\n    <\/section>\n\n    <div class=\"nit-code-window\" role=\"region\" aria-label=\"sync_coordinator.dart \u00b7 conceptual Dart example\">\n      <div class=\"nit-code-window__bar\" aria-hidden=\"true\">\n        <span class=\"nit-code-window__dot\"><\/span>\n        <span class=\"nit-code-window__dot\"><\/span>\n        <span class=\"nit-code-window__dot\"><\/span>\n        <span class=\"nit-code-window__file\">sync_coordinator.dart \u00b7 conceptual Dart<\/span>\n      <\/div>\n      <div class=\"nit-code-window__body\">\n        <span class=\"nit-code-line\">Future&lt;void&gt; runSync() async {<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">if (!await store.acquireSyncLease()) return;<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">try {<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">for (final op in await store.readyOperationsInOrder()) {<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">await store.markEverSent(op.id); \/\/ Before HTTP<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">try {<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">final reply = await api.send(op);<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">if (reply.isAcknowledged) {<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">await store.ackAndRebaseOnlyUnsent(op, reply);<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">} else if (reply.isConflict) {<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">await store.preserveConflict(op, reply);<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">} else if (reply.requiresLogin) {<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">await store.pauseForLogin(op);<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">break;<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">} else if (reply.isPermanentRejection) {<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">await store.keepForCorrection(op, reply);<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">} else {<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">await store.deferRetry(op);<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">}<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">} on NetworkException {<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">await store.deferRetry(op); \/\/ Same ID, same body<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">}<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">}<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">await store.pullPagesWithAtomicCursor(api);<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">} finally {<\/span>\n        <span class=\"nit-code-line nit-code-line--indent2\">await store.releaseSyncLease();<\/span>\n        <span class=\"nit-code-line nit-code-line--indent\">}<\/span>\n        <span class=\"nit-code-line\">}<\/span>\n      <\/div>\n    <\/div>\n\n    <div class=\"nit-callout nit-callout--info\"><p><strong>Read the example:<\/strong> The worker must handle request exceptions, distinguish retryable errors from permission or validation failures, and avoid overlapping runs. It must persist the attempted flag before transmitting. Its acknowledgement handler should mark only the acknowledged outbox operation complete; update the visible record to \u201csynced\u201d only when no newer local revision is pending. When a pull response and an unsent edit concern the same visit, keep both for conflict processing.<\/p><\/div>\n\n    <h3>Make the interface tell the truth<\/h3>\n    <div class=\"nit-table-wrap\">\n      <table class=\"nit-table\">\n        <thead><tr><th scope=\"col\">Visible status<\/th><th scope=\"col\">What it means<\/th><\/tr><\/thead>\n        <tbody>\n          <tr><td>Saved on device<\/td><td>The local transaction succeeded; upload may not have started<\/td><\/tr>\n          <tr><td>Pending sync<\/td><td>A durable operation is waiting for a suitable connection<\/td><\/tr>\n          <tr><td>Syncing<\/td><td>A transmission or reconciliation attempt is in progress<\/td><\/tr>\n          <tr><td>Synced<\/td><td>The app has recorded a valid server acknowledgement for the latest relevant operation<\/td><\/tr>\n          <tr><td>Needs review<\/td><td>The server rejected or conflicted with a change, and local work remains accessible<\/td><\/tr>\n        <\/tbody>\n      <\/table>\n    <\/div>\n    <p class=\"nit-table-note\">On a phone, swipe sideways within the table to read every column.<\/p>\n    \n    <h3>Background syncing is best effort, not an instant-delivery guarantee<\/h3>\n    <p>Run sync on app launch, after a local save, on a usable connectivity change and through supported background scheduling. Operating systems can delay or suspend background jobs for battery, network or platform reasons. Android&#8217;s WorkManager supports persistent work, while Flutter documents the corresponding practical constraints. Neither guarantees immediate or continuous sync on every device. <a href=\"https:\/\/developer.android.com\/topic\/architecture\/data-layer\/offline-first\" target=\"_blank\" rel=\"noopener noreferrer\">[1]<\/a> <a href=\"https:\/\/docs.flutter.dev\/app-architecture\/design-patterns\/offline-first\" target=\"_blank\" rel=\"noopener noreferrer\">[2]<\/a><\/p>\n    <p>Provide <strong>Sync now<\/strong> and a truthful last-confirmed time when this matters to the user. Prevent overlapping workers, recover after process termination and treat connectivity indicators as hints rather than proof that the API is working.<\/p>\n\n    <section id=\"failure-tests\" aria-labelledby=\"test-heading\">\n      <h2 id=\"test-heading\">12. Test the Failures, Not Only the Happy Path<\/h2>\n      <p>A synchronization demo that works once on strong Wi-Fi is not evidence of a reliable offline-first system. Use fictional data, two devices or emulators, and a backend test environment.<\/p>\n      <div class=\"nit-table-wrap\">\n        <table class=\"nit-table\">\n          <thead><tr><th scope=\"col\">Test scenario<\/th><th scope=\"col\">Expected safe result<\/th><\/tr><\/thead>\n          <tbody>\n            <tr><td>Save in airplane mode<\/td><td>Record remains after a full app restart; outbox entry remains pending<\/td><\/tr>\n            <tr><td>Lose internet after server commit<\/td><td>Retry same operation ID; server applies business effect once<\/td><\/tr>\n            <tr><td>Tap Save twice rapidly<\/td><td>Client blocks unintended second action; separate operation IDs are not automatically duplicates<\/td><\/tr>\n            <tr><td>Two devices edit version 7<\/td><td>Server detects a stale-version conflict; neither edit disappears silently<\/td><\/tr>\n            <tr><td>Worker interrupted mid-batch<\/td><td>Previously committed acknowledgements survive; remaining operations retry<\/td><\/tr>\n            <tr><td>New edit arrives while old upload is in flight<\/td><td>Old acknowledgement clears only its operation; newest local revision remains pending<\/td><\/tr>\n            <tr><td>Power loss while applying sync page<\/td><td>Remote records and next cursor both commit, or neither does; page is safe to replay<\/td><\/tr>\n            <tr><td>Reuse operation ID with modified payload<\/td><td>Server rejects key reuse; no second business effect is applied<\/td><\/tr>\n            <tr><td>Server deletes a record<\/td><td>Offline client later sees the deletion marker or performs safe re-bootstrap<\/td><\/tr>\n            <tr><td>Photo upload fails at 80%<\/td><td>Metadata remains correct; attachment stays pending until verified<\/td><\/tr>\n            <tr><td>Access token expires<\/td><td>Protected sync pauses and resumes after safe re-authentication; local data is protected<\/td><\/tr>\n            <tr><td>Local storage becomes full<\/td><td>Failed transaction does not leave an orphaned outbox operation or half-saved visit<\/td><\/tr>\n            <tr><td>Different account logs in<\/td><td>Previous account&#8217;s private offline records do not become visible to the new user<\/td><\/tr>\n            <tr><td>Device offline for months<\/td><td>Expired cursor is detected; re-bootstrap preserves pending local edits<\/td><\/tr>\n          <\/tbody>\n        <\/table>\n      <\/div>\n      <p class=\"nit-table-note\">On a phone, swipe sideways within the table to read every column.<\/p>\n      <p>Mark each test as pass, fail or not run; keep screenshots, server receipts or database inspection evidence for the outcome.<\/p>\n      <div class=\"nit-callout nit-callout--info\"><p class=\"nit-callout__title\">A demonstrable portfolio test<\/p><p>Show a visit saved in airplane mode, restart the app, reconnect, intentionally lose an acknowledgement, retry the same operation ID and verify that the server has one logical result. Then edit that record locally while an earlier operation is in flight: the newer edit must remain pending after the old acknowledgement. Finally, create a two-device conflict and resolve it without discarding either person&#8217;s proposed content.<\/p><\/div>\n      <h3>A small executable verification exercise<\/h3>\n      <p>Make a miniature local and server database, then test eight outcomes: local rollback, lost acknowledgement, changed-payload rejection, older acknowledgement, stale-version conflict, dependent edits blocked during conflict, atomic cursor rollback and account-scoped receipt keys.<\/p>\n      <p>A simulated SQLite model can verify state transitions; a real Flutter app and authenticated API still require integration, device, encryption, background and network-race testing.<\/p>\n    <\/section>\n\n    <section id=\"mistakes\" aria-labelledby=\"mistakes-heading\">\n      <h2 id=\"mistakes-heading\">13. Common Offline-First Mistakes and Their Corrections<\/h2>\n      <div class=\"nit-concept-grid\">\n        <div class=\"nit-concept-card\"><h3>Clearing the queue too soon<\/h3><p>Do not delete pending work because a request started; wait for a valid server response recorded durably.<\/p><\/div>\n        <div class=\"nit-concept-card\"><h3>Blindly overwriting changes<\/h3><p>Keep base versions and define a conflict policy that fits the business meaning of each record.<\/p><\/div>\n        <div class=\"nit-concept-card\"><h3>Assuming Wi-Fi means success<\/h3><p>Distinguish network connectivity, API reachability, valid authentication and successful record acknowledgement.<\/p><\/div>\n        <div class=\"nit-concept-card\"><h3>Recreating operation IDs<\/h3><p>Retried delivery of the same mutation must retain the same stable ID and payload.<\/p><\/div>\n        <div class=\"nit-concept-card\"><h3>Ignoring local storage failures<\/h3><p>Test disk-full conditions, database corruption recovery, migrations and unsafe logout scenarios.<\/p><\/div>\n        <div class=\"nit-concept-card\"><h3>Trying to sync everything<\/h3><p>Download only authorized, relevant records. Use bounded batches, pagination and suitable background-work constraints.<\/p><\/div>\n      <\/div>\n      <p>Remember: a reliable architecture is a set of data guarantees, not merely a choice between Flutter, Firebase, REST or SQLite.<\/p>\n    <\/section>\n\n    <section id=\"faq\" class=\"nit-faq\" aria-labelledby=\"faq-heading\">\n      <h2 id=\"faq-heading\">Frequently Asked Questions<\/h2>\n      <div class=\"nit-faq__item\"><details><summary>Can a Flutter app work without internet?<\/summary><div class=\"nit-faq__answer\"><p>Yes. Flutter apps can use local databases and offline-first repositories so essential screens and saves work without connectivity. The exact available features depend on how the app has been designed. <a href=\"https:\/\/docs.flutter.dev\/app-architecture\/design-patterns\/offline-first\" target=\"_blank\" rel=\"noopener noreferrer\">[2]<\/a><\/p><\/div><\/details><\/div>\n      <div class=\"nit-faq__item\"><details><summary>Does SQLite automatically sync data to a server?<\/summary><div class=\"nit-faq__answer\"><p>No. SQLite stores and queries local data. Unless you use a separate synchronization layer or a managed service with defined sync support, you must build the operations, API, retries, conflict policies and acknowledgements yourself.<\/p><\/div><\/details><\/div>\n      <div class=\"nit-faq__item\"><details><summary>Should I use Firebase or build a custom sync system?<\/summary><div class=\"nit-faq__answer\"><p>Use managed synchronization when its data model, conflict behavior, access controls, offline support and cost fit the application. Build custom synchronization when business operations, backend ownership or consistency rules require behavior the service does not offer. Test the real offline and conflict requirements before choosing.<\/p><\/div><\/details><\/div>\n      <div class=\"nit-faq__item\"><details><summary>How can I prevent duplicate records after reconnecting?<\/summary><div class=\"nit-faq__answer\"><p>Assign a stable ID to each logical mutation, preserve it on retries, and require the server to deduplicate atomically with the database change. Also distinguish duplicate button presses from retries of one accepted user action.<\/p><\/div><\/details><\/div>\n      <div class=\"nit-faq__item\"><details><summary>What happens if two phones edit the same record offline?<\/summary><div class=\"nit-faq__answer\"><p>When the changes arrive, the server should compare versions and apply a defined merge policy or report a conflict. Important edits should not disappear merely because one phone synchronized last.<\/p><\/div><\/details><\/div>\n      <div class=\"nit-faq__item\"><details><summary>Can offline-first apps guarantee zero data loss?<\/summary><div class=\"nit-faq__answer\"><p>No architecture can promise zero loss in every event, such as a destroyed device before any successful upload or recoverable backup. Design to minimize loss through durable storage, appropriate backup strategies, observable pending state, atomic transactions and robust tests.<\/p><\/div><\/details><\/div>\n      <div class=\"nit-faq__item\"><details><summary>Is offline-first suitable for payments and inventory?<\/summary><div class=\"nit-faq__answer\"><p>It can support offline drafting and queued requests, but a local \u201csaved\u201d action must not be confused with final financial or inventory approval. Operations requiring authoritative shared state should confirm their success against the server and handle duplicate attempts explicitly.<\/p><\/div><\/details><\/div>\n      <div class=\"nit-faq__item\"><details><summary>Does background sync always run immediately after reconnecting?<\/summary><div class=\"nit-faq__answer\"><p>No. Mobile operating systems can delay background work. Persist pending operations, schedule supported jobs, retry when the app is reopened and show accurate pending or confirmed status. <a href=\"https:\/\/developer.android.com\/topic\/architecture\/data-layer\/offline-first\" target=\"_blank\" rel=\"noopener noreferrer\">[1]<\/a> <a href=\"https:\/\/docs.flutter.dev\/app-architecture\/design-patterns\/offline-first\" target=\"_blank\" rel=\"noopener noreferrer\">[2]<\/a><\/p><\/div><\/details><\/div>\n    <\/section>\n\n    <section aria-labelledby=\"next-steps-heading\">\n      <h2 id=\"next-steps-heading\">What to Build Next<\/h2>\n      <p>Start with one offline form and a local database. Add an outbox. Implement one idempotent server operation. Then deliberately break the network and prove what happens. Only expand to multiple record types, large attachments and complex merges when the first path is dependable.<\/p>\n      <p>For another portfolio idea, see NIT&#8217;s <a href=\"https:\/\/niteducation.com\/resources\/ict-portfolio-projects-in-kenya\/\">ICT portfolio projects guide<\/a>, which includes an offline event check-in application. To understand where Flutter sits within a learning path, read <a href=\"https:\/\/niteducation.com\/resources\/mobile-app-development-vs-web-development\/\">mobile app vs web development<\/a> and <a href=\"https:\/\/niteducation.com\/resources\/mobile-app-developer-career-in-kenya\/\">mobile developer career skills<\/a>.<\/p>\n    <\/section>\n\n    <section class=\"nit-sources\" aria-labelledby=\"sources-heading\">\n      <h2 id=\"sources-heading\">References and Technical Reading<\/h2>\n      <ol class=\"nit-list\">\n        <li><a href=\"https:\/\/developer.android.com\/topic\/architecture\/data-layer\/offline-first\" target=\"_blank\" rel=\"noopener noreferrer\">[1] Android Developers \u2014 Build an offline-first app.<\/a> Local data, synchronization, write strategies, conflict resolution and WorkManager.<\/li>\n        <li><a href=\"https:\/\/docs.flutter.dev\/app-architecture\/design-patterns\/offline-first\" target=\"_blank\" rel=\"noopener noreferrer\">[2] Flutter documentation \u2014 Offline-first support.<\/a> Repositories, local\/remote data, reads, writes and background sync.<\/li>\n        <li><a href=\"https:\/\/mas.owasp.org\/MASVS\/05-MASVS-STORAGE\/\" target=\"_blank\" rel=\"noopener noreferrer\">[3] OWASP MASVS \u2014 Storage.<\/a> Mobile storage protection and prevention of sensitive-data leakage.<\/li>\n        <li><a href=\"https:\/\/www.odpc.go.ke\/wp-content\/uploads\/2024\/02\/PERSONAL-DATA-PROTECTION-HANDBOOK.pdf\" target=\"_blank\" rel=\"noopener noreferrer\">[4] Kenya Office of the Data Protection Commissioner \u2014 Personal Data Protection Handbook.<\/a> Core data-protection principles.<\/li>\n        <li><a href=\"https:\/\/www.sqlite.org\/lang_upsert.html\" target=\"_blank\" rel=\"noopener noreferrer\">[5] SQLite \u2014 UPSERT documentation.<\/a> Updating existing records using ON CONFLICT DO UPDATE.<\/li>\n        <li><a href=\"https:\/\/datatracker.ietf.org\/doc\/html\/draft-ietf-httpapi-idempotency-key-header-08\" target=\"_blank\" rel=\"noopener noreferrer\">[6] IETF HTTPAPI \u2014 Idempotency-Key Header (Internet-Draft).<\/a> Operation keys, reuse and expiration; not a final RFC.<\/li>\n      <\/ol>\n      <p>Code snippets and the field-survey example are original educational illustrations. They show architectural patterns; they are not a production-ready codebase or evidence that a deployed app has passed security testing.<\/p>\n    <\/section>\n\n    <section class=\"nit-enrol\" aria-labelledby=\"nit-course-heading\">\n      <p class=\"nit-hero__eyebrow\">Develop skills you can demonstrate<\/p>\n      <h2 id=\"nit-course-heading\">Learn to Build Mobile Apps With Newton Institute of Technology<\/h2>\n      <p>Explore NIT&#8217;s Mobile App Development training in Dart and Flutter. The worked example in this guide shows why a mobile developer should understand local storage, APIs, user feedback and software testing alongside interface design.<\/p>\n      <div class=\"nit-enrol__cards\">\n        <div class=\"nit-enrol-card\"><span>Core technology<\/span><strong>Dart + Flutter<\/strong><p>Develop cross-platform mobile applications.<\/p><\/div>\n        <div class=\"nit-enrol-card\"><span>Practical learning<\/span><strong>Projects + testing<\/strong><p>Apply mobile, API and storage concepts.<\/p><\/div>\n        <div class=\"nit-enrol-card\"><span>Next step<\/span><strong>Explore the course<\/strong><p>Read the official course information and entry details.<\/p><\/div>\n      <\/div>\n     <div class=\"nit-enrol__actions\"><a class=\"nit-button nit-button--primary\" href=\"https:\/\/niteducation.com\/resources\/mobile-app-development-course-in-kenya\/\">Explore NIT Mobile App Development<\/a><a class=\"nit-button nit-button--secondary\" href=\"https:\/\/niteducation.com\/\">Visit NIT<\/a><\/div>\n       <div class=\"nit-article__footer\">\n      <p>Newton Institute of Technology \u00b7 Practical ICT learning for Kenya, Africa and the world.  Deep technical edition \u00b7 Updated 17 November 2026.<\/p>\n    <\/div>\n  <\/div>\n   \n    <\/section>\n   \n<\/article>\n","protected":false},"excerpt":{"rendered":"<p>NIT Practical Mobile Development Guide How to Design an Offline-First Mobile App That Syncs Safely Build for weak networks, interrupted uploads and two phones editing the same record. Learn how to save work locally, sync it reliably and show users what really happened. Flutter-friendly Real field-survey example Failure tests included Follow the example See the [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"set","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[30],"tags":[914,913,912,915],"class_list":["post-3951","post","type-post","status-publish","format-standard","hentry","category-ict","tag-mobile-app-data-synchronization","tag-offline-first-app-architecture","tag-offline-first-mobile-app","tag-offline-first-sync"],"_links":{"self":[{"href":"https:\/\/niteducation.com\/resources\/wp-json\/wp\/v2\/posts\/3951","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/niteducation.com\/resources\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/niteducation.com\/resources\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/niteducation.com\/resources\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/niteducation.com\/resources\/wp-json\/wp\/v2\/comments?post=3951"}],"version-history":[{"count":3,"href":"https:\/\/niteducation.com\/resources\/wp-json\/wp\/v2\/posts\/3951\/revisions"}],"predecessor-version":[{"id":3954,"href":"https:\/\/niteducation.com\/resources\/wp-json\/wp\/v2\/posts\/3951\/revisions\/3954"}],"wp:attachment":[{"href":"https:\/\/niteducation.com\/resources\/wp-json\/wp\/v2\/media?parent=3951"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/niteducation.com\/resources\/wp-json\/wp\/v2\/categories?post=3951"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/niteducation.com\/resources\/wp-json\/wp\/v2\/tags?post=3951"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}