<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mohamed Nabil on Medium]]></title>
        <description><![CDATA[Stories by Mohamed Nabil on Medium]]></description>
        <link>https://medium.com/@muhmmadnabil?source=rss-90211108f014------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FndkyQc78NVFeB5VBT4LiQ.jpeg</url>
            <title>Stories by Mohamed Nabil on Medium</title>
            <link>https://medium.com/@muhmmadnabil?source=rss-90211108f014------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 06:28:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muhmmadnabil/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Preventing Race Conditions with Mutex in Kotlin Coroutines]]></title>
            <link>https://muhmmadnabil.medium.com/preventing-race-conditions-with-mutex-in-kotlin-coroutines-d3d2dd802028?source=rss-90211108f014------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3d2dd802028</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[race-condition]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Mohamed Nabil]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 00:24:13 GMT</pubDate>
            <atom:updated>2026-08-03T09:56:39.069Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4rVcJz92GbQZlJrvRYsZ7Q.png" /></figure><p>Modern mobile applications perform many operations concurrently.</p><p>A chat application, for example, may receive messages through a socket connection, synchronize older messages from an API, update a local database, download media files, and refresh the UI almost at the same time.</p><p>Concurrency improves responsiveness and performance, but it can also introduce bugs that are difficult to reproduce.</p><p>One of these bugs is a <strong>race condition</strong>.</p><p>In this article, we will explore a real-world race condition involving voice-note caching, understand why it happened, and see how Kotlin’s Mutex can solve it without removing the benefits of concurrency.</p><h3>The Real-World Scenario</h3><p>While working on an offline-first chat feature, every incoming message was stored immediately in the local database.</p><p>This made the local database the single source of truth for the UI.</p><p>For a text message, the process was simple:</p><pre>Receive message<br>Save it in the local database<br>Display it in the conversation</pre><p>Voice notes required additional work:</p><pre>Receive message<br>Save it in the local database<br>Download the audio file<br>Save the file in the local cache<br>Update the message with the local file path</pre><p>At first, this flow appeared straightforward.</p><p>The problem was not that multiple different voice notes were downloaded concurrently. Different messages can usually be processed independently without any issue.</p><p>The actual problem occurred when the <strong>same voice-note message</strong> could be scheduled for processing from more than one flow at the same time.</p><h4>How Can the Same Message Be Processed Twice?</h4><p>A chat application may receive the same message through different sources.</p><p>For example, a message may arrive from the real-time socket:</p><pre>Socket event<br>    ↓<br>Process message 123</pre><p>At almost the same moment, an API synchronization request may return the same message:</p><pre>API synchronization<br>    ↓<br>Process message 123</pre><p>Both flows may now attempt to cache the same voice note.</p><p>Each coroutine reads the current message state and sees that the voice note has not been downloaded yet.</p><p>They may then both start the same operation:</p><pre>Coroutine A                       Coroutine B<br>Read message 123                  Read message 123<br>Status: NOT_DOWNLOADED            Status: NOT_DOWNLOADED<br>Set status to DOWNLOADING         Set status to DOWNLOADING<br>Download the audio file           Download the audio file<br>Save the local file               Save the local file<br>Update the database               Update the database</pre><p>This creates duplicate work, but duplicate work alone is not necessarily a race condition.</p><p>The real race appears when the final result depends on which coroutine finishes last.</p><h3>An Example of the Incorrect Result</h3><p>Imagine that the first coroutine completes successfully:</p><pre>Coroutine A:<br>Download completed<br>File saved<br>Status updated to DOWNLOADED</pre><p>The second coroutine may then fail or get cancelled:</p><pre>Coroutine B:<br>Download failed<br>Status updated to FAILED</pre><p>The final database state becomes: FAILED</p><p>However, the file was already downloaded successfully by the first coroutine.</p><p>The opposite can also happen. A cancelled coroutine may reset the state to NOT_DOWNLOADED after another coroutine has already completed the operation.</p><p>The code may work correctly many times before failing under the right timing conditions.</p><p>That is what makes race conditions difficult to debug.</p><h3>What Is a Race Condition?</h3><p>A race condition happens when the result of an operation depends on the timing or execution order of concurrent tasks.</p><p>Consider this simplified example:</p><pre>var counter = 0<br><br>suspend fun increment() {<br>    counter++<br>}</pre><p>The expression counter++ looks like one operation, but internally it involves multiple steps:</p><pre>Read the current value<br>Increase the value<br>Write the new value</pre><p>If two coroutines execute these steps concurrently, they may both read the same value before either writes the result.</p><p>Some updates can therefore be lost.</p><p>The same issue can happen with:</p><ul><li>Cached files</li><li>Database updates</li><li>Shared collections</li><li>Message states</li><li>In-memory application state</li></ul><h3>The Naive Global Mutex Solution</h3><p>Kotlin Coroutines provides Mutex for protecting critical sections.</p><p>A simple solution may look like this:</p><pre>private val cacheMutex = Mutex()<br><br>suspend fun cacheVoiceNote(message: Message) {<br>    cacheMutex.withLock {<br>        downloadVoiceFile(message)<br>        saveVoiceFile(message)<br>        updateLocalMessage(message)<br>    }<br>}</pre><p>This prevents concurrent access because only one coroutine can enter the withLock block at a time.</p><p>However, it also serializes every voice-note download.</p><p>Even completely independent messages must wait for one another:</p><pre>Download message 100<br>        ↓<br>Download message 200<br>        ↓<br>Download message 300</pre><p>This removes useful concurrency and may significantly slow down media caching.</p><p>The goal is not to prevent all voice notes from running concurrently.</p><blockquote><em>The goal is to prevent the same voice note from being processed twice at the same time.</em></blockquote><h3>Tracking Active Message IDs</h3><p>A better approach is to maintain a set containing the IDs currently being processed:</p><pre>private val activeDownloadIds = mutableSetOf&lt;String&gt;()</pre><p>However, MutableSet is shared mutable state.</p><p>The check and insertion must happen atomically.</p><p>Without synchronization, code like this is unsafe:</p><pre>if (messageId !in activeDownloadIds) {<br>    activeDownloadIds.add(messageId)<br>    downloadVoiceNote(messageId)<br>}</pre><p>Two coroutines could both check the set before either of them adds the ID.</p><p>Both would see that the ID is missing, and both would start the download.</p><p>We can protect the set using a Mutex:</p><pre>private val activeDownloadsMutex = Mutex()<br>private val activeDownloadIds = mutableSetOf&lt;String&gt;()</pre><p>Then create an atomic claim operation:</p><pre>private suspend fun claimDownload(messageId: String): Boolean =<br>    activeDownloadsMutex.withLock {<br>        activeDownloadIds.add(messageId)<br>    }</pre><p>MutableSet.add() returns:</p><ul><li>true when the ID was added.</li><li>false when the ID already existed.</li></ul><p>This allows us to atomically check and register the operation in one step.</p><h3>Processing the Voice Note Safely</h3><p>The caching function can now claim the message before starting:</p><pre>private suspend fun cacheVoiceNoteIfNeeded(message: Message) {<br>    val messageId = message.id<br>    if (!claimDownload(messageId)) {<br>        return<br>    }<br>    try {<br>        downloadAndCacheVoiceNote(message)<br>    } finally {<br>        releaseDownload(messageId)<br>    }<br>}</pre><p>The release operation also uses the same mutex:</p><pre>private suspend fun releaseDownload(messageId: String) {<br>    activeDownloadsMutex.withLock {<br>        activeDownloadIds.remove(messageId)<br>    }<br>}</pre><p>The finally block is important.</p><p>The message ID must be removed whether the operation:</p><ul><li>Succeeds</li><li>Fails</li><li>Throws an exception</li><li>Gets cancelled</li></ul><p>Without finally, an exception could leave the ID inside the set permanently, preventing future retries.</p><h3>What Does the Mutex Protect?</h3><p>An important detail is that the mutex does not protect the entire download.</p><p>It only protects access to:</p><pre>activeDownloadIds</pre><p>The critical section is very small:</p><pre>activeDownloadsMutex.withLock {<br>    activeDownloadIds.add(messageId)<br>}</pre><p>The actual network request, file writing, and database update happen outside the lock.</p><p>This means different voice notes can still be downloaded concurrently:</p><pre>Message 100 → Downloading<br>Message 200 → Downloading<br>Message 300 → Downloading</pre><p>But the same message cannot be processed twice concurrently:</p><pre>First request for message 100  → Allowed<br>Second request for message 100 → Ignored</pre><p>The mutex protects the in-memory tracking set directly.</p><p>The database row and cached file are protected indirectly because only one coroutine is allowed to process a specific message ID.</p><h3>Mutex Is Not a Complete Solution</h3><p>A mutex only protects the code paths that use the same coordination mechanism.</p><p>If another part of the application calls the raw download function directly without claiming the message ID first, the same voice note may still be processed twice.</p><p>For that reason, the raw download operation should remain private, and every caller should use the same protected entry point.</p><h3>Final Thoughts</h3><p>Race conditions are difficult because they depend on timing.</p><p>The same code may work hundreds of times before failing once under the right concurrency conditions.</p><p>Mutex provides a coroutine-friendly way to ensure that only one coroutine accesses a critical section at a time.</p><p>The key is not to lock everything.</p><p>Instead:</p><ul><li>Identify the actual shared resource.</li><li>Protect only the critical section.</li><li>Keep slow or independent operations outside the lock.</li><li>Use the same mutex consistently for every access.</li></ul><p>Concurrency does not always need to be removed.</p><p>It needs to be controlled.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3d2dd802028" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Offline-First Mobile Systems: Designing Real Offline Features]]></title>
            <link>https://muhmmadnabil.medium.com/building-offline-first-mobile-systems-designing-real-offline-features-bfb1aba6db73?source=rss-90211108f014------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfb1aba6db73</guid>
            <category><![CDATA[offline-first]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Mohamed Nabil]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 09:29:50 GMT</pubDate>
            <atom:updated>2026-07-06T09:29:50.931Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J8b8ND41129bODXSm-yBCA.png" /></figure><p>It is easy to say:</p><blockquote><em>Save the data locally, then sync it later.</em></blockquote><p>And honestly, this sentence is correct.</p><p>But it is also too simple.</p><p>Because real features are not that clean.</p><p>A text message is not like a voice note.<br>A voice note is not like a POS order.</p><p>Each feature has its own lifecycle, failure cases, retry rules, and user experience decisions.</p><p>This is where Offline-First starts to become interesting.</p><p>In the previous articles, we talked about the foundation:</p><ul><li>Local database as the source of truth</li><li>Offline-first architecture</li><li>Pending operations queue</li><li>Sync engine</li><li>Retry policies</li><li>Idempotency</li><li>Conflict handling</li></ul><p>Now let’s move from concepts to real features.</p><p>In this article, we will look at how Offline-First design works in real production-inspired features:</p><ul><li>Chat messages</li><li>Voice notes</li><li>POS orders</li></ul><p>The goal is not to memorize an implementation.</p><p>The goal is to understand how to think.</p><h3>The Foundation We Already Built</h3><p>Before we jump into the examples, let’s quickly remember the base idea.</p><p>In an Offline-First system, the UI should not depend directly on the network.</p><p>The UI reads from the local database.</p><p>The app updates the local database first.</p><p>Then the sync engine is responsible for sending changes to the server.</p><p>The basic flow looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n5SZ1zLSDk7Zw_t-NBYxJQ.png" /></figure><p>This pattern is simple.</p><p>But the hard part is applying it correctly to different features.</p><p>Because not every action should behave the same way.</p><p>Some actions can be retried silently.</p><p>Some actions need the user to manually retry.</p><p>Some actions can be rolled back.</p><p>And some actions should never be rolled back automatically.</p><p>That is the real engineering work.</p><h3>Case Study 1: Offline Chat Messages</h3><p>Let’s start with a chat app.</p><p>The user opens a conversation, writes a message, and taps Send.</p><p>But the network is weak.</p><p>What should happen?</p><p>Should the app wait for the server before showing the message?</p><p>Probably not.</p><p>That would make the app feel slow.</p><p>A good chat experience should feel instant.</p><p>So instead of waiting for the network, we save the message locally first and show it immediately.</p><p>The message starts as a local message with a pending state.</p><h3>Chat Message Lifecycle</h3><p>A message does not go directly from “created” to “done”.</p><p>It usually moves through multiple states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V0N_BR1Qpvq6WK5b6OSKGg.png" /></figure><p>There is an important difference here.</p><p>Pending, Sent, and Failed are related to sending the message from the current device to the server.</p><p>But Delivered and Read are different.</p><p>They are related to what happens after the server accepts the message.</p><p>This separation matters because a pending message cannot be delivered or read yet.</p><p>It does not officially exist on the server.</p><h3>The Local Message ID Problem</h3><p>If we wait for the server to generate the message ID, we cannot show the message immediately.</p><p>So the client needs to generate a local ID.</p><p>That local ID allows the app to store and display the message before the server responds.</p><pre>val localMessageId = generateLocalId()</pre><p>This ID is not just for UI.</p><p>It is also useful for retries and idempotency.</p><p>If the network fails and the sync engine retries the same message, the server should recognize it as the same message, not a new one.</p><p>Without this, retry can create duplicate messages.</p><h3>Sending a Message Offline</h3><p>The send message flow may look like this:</p><pre>suspend fun sendMessage(<br>    conversationId: String,<br>    text: String<br>) {<br>    val localMessageId = generateLocalId()<br>    val message = Message(<br>        id = localMessageId,<br>        conversationId = conversationId,<br>        text = text,<br>        status = MessageStatus.Pending,<br>        createdAt = currentTime()<br>    )<br>    localDatabase.insertMessage(message)<br>    pendingActionsQueue.enqueue(<br>        PendingAction.SendMessage(<br>            actionId = generateActionId(),<br>            localMessageId = localMessageId,<br>            conversationId = conversationId,<br>            text = text<br>        )<br>    )<br>}</pre><p>Notice something important.</p><p>This function does not wait for the API response.</p><p>It does two main things:</p><ol><li>Saves the message locally.</li><li>Adds a pending action to the queue.</li></ol><p>The UI will observe the local database and show the message immediately.</p><p>The sync engine will handle the network later.</p><h3>Chat Message Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pkXVAsIq6sJlsS1X-mBWHQ.png" /></figure><p>This is a very common Offline-First pattern.</p><p>But even in this simple feature, we already have many decisions:</p><ul><li>How do we generate local IDs?</li><li>How do we prevent duplicate messages?</li><li>How many times should we retry?</li><li>When do we show Failed?</li><li>Should failed messages retry automatically or wait for the user?</li></ul><p>There is no single correct answer for every app.</p><p>But the important point is this:</p><blockquote><em>The message should not disappear just because the network failed.</em></blockquote><p>Once the user sends it, the action must become recoverable.</p><h3>Case Study 2: Offline Voice Notes</h3><p>Now, let’s make the feature harder.</p><p>A voice note looks similar to a text message.</p><p>The user records something and sends it inside the conversation.</p><p>But technically, it is very different.</p><p>A text message is small.</p><p>A voice note has a file.</p><p>That file needs to be stored locally, uploaded, linked to a message, retried if upload fails, and maybe played before it is uploaded.</p><p>So the lifecycle is more complex.</p><h3>Voice Notes Are Not Just Messages</h3><p>For a text message, the payload may be something like:</p><pre>conversationId + text</pre><p>For a voice note, the app needs to handle:</p><pre>conversationId + local audio file + duration + upload state + remote URL</pre><p>This means the local file is part of the feature state.</p><p>If the database says the voice note exists, but the local file is missing, the feature is broken.</p><p>So we need to think about both:</p><ul><li>Database state</li><li>File system state</li></ul><h3>Voice Note Lifecycle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ROO_NczsOoD0yu3z-ZbT1A.png" /></figure><p>The user experience should still be fast.</p><p>After recording, the voice note should appear in the conversation immediately.</p><p>But internally, the app may still need to upload the file.</p><h3>Voice Note States</h3><p>A voice note may need more states than a normal text message.</p><pre>enum class VoiceNoteStatus {<br>    PendingUpload,<br>    Uploading,<br>    Sent,<br>    Failed<br>}</pre><p>The exact states depend on the backend design.</p><p>For example, some APIs may require uploading the file first, then sending a message with the uploaded file URL.</p><p>Other APIs may allow sending the voice note as one request.</p><p>But from an Offline-First perspective, the same rule applies:</p><blockquote><em>Save locally first. Upload later. Make the action recoverable.</em></blockquote><h3>Voice Note Upload Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aIlulrVAacvUJcguQ_bLbw.png" /></figure><p>Now the sync engine is not just sending JSON.</p><p>It may be uploading files.</p><p>And file upload introduces new problems:</p><ul><li>What if the app closes during upload?</li><li>What if the upload reaches 70%, then fails?</li><li>What if the user deletes the voice note while it is still uploading?</li><li>What if the local file is deleted before the upload succeeds?</li><li>What if the server accepts the file, but the app crashes before saving the remote URL?</li></ul><p>These are the details that make real Offline-First features harder than diagrams.</p><h3>Important Engineering Decisions for Voice Notes</h3><h3>1. The local file path must be stored</h3><p>The database should know where the local audio file exists.</p><pre>data class VoiceMessage(<br>    val id: String,<br>    val conversationId: String,<br>    val localFilePath: String,<br>    val remoteUrl: String?,<br>    val durationInSeconds: Int,<br>    val status: VoiceNoteStatus<br>)</pre><p>Before the upload succeeds, remoteUrl may be null.</p><p>That is normal.</p><p>The message can still exist locally.</p><h3>2. Upload should be retryable</h3><p>A voice note upload should not depend only on the current screen.</p><p>If the user leaves the conversation, the upload should still be recoverable.</p><p>That means the upload action should be stored in a queue.</p><pre>pendingActionsQueue.enqueue(<br>    PendingAction.UploadVoiceNote(<br>        actionId = generateActionId(),<br>        messageId = localMessageId,<br>        localFilePath = filePath<br>    )<br>)</pre><h3>3. Failed upload should be visible</h3><p>For text messages, a small failed icon may be enough.</p><p>For voice notes, failure can be more frustrating because the user spent time recording it.</p><p>So the UI should clearly show that the voice note is not uploaded yet.</p><p>The user should know whether the voice note is:</p><ul><li>Waiting</li><li>Uploading</li><li>Failed</li><li>Sent</li></ul><p>Offline-First is not only about data.</p><p>It is also about giving the user confidence.</p><h3>Case Study 3: Offline POS Orders</h3><p>Now let’s move to a more sensitive example.</p><p>Imagine a cashier in a supermarket.</p><p>The customer pays.</p><p>The cashier taps “Complete Order”.</p><p>Then the internet disconnects.</p><p>What should the app do?</p><p>Should it cancel the order?</p><p>Should it wait for the server?</p><p>Should it block the cashier?</p><p>In many POS systems, blocking the cashier is not acceptable.</p><p>The business must continue.</p><p>So the order needs to be saved locally and synced later.</p><p>But this is much more serious than a chat message.</p><p>Because now we are dealing with:</p><ul><li>Money</li><li>Receipts</li><li>Inventory</li><li>Taxes</li><li>Order numbers</li><li>Refunds</li><li>Duplicate transactions</li><li>Reconciliation</li></ul><p>This is where Offline-First becomes a business-critical decision.</p><h3>POS Order Lifecycle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d2L60pDaWxKgQaeqPlGvTQ.png" /></figure><p>The key difference here is failure handling.</p><p>In chat, a failed message can show:</p><blockquote><em>Tap to retry.</em></blockquote><p>But in POS, it is not that simple.</p><p>The customer may have already paid.</p><p>The receipt may have already been printed.</p><p>The cashier may have already moved to the next customer.</p><p>So automatic rollback can be dangerous.</p><h3>POS Order States</h3><p>A POS order may have states like:</p><pre>enum class OrderSyncStatus {<br>    PendingSync,<br>    Syncing,<br>    Synced,<br>    NeedsReview<br>}</pre><p>The NeedsReview State is important.</p><p>It means the app could not safely complete the sync automatically.</p><p>Maybe the server rejected the order.</p><p>Maybe the product price changed.</p><p>Maybe the order number conflicts with another order.</p><p>Maybe the payment status is unclear.</p><p>In these cases, the app should not silently hide the problem.</p><p>It should make the issue visible to someone who can review and fix it.</p><h3>POS Sync Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iNECDSUXQh-9qkS_pCEHFQ.png" /></figure><p>This is why POS systems need stronger guarantees.</p><p>A duplicate chat message is annoying.</p><p>A duplicate order can be expensive.</p><p>So POS sync usually requires careful idempotency, local audit logs, and reconciliation tools.</p><h3>The Common Pattern</h3><p>Most Offline-First features follow this pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xe3mgfnvjq0g3UuQPgTR2w.png" /></figure><p>The pattern is reusable.</p><p>But the final failure decision changes depending on the feature.</p><p>For example:</p><ul><li>A failed like can rollback.</li><li>A failed message can show a retry.</li><li>A failed POS order may need review.</li><li>A failed voice note upload may stay locally and retry later.</li></ul><p>This is why designing Offline-First features requires product thinking, not only technical thinking.</p><h3>Retry vs Rollback vs Review</h3><p>When a pending action fails, you usually have three options.</p><h3>1. Retry</h3><p>Retry is useful when the failure is temporary.</p><p>Examples:</p><ul><li>No internet</li><li>Timeout</li><li>Server unavailable</li><li>Upload interrupted</li></ul><p>Retry works well for:</p><ul><li>Chat messages</li><li>Voice notes</li><li>Offline orders</li><li>Form submissions</li></ul><p>But retry must be safe.</p><p>If retry can create duplicates, you need idempotency.</p><h3>2. Rollback</h3><p>Rollback is useful when the action is simple and easy to undo.</p><p>Examples:</p><ul><li>Like button</li><li>Save item</li><li>Follow user</li></ul><p>If the server rejects the action, the app can return the UI to the previous state.</p><p>But rollback is not always a good experience.</p><p>If the user sees something happen, then it suddenly disappears, it can feel confusing.</p><p>So, rollback should be used carefully.</p><h3>3. Needs Review</h3><p>Some failures cannot be fixed automatically.</p><p>Examples:</p><ul><li>POS order rejected by the server</li><li>Payment status unclear</li><li>Inventory conflict</li><li>Permission or business rule issue</li></ul><p>In these cases, the app should mark the item as NeedsReview.</p><p>This is not a failure of the Offline-First design.</p><p>Actually, it is a sign of good design.</p><p>Because the system is admitting:</p><blockquote><em>I cannot safely solve this automatically.</em></blockquote><p>That honesty is important in production systems.</p><h3>Common Mistakes</h3><h3>Mistake 1: Treating All Offline Actions the Same</h3><p>This is one of the biggest mistakes.</p><p>A message, a voice note, and a POS order may all use a queue.</p><p>But they should not have the same failure strategy.</p><p>The business risk is different.</p><p>The user expectation is different.</p><p>The recovery flow is different.</p><h3>Mistake 2: Updating UI Without Durable Local State</h3><p>Sometimes developers update the UI immediately, but do not save the action locally.</p><p>That looks good for a few seconds.</p><p>But if the app crashes, the action disappears.</p><p>That is not Offline-First.</p><p>In a real Offline-First system, the local database should be updated first.</p><p>Then the UI should react to it.</p><h3>Mistake 3: Forgetting Idempotency</h3><p>Retries are dangerous without idempotency.</p><p>If the app retries the same request three times, the server must know whether these retries represent the same action or three different actions.</p><p>Without idempotency:</p><ul><li>One message can be sent multiple times.</li><li>One order can be created twice.</li><li>One payment can be recorded incorrectly.</li></ul><p>Retry is not enough.</p><p>Retry must be safe.</p><h3>Mistake 4: Hiding Failed States</h3><p>A pending action should not stay pending forever without explanation.</p><p>The user needs feedback.</p><p>For example:</p><ul><li>Message failed to send</li><li>Voice note upload failed</li><li>Order needs review</li></ul><p>Good Offline-First UX does not mean hiding problems.</p><p>It means making the system usable even when problems happen.</p><h3>Mistake 5: Assuming Network Failure Is the Only Failure</h3><p>Not every failure is caused by the internet.</p><p>The server can reject a request because of:</p><ul><li>Validation rules</li><li>Permissions</li><li>Business rules</li><li>Deleted resources</li><li>Inventory changes</li><li>Duplicate actions</li></ul><p>Offline-First systems should handle both temporary failures and permanent failures.</p><p>Temporary failures can be retried.</p><p>Permanent failures need another decision.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfb1aba6db73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Offline-First Mobile Systems: How Data Synchronization Works in Offline-First Apps]]></title>
            <link>https://muhmmadnabil.medium.com/building-offline-first-mobile-systems-how-data-synchronization-works-in-offline-first-apps-da0495c2ab49?source=rss-90211108f014------2</link>
            <guid isPermaLink="false">https://medium.com/p/da0495c2ab49</guid>
            <category><![CDATA[offline-first]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Mohamed Nabil]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 06:22:49 GMT</pubDate>
            <atom:updated>2026-07-05T06:22:49.355Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J8b8ND41129bODXSm-yBCA.png" /></figure><p>You’re chatting with a friend on the subway.</p><p>You type a message. You hit send. It shows up instantly in the conversation, sitting there like it always does.</p><p>Then the train dips into a tunnel.</p><p>Signal drops.</p><p>Did it reach the server?</p><p>Did your friend receive it?</p><p>Or is it still waiting on your device until the connection comes back?</p><p>You don’t know. And from where you’re sitting, there’s no way to know — until the connection comes back.</p><p>That gap — between “the app shows something happened” and “the server actually knows it happened” — is what synchronization exists to close.</p><p>In the previous article, we designed the main building blocks of an Offline-First architecture: Local Database, Repository, Remote API, Sync Engine, Network Monitor, Background Workers, and Pending Operations Queue.</p><p>Now let’s focus on the part that connects all of them: Data Synchronization.</p><p>In a chat app, synchronization answers one important question:</p><blockquote><em>How can the app keep local messages and server messages consistent?</em></blockquote><p>This is where Offline-First becomes more than local caching.</p><p>The app not only saves data locally.</p><p>It also needs a reliable way to send local changes, receive remote changes, retry failed work, and avoid duplicates.</p><h3>The Main Sync Flow</h3><p>When the user sends a message, the app should not wait for the API response before showing it.</p><p>The message should be written locally first.</p><p>Then the sync system takes responsibility for sending it later.</p><p>The flow looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bKInXF24O-xgiDsJCh9Q9w.png" /></figure><p>The important point here is that the UI does not depend directly on the network.</p><p>The UI reads from the local database.</p><p>The sync engine works in the background to make the local state match the remote state.</p><h3>Push Sync</h3><p>Push Sync means sending local changes from the device to the server.</p><p>In a chat app, examples of local changes are:</p><ul><li>Sending a message</li><li>Deleting a message</li><li>Marking messages as read</li><li>Updating delivery state</li></ul><p>For example, when the user sends a message, we save it locally first:</p><pre>data class Message(<br>    val localId: String,<br>    val serverId: String?,<br>    val conversationId: String,<br>    val text: String,<br>    val status: MessageStatus<br>)</pre><pre>enum class MessageStatus {<br>    Sending,<br>    Sent,<br>    Failed<br>}</pre><p>At this point, the message exists locally, but the server does not know about it yet.</p><p>So we need another record that tells the sync engine what should happen.</p><pre>data class PendingOperation(<br>    val id: String,<br>    val type: OperationType,<br>    val entityId: String,<br>    val retryCount: Int<br>)</pre><pre>enum class OperationType {<br>    SendMessage,<br>    DeleteMessage,<br>    MarkAsRead<br>}</pre><p>The message is the data.</p><p>The pending operation is the instruction.</p><p>This separation is important.</p><p>The messages table keeps what the user sees.</p><p>The pending_operations table keeps what the sync engine still needs to do.</p><p>If the app closes, the pending operation is still stored locally.</p><p>When the app opens again, sync can continue.</p><h3>Pull Sync</h3><p>Push Sync sends local changes.</p><p>Pull Sync receives remote changes.</p><p>In a chat app, Pull Sync can receive:</p><ul><li>New messages</li><li>Delivered updates</li><li>Read receipts</li><li>Deleted messages</li><li>Conversation updates</li></ul><p>The flow is simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_fmyIBWvmB6p3cDcXlm6Q.png" /></figure><p>Again, the UI does not read directly from the API.</p><p>The API response updates the local database.</p><p>Then the UI reacts to the new local state.</p><p>This keeps one clear rule in the app:</p><blockquote><em>The local database is the source of truth.</em></blockquote><h3>Incremental Sync</h3><p>The app should not download the whole conversation every time it reconnects.</p><p>That may work for small conversations, but it becomes expensive when the conversation has hundreds or thousands of messages.</p><p>A better approach is Incremental Sync.</p><p>Instead of asking the server:</p><pre>Give me all messages.</pre><p>The app asks:</p><pre>Give me messages after sequence 120.</pre><p>For example:</p><pre>data class ConversationSyncState(<br>    val conversationId: String,<br>    val lastSyncedSequence: Long<br>)</pre><p>Each conversation can store the last synced sequence.</p><p>Then, when the app reconnects, it only asks for changes after that point.</p><p>This makes sync faster, cheaper, and easier to scale.</p><h3>Retry Logic</h3><p>Network requests fail all the time.</p><p>That is normal in mobile apps.</p><p>So the sync engine needs retry logic.</p><p>But not every failure should be retried forever.</p><p>Retryable failures:</p><ul><li>No internet</li><li>Timeout</li><li>Server unavailable</li></ul><p>Non-retryable failures:</p><ul><li>Invalid request</li><li>Unauthorized user</li><li>Backend rejected the operation</li></ul><p>A simple rule could look like this:</p><pre>fun shouldRetry(error: SyncError): Boolean {<br>    return when (error) {<br>        SyncError.NoInternet -&gt; true<br>        SyncError.Timeout -&gt; true<br>        SyncError.ServerUnavailable -&gt; true<br>        SyncError.InvalidRequest -&gt; false<br>        SyncError.Unauthorized -&gt; false<br>    }<br>}</pre><p>If the error is retryable, the operation stays pending.</p><p>If the error is not retryable, the operation should be marked as failed.</p><p>The user should have a clear way to recover.</p><p>For example:</p><pre>Sending...<br>Sent<br>Failed — Tap to retry</pre><p>A failed message should not disappear silently.</p><h3>Idempotency</h3><p>Retry creates another problem.</p><p>What if the app sends a message, the server receives it, but the response never reaches the app?</p><p>From the app’s point of view, the request failed.</p><p>So it retries.</p><p>Without protection, the server may create the same message twice.</p><p>That is why each message should have a stable client-generated ID.</p><p>For example:</p><pre>data class SendMessageRequest(<br>    val clientMessageId: String,<br>    val conversationId: String,<br>    val text: String<br>)</pre><p>The clientMessageId is created once on the device.</p><p>Every retry sends the same clientMessageId.</p><p>So if the server receives the same request again, it can recognize it as the same message, not a new one.</p><p>This is one of the most important ideas in synchronization:</p><blockquote><em>Retry makes sync possible.<br>Idempotency makes retry safe.</em></blockquote><h3>Conflict Resolution</h3><p>In chat apps, conflicts are usually simpler than in other domains because messages are mostly append-only.</p><p>But conflicts can still happen with actions like editing a message, deleting a message, or syncing read receipts from multiple devices.</p><p>The important rule is that conflict resolution should follow product rules, not random technical rules.</p><p>For example:</p><p>- For read receipts, the highest read sequence usually wins.<br>- For deleted messages, delete may win over edit.<br>- For sending messages, idempotency prevents duplicate sends.</p><p>So conflict resolution is not only a sync problem.</p><p>It is a product decision.</p><h3>Sync Engine Flow</h3><p>The sync engine does not need to be complicated in concept.</p><p>At a high level, it does this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ecjmM-z875nVdJVRqXWTTA.png" /></figure><p>A simplified version could look like this:</p><pre>class SyncEngine(<br>    private val pendingOperations: PendingOperationRepository,<br>    private val remoteDataSource: RemoteMessageDataSource<br>) {<br>    suspend fun sync() {<br>        val operations = pendingOperations.getPendingOperations()<br>        operations.forEach { operation -&gt;<br>            try {<br>                remoteDataSource.execute(operation)<br>                pendingOperations.markAsSynced(operation.id)<br>            } catch (error: SyncError) {<br>                if (shouldRetry(error)) {<br>                    pendingOperations.markForRetry(operation.id)<br>                } else {<br>                    pendingOperations.markAsFailed(operation.id)<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>This is not complete production code.</p><p>The point is the responsibility.</p><p>The sync engine should not control the UI.</p><p>It should only move pending local changes toward the server and update local state based on the result.</p><h3>Common Mistakes</h3><h3>Keeping pending operations only in memory</h3><p>If the app is killed, the sync work is lost.</p><p>Pending operations should be stored locally.</p><h3>Making the UI wait for the API</h3><p>In Offline-First apps, the UI should read from local state.</p><p>The API should not be the first source of truth for the screen.</p><h3>Retrying without idempotency</h3><p>Retry without a stable clientMessageId can create duplicate messages.</p><h3>Downloading everything again</h3><p>Full sync is simple, but it does not scale well.</p><p>For chat, incremental sync is usually better.</p><h3>Hiding failed messages</h3><p>If a message fails, the user should know.</p><p>A failed message should have a visible state and a retry option.</p><h3>What’s Next?</h3><p>In this article, we focused on how data moves between the device and the server.</p><p>But users do not see sync engines or pending operations.</p><p>They see UI states.</p><p>They see messages as sending, sent, failed, or retrying.</p><p>That is what we will discuss in the next article:</p><p>Optimistic Updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da0495c2ab49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Offline-First Mobile Systems: Designing the Architecture]]></title>
            <link>https://muhmmadnabil.medium.com/building-offline-first-mobile-systems-designing-the-architecture-42cc8b79d53b?source=rss-90211108f014------2</link>
            <guid isPermaLink="false">https://medium.com/p/42cc8b79d53b</guid>
            <category><![CDATA[offline-first]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Mohamed Nabil]]></dc:creator>
            <pubDate>Wed, 01 Jul 2026 23:13:56 GMT</pubDate>
            <atom:updated>2026-07-01T23:13:56.924Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J8b8ND41129bODXSm-yBCA.png" /></figure><p>In the first article, we defined Offline-First as an architectural decision, not a caching strategy.</p><p>Now let’s open the system and see how it actually works.</p><p>Imagine a user opens a chat conversation, writes a message, and taps send.</p><p>At the same moment, the network becomes unstable.</p><p>What should happen inside the app?</p><h3>The Offline-First Contract</h3><p>Before we talk about layers, repositories, queues, or sync engines, we need to define the contract of the system.</p><p>An Offline-First app should guarantee a few things.</p><p>The UI should be able to display data without waiting for the network.</p><p>User actions should be accepted locally first.</p><p>The local database should be the single source of truth for the app UI.</p><p>Every important action should be recoverable.</p><p>Sync should be able to fail without breaking the user experience.</p><p>The app should survive network loss, app restart, and process death.</p><p>And the UI should always represent the real state of the data.</p><p>For example, in a chat app, a message is not just “there” or “not there”.</p><p>A message can be:</p><ul><li>Pending</li><li>Sending</li><li>Sent</li><li>Delivered</li><li>Read</li><li>Failed</li></ul><p>These states matter.</p><p>Because when the user sends a message while offline, the message should not disappear.</p><p>It should appear immediately, but with a clear state.</p><p>Maybe it shows a small clock icon.</p><p>Maybe it shows “Sending…”</p><p>Maybe it shows a retry button if sending fails.</p><p>The exact UI does not matter here.</p><p>What matters is that the architecture supports this behavior.</p><p>Offline-First is not only about storing data.</p><p>It is about storing enough state to continue safely later.</p><h3>The Big Picture</h3><p>A typical Offline-First architecture has these main parts:</p><ul><li>UI</li><li>State Holder or ViewModel</li><li>Use Cases</li><li>Repository</li><li>Local Database</li><li>Pending Operations Queue (a table in the local Database)</li><li>Sync Engine</li><li>Remote API</li><li>Network Monitor</li><li>Background Worker</li></ul><p>Names and technologies vary — Room, SQLDelight, Core Data, Realm, and so on. That is not the important part. What matters is the responsibility of each component and how data moves through the app.</p><p>Here is the main idea:</p><blockquote><em>The UI reads from the local database.<br>User actions are written locally first.<br>The sync engine talks to the server later.</em></blockquote><h3>Main Architecture Diagram</h3><p>At a high level, the system can look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-oUzjfIvDduu4RNSjZfOA.png" /></figure><p>This diagram has three important flows:</p><ol><li>Read flow</li><li>Write flow</li><li>Sync flow</li></ol><p>Let’s break them down.</p><h3>Local Database as the Single Source of Truth</h3><p>This is the most important rule in Offline-First architecture:</p><blockquote><em>The local database is the single source of truth for the app UI.</em></blockquote><p>This means the UI should not depend directly on API responses.</p><p>When the screen needs messages, it observes messages from the local database.</p><p>When a new message arrives from the server, it is saved in the local database first.</p><p>When the user sends a message, it is saved in the local database first.</p><p>When the server confirms that a pending message was sent successfully, the local database is updated.</p><p>Then the UI reacts to the local database change.</p><p>There is one important nuance here.</p><p>The local database is the source of truth for the app UI.</p><p>The server may still be the final authority for shared data across devices and users.</p><p>For example, in a chat app, the server may decide the final message sequence, delivery state, or read receipts.</p><p>But inside the mobile app, the UI should still be driven by local data.</p><p>This separation is very important.</p><p>The server is the authority for global truth.</p><p>The local database is the source of truth for the local app experience.</p><h3>Read Flow: Opening a Conversation</h3><p>Let’s say the user opens a conversation.</p><p>In an Offline-First app, the screen should not wait for the network before showing messages.</p><p>The flow should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cUjng1tzKWwHMkZVbay8lg.png" /></figure><p>The important part is that the first data shown on the screen comes from the local database.</p><p>This makes the app feel fast.</p><p>This gives us one consistent path:</p><blockquote><em>Local Database → UI</em></blockquote><p>Whether the data was old, new, cached, synced, or created offline, the UI still reads it from the same place.</p><h3>Write Flow: Sending a Message</h3><p>Now let’s look at the more interesting part.</p><p>The user writes a message and taps send.</p><p>In an Offline-First app, we should not wait for the server before showing the message.</p><p>The app should accept the user action locally first.</p><p>The flow can look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4s7Kb4PMSpcXZUCr9zRWAA.png" /></figure><p>From the user’s point of view, the message appears immediately.</p><p>From the system’s point of view, the message is not fully synced yet.</p><p>That is why we need a state.</p><p>The message may start as Pending.</p><p>Then it may become Sending.</p><p>Then Sent.</p><p>Later, it may become Delivered.</p><p>Then Read.</p><p>The user does not need to wait for all of this.</p><p>They can continue using the app.</p><p>That is the user experience Offline-First is trying to protect.</p><h3>Saving Data Is Not Enough</h3><p>A common mistake is to save the message locally and stop there.</p><p>But that is not enough.</p><p>If the app saves a message locally while offline, it also needs to remember that this message must be uploaded later.</p><p>A message is data. Sending the message is an operation. Offline-First architecture needs to store both</p><p>The local database stores the data. The queue stores the work that still needs to happen. It is the memory of unfinished work.</p><p>Without it, the app may look Offline-First on the surface, but it will not be reliable. If the app is killed and reopened, it needs to know two things: what to display, and what still needs to be synced. The first answer comes from the local database. The second comes from the pending operations queue.</p><p>A queue operation can be something like:</p><pre>enum class PendingOperationType {<br>    SendMessage,<br>    DeleteMessage,<br>    MarkConversationAsRead,<br>    UploadVoiceNote<br>}</pre><p>And a simple pending operation model may look like this:</p><pre>data class PendingOperation(<br>    val id: String,<br>    val type: PendingOperationType,<br>    val entityId: String,<br>    val payload: String,<br>    val retryCount: Int,<br>    val createdAt: Long<br>)</pre><p>For example, when the user sends a message, we save two things:</p><ol><li>A local message with Pending status.</li><li>A queue operation of type SendMessage.</li></ol><p>Maybe the network returns in five seconds. Maybe the user closes the app and comes back tomorrow. The system should still know what needs to be done.</p><h3>Sync Engine</h3><p>The sync engine is responsible for moving local pending work to the server and bringing remote changes back to the local database.</p><p>It should not live inside the UI.</p><p>It should not be hidden inside a screen-specific ViewModel.</p><p>It should be a clear part of the architecture.</p><p>Why?</p><p>Because sync is not a screen behavior.</p><p>Sync is an app behavior.</p><p>A voice note may finish uploading after the user leaves the screen. A read receipt may be sent in the background. A failed operation may be retried after the app restarts. None of these belongs to a single screen.</p><p>If sync logic lives only inside the screen, it becomes fragile.</p><p>The sync engine usually has responsibilities like:</p><ul><li>Reading pending operations.</li><li>Sending them to the remote API.</li><li>Updating local data after success.</li><li>Keeping failed operations recoverable.</li><li>Retrying when it makes sense.</li><li>Pulling remote changes.</li><li>Coordinating with background workers.</li><li>Reacting to network changes.</li></ul><p>But we should be careful here.</p><p>Sync is a big topic.</p><p>Retry policies, incremental sync, full sync, conflict resolution, and idempotency deserve their own article.</p><p>So in this article, the main point is:</p><blockquote>Offline-First architecture needs a dedicated place for sync decisions.</blockquote><h3>Network Monitor Is Not the Sync Engine</h3><p>Another common mistake is thinking that network monitoring solves offline sync.</p><p>It does not.</p><p>A network monitor can tell the app:</p><p>“The device appears to be online.”</p><p>But that does not mean:</p><ul><li>The server is reachable.</li><li>The request will succeed.</li><li>The token is valid.</li><li>The payload is accepted.</li><li>The operation is safe to retry.</li><li>The data is not duplicated.</li></ul><p>Network availability is only a signal.</p><p>It can trigger the sync engine to try again.</p><p>But the sync engine still needs to handle failure.</p><p>For example:</p><p>The user sends a message offline.</p><p>The queue stores the operation.</p><p>Later, the network monitor says the device is online.</p><p>The sync engine starts uploading the message.</p><p>But the request fails because the server returns an error.</p><p>What should happen?</p><p>The answer should not be inside the network monitor.</p><p>The network monitor only says:</p><p>“Maybe now is a good time to sync.”</p><p>The sync engine decides what to do next.</p><h3>Background Worker</h3><p>A background worker helps the app continue sync work outside the current screen lifecycle.</p><p>This is important because users do not always stay on the same screen.</p><p>They may close the screen, switch apps, or lose connection entirely.</p><p>If the sync logic only runs while the screen is open, pending work may be stuck.</p><p>A background worker gives the app a better chance to continue.</p><p>In a mobile app, background execution has limits.</p><p>Different platforms have different rules.</p><p>Android, iOS, Flutter, React Native, and KMP all handle background work differently.</p><p>But the engineering idea is the same:</p><blockquote><em>Sync should not depend only on the screen being alive.</em></blockquote><p>The architecture should allow sync to run when possible.</p><h3>Message State Model</h3><p>Offline-First systems need clear state models.</p><p>Without a state, the UI becomes confusing, and the sync logic becomes harder to reason about.</p><p>For a chat message, we can start with something like this:</p><pre>enum class MessageStatus {<br>    Pending,<br>    Sending,<br>    Sent,<br>    Delivered,<br>    Read,<br>    Failed<br>}</pre><p>And the lifecycle may look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*155YwIJNqKJUx8lYUf2Gsg.png" /></figure><p>This state machine is simple, but it gives the system a clear language.</p><p>When the message isPending, it exists locally, but sync has not started yet.</p><p>When it isSending, the sync engine is trying to upload it.</p><p>When it isSent, the server accepts it.</p><p>When it isDelivered, the receiver’s device has received it.</p><p>When it isRead, the receiver has seen it.</p><p>When it is FailedThe app could not complete the operation and may need user action or retry.</p><p>The exact states depend on the product.</p><p>A POS, notes, or banking app will define its own states.</p><p>But the idea is the same:</p><blockquote><em>Offline-First architecture needs explicit states for user actions.</em></blockquote><p>If you do not model these states clearly, you will end up hiding complex behavior behind booleans.</p><p>And usually, that becomes painful later.</p><p>For example:</p><pre>val isSynced: Boolean<br>val isFailed: Boolean<br>val isLoading: Boolean</pre><p>This may work at the beginning.</p><p>But after adding retries, cancellation, delivery receipts, read receipts, and background sync, simple booleans become hard to maintain.</p><h3>Repository Responsibility</h3><p>In many apps, the repository is treated as a simple class that calls the API and maps the response.</p><p>But in Offline-First architecture, the repository has a bigger responsibility.</p><p>The repository protects the app from direct network dependency.</p><p>It coordinates local data, pending operations, and remote sync.</p><p>For example, a simplified sendMessage function may look like this:</p><pre>class ChatRepository(<br>    private val localDataSource: ChatLocalDataSource,<br>    private val pendingQueue: PendingOperationQueue<br>) {<br>suspend fun sendMessage(<br>        conversationId: String,<br>        text: String<br>    ) {<br>        val localMessageId = generateLocalId()<br>        val message = Message(<br>            id = localMessageId,<br>            conversationId = conversationId,<br>            text = text,<br>            status = MessageStatus.Pending,<br>            createdAt = currentTimeMillis()<br>        )<br>        localDataSource.insertMessage(message)<br>        pendingQueue.enqueue(<br>            PendingOperation(<br>                id = generateLocalId(),<br>                type = PendingOperationType.SendMessage,<br>                entityId = localMessageId,<br>                payload = buildSendMessagePayload(message),<br>                retryCount = 0,<br>                createdAt = currentTimeMillis()<br>            )<br>        )<br>    }<br>}</pre><p>Notice what this function does not do: it does not wait for the API, block the user, or make the UI depend on the server response. It accepts the action locally. The sync engine uploads it later.</p><blockquote><em>Write locally first.<br>Sync later.</em></blockquote><h3>Remote API Responsibility</h3><p>The remote API is still important.</p><p>Offline-First does not mean ignoring the server.</p><p>It means the app does not wait for the server to be usable.</p><p>The API is responsible for things like:</p><ul><li>Accepting pending local changes.</li><li>Returning server-generated IDs.</li><li>Returning official timestamps.</li><li>Returning the latest remote changes.</li><li>Confirming delivery state.</li><li>Rejecting invalid operations.</li><li>Helping the app resolve differences between local and remote data.</li></ul><p>But API responses should update the local database.</p><p>They should not become a second source of truth for the UI.</p><p>For example, when the server accepts a message, it may return:</p><ul><li>Server message ID</li><li>Server timestamp</li><li>Message sequence</li><li>Delivery state</li></ul><p>The sync engine should use this response to update the local message row.</p><p>Then the UI updates because the local database changed.</p><p>Again, the path stays consistent:</p><blockquote><em>Server → Local Database → UI</em></blockquote><p>Not directly:</p><blockquote><em>Server → UI</em></blockquote><h3>Common Offline-First Design Mistakes</h3><p>Offline-First architecture is powerful, but it is easy to get wrong.</p><p>Here are some common mistakes.</p><h3>Mistake 1: Treating the Local Database as a Cache</h3><p>A cache is usually temporary.</p><p>If it is empty, the app can ask the network.</p><p>If it is stale, the app can replace it.</p><p>But in Offline-First architecture, the local database is more than a cache.</p><p>It stores the current state, pending data, failed data, and operations that still need to happen.<br>If you treat the local database as a simple cache, you will probably lose important state.</p><h3>Mistake 2: Saving Data Without Saving the Operation</h3><p>Saving a pending message is not enough.</p><p>The app also needs to remember that this message must be sent.</p><p>If the message exists locally but no operation exists in the queue, the sync engine may never upload it.</p><p>This creates a dangerous situation.</p><p>The UI shows the message, but the server never receives it.</p><p>That is why Offline-First architecture usually needs both:</p><ul><li>Local data</li><li>Pending operation</li></ul><h3>Mistake 3: Putting Sync Logic in the UI</h3><p>The UI should not know how to sync data.</p><p>The UI should show the state and send user actions.</p><p>If sync logic lives inside the UI, it becomes tied to the screen lifecycle.</p><p>When the screen is closed, sync may stop.</p><p>When the app restarts, the sync state may be lost.</p><p>The sync engine should be independent of the screen.</p><h3>Mistake 4: Ignoring Failed States</h3><p>Offline-First does not mean everything will eventually succeed automatically.</p><p>Some operations may fail permanently.</p><p>Maybe the server rejects it, the user lost permission, the payload is invalid, or the conversation was deleted from another device.</p><p>The UI needs a way to show failure.</p><p>The system needs a way to recover.</p><p>Ignoring failed states makes the app look simple in the beginning, but it creates a bad user experience later.</p><h3>Trade-offs</h3><p>Offline-First architecture gives the user a better experience.</p><p>But it is not free.</p><p>You will write more code — more local models, more states, a queue, sync rules, and more edge cases to think about upfront.</p><p>For example:</p><p>What happens if the user sends five messages offline?</p><p>What happens if the third message fails?</p><p>Should the fourth message wait?</p><p>Can messages be uploaded in parallel?</p><p>How do you prevent duplicated messages?</p><p>What happens if the app is killed after saving the message but before adding the queue operation?</p><p>What happens if the server accepts the message, but the response never reaches the app?</p><p>These are not easy questions.</p><p>But they are the real questions behind Offline-First systems.</p><p>This is why Offline-First should be an architecture decision, not a small feature added at the end.</p><p>If the app really needs to work under unreliable network conditions, then the architecture should be designed for that from the beginning.</p><h3>What’s Next?</h3><p>Now we have the architecture.</p><p>But architecture alone is not enough.</p><p>The next hard question is:</p><blockquote><em>How does the app sync data correctly?</em></blockquote><p>In the next article, we will go deeper into data synchronization.</p><p>We will talk about push sync, pull sync, incremental sync, retry policies, idempotency, conflict handling, and error recovery.</p><p>Because in real Offline-First systems, sync is where most of the complexity lives.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42cc8b79d53b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Offline-First Mobile Systems: What Does Offline-First Mean?]]></title>
            <link>https://muhmmadnabil.medium.com/building-offline-first-mobile-systems-what-does-offline-first-mean-4c9da1b091d3?source=rss-90211108f014------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c9da1b091d3</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[offline-first]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Mohamed Nabil]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 08:01:02 GMT</pubDate>
            <atom:updated>2026-06-30T08:01:02.713Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J8b8ND41129bODXSm-yBCA.png" /></figure><h3>Let’s start with a simple chat problem</h3><p>Imagine you are using a chat app.</p><p>You write a message:</p><blockquote><em>“I’m on my way.”</em></blockquote><p>Then you press send.</p><p>At the same moment, your internet connection drops.</p><p>Now the question is:</p><p>What should the app do?</p><p>Should it show an error?</p><p>Should the message disappear?</p><p>Should the user write it again?</p><p>Or should the app show the message immediately, mark it as pending, and send it later when the internet comes back?</p><p>This small moment explains the real idea behind Offline-First.</p><p>Offline-First is not about caching old messages.</p><p>It is not about saving API responses locally.</p><p>It is not about using Room, SQLDelight, Realm, Core Data, or any specific database.</p><p>Offline-First means the app is designed to continue working even when the network is unstable.</p><p>And in a chat app, this means one very important thing:</p><blockquote><em>A message should not be lost just because the internet failed.</em></blockquote><h3>The normal way</h3><p>In many apps, the flow is very simple:</p><ol><li>User sends a message.</li><li>App calls the API.</li><li>App waits for the response.</li><li>If the API succeeds, the message appears.</li><li>If the API fails, the app shows an error.</li></ol><p>This sounds fine at first.</p><p>But there is a problem.</p><p>The user action depends completely on the network.</p><p>If the network is slow, sending feels slow.</p><p>If the request fails, the message fails.</p><p>If the app is closed before the request finishes, the message may be lost.</p><p>That is not a good experience for a chat app.</p><p>When users send a message, they expect the app to keep it safe.</p><p>They do not think about APIs, requests, retries, or network problems.</p><p>They only think:</p><blockquote><em>“I wrote this message. The app should not lose it.”</em></blockquote><h3>The offline-first way</h3><p>In an Offline-First chat app, we do not start with the API.</p><p>We start with the local database.</p><p>The flow becomes:</p><ol><li>User sends a message.</li><li>The app saves the message to the local database.</li><li>The app shows the message immediately — maybe with a small clock icon next to it. That icon tells the user: <em>“Your message is saved. We will send it when we can.”</em></li><li>Message status becomes Pending.</li><li>App adds this message to a queue (local database).</li><li>When the internet is available, the app sends it to the server.</li><li>If sending succeeds, the message becomes Sent.</li><li>If sending fails, the app retries or marks it as Failed.</li></ol><p>The key idea is simple:</p><blockquote><em>The message exists locally before it exists on the server.</em></blockquote><p>This is the heart of Offline-First.</p><p>The server is still important.</p><p>But the user experience should not wait for the server every time.</p><h3>Local database as the single source of truth</h3><p>This is one of the most important rules in Offline-First:</p><blockquote><em>The local database is the single source of truth.</em></blockquote><p>This means the UI should read messages from the local database.</p><p>Not directly from the API.</p><p>When the app receives messages from the server, it saves them locally first.</p><p>When the user sends a message, it saves it locally first.</p><p>When sync succeeds, it updates the local message.</p><p>When sync fails, it updates the local message.</p><p>The UI only listens to the local database.</p><p>So the flow becomes clear:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f0pWML2Paqppuz2NOCTe-Q.png" /></figure><p>This makes the app easier to reason about.</p><p>The UI does not need to ask:</p><p>“Should I show API data or local data?”</p><p>It only has one answer:</p><blockquote><em>Show what exists in the local database.</em></blockquote><p>That is why we call it the single source of truth.</p><h3>This idea is bigger than chat</h3><p>We are using a chat app as our main example in this series.</p><p>But the same idea applies to many other apps.</p><p>A POS system should not block the cashier just because the connection drops.</p><p>A notes app should not lose a draft because the user went offline.</p><p>A delivery app should let the driver update the order status even in a weak-signal area.</p><p>The domain changes.</p><p>But the principle is the same:</p><blockquote><em>The app should protect the user’s work first, then sync when possible.</em></blockquote><p>That is why Offline-First is not a chat-only idea.</p><p>It is a mobile architecture idea.</p><h3>Message lifecycle</h3><p>A chat message is not only text.</p><p>It has a state.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWZ4RAZGYe9XeSlQRu-KKA.png" /></figure><p>A message usually starts locally first.</p><p>Then it becomes Pending.</p><p>If sync succeeds, it becomes Sent.</p><p>After that, the server may confirm it as Delivered.</p><p>Later, when the other user opens the conversation, it becomes Read.</p><p>If sync fails, the message moves toFailed, and the user or the app can retry it.</p><h3>Coding example</h3><p>The code here is not the main point.</p><p>The idea is the main point.</p><pre>class MessagesRepository(<br>    private val localDataSource: MessagesLocalDataSource,<br>    private val syncQueue: SyncQueue<br>) {<br>    fun observeMessages(conversationId: String): Flow&lt;List&lt;Message&gt;&gt; {<br>        return localDataSource.observeMessages(conversationId)<br>    }<br>    suspend fun sendMessage(<br>        conversationId: String,<br>        text: String<br>    ) {<br>        val message = Message(<br>            id = MessageId.local(),<br>            conversationId = conversationId,<br>            text = text,<br>            status = MessageStatus.Pending,<br>            createdAt = Clock.now()<br>        )<br>        localDataSource.saveMessage(message)<br>        syncQueue.enqueue(<br>            SyncOperation.SendMessage(message.id)<br>        )<br>    }<br>}</pre><p>Notice the order.</p><p>We do not call the API first.</p><p>We save the message locally first.</p><p>Then we add it to the queue.</p><p>This means the message is safe even if the network is down.</p><p>The UI will show it because the UI is observing the local database.</p><p>Later, the sync logic can send it to the server.</p><h3>Why not just call the API and retry?</h3><p>You may ask:</p><p>Why do we need all of this?</p><p>Why not just call the API, and if it fails, retry?</p><p>The problem is that retry alone is not enough.</p><p>Where will the message live while waiting?</p><p>What happens if the app is closed?</p><p>What happens if the device restarts?</p><p>What happens if the user sends 10 messages while offline?</p><p>What happens if some messages succeed and others fail?</p><p>To handle these cases, we need more than a network retry.</p><p>We need a local state.</p><p>We need a queue.</p><p>We need the message status.</p><p>We need the local database to be the single source of truth.</p><p>That is why Offline-First is an architecture decision, not just a retry function.</p><h3>Trade-offs</h3><p>Offline-First gives the user a better experience.</p><p>But it is not free.</p><p>When we choose Offline-First, we accept more responsibility inside the app.</p><p>First, the architecture becomes more complex from the beginning.</p><p>Instead of only calling an API and showing the result, we now need local storage, local states, queues, and sync logic.</p><p>Second, we need to manage storage carefully.</p><p>Messages, media files, voice notes, and failed operations can grow over time.</p><p>So the app needs a clear strategy for cleanup, cache limits, and old data.</p><p>Third, sync conflicts become our problem.</p><p>What if the same message was edited from another device?</p><p>What if a message was deleted on the server while it still exists locally?</p><p>What if the user sends messages offline, but the conversation was deleted from another device?</p><p>These cases need clear rules.</p><p>Fourth, the UI must show the right state.</p><p>A pending message should not look exactly like a sent message.</p><p>A failed message should not disappear silently.</p><p>The user should understand what is happening without feeling confused.</p><p>So yes, Offline-First improves reliability.</p><p>But it also adds complexity.</p><p>That is why it should be an architecture decision from day one, not something we add quickly at the end.</p><h3>Common mistakes</h3><h3>1. Treating Offline-First as caching</h3><p>Caching means:</p><blockquote><em>“I saved old data so I can show it later.”</em></blockquote><p>Offline-First means more than that.</p><p>It means the user can still take actions, and the app can sync those actions later.</p><p>In a chat app, showing old messages offline is useful.</p><p>But if the user cannot send a new message while offline, the app is not really Offline-First.</p><h3>2. Not defining the source of truth</h3><p>This is a big mistake.</p><p>If the UI sometimes reads from the API and sometimes reads from the local database, the app becomes hard to understand.</p><p>You may see different states in different screens.</p><p>You may update the UI from the API, but forget to update the local database.</p><p>Or you may update the local database, but the UI still waits for the API.</p><p>To avoid this, define the rule early:</p><blockquote><em>The local database is the single source of truth.</em></blockquote><h3>3. Building sync as an afterthought</h3><p>Sync is not a small feature.</p><p>It is one of the hardest parts of Offline-First.</p><p>If we design the app as online-first, then later try to add offline support, we will probably change many parts of the app.</p><p>The data flow.</p><p>The UI states.</p><p>The repository.</p><p>The error handling.</p><p>The retry logic.</p><p>This is why Offline-First should be part of the architecture from the start.</p><h3>4. Hiding failed states from the user</h3><p>Sometimes developers try to make the UI look clean by hiding failures.</p><p>But this can create a worse experience.</p><p>If a message fails to send, the user should know.</p><p>Maybe we should show a retry button.</p><p>Maybe we show a small error icon.</p><p>Maybe we can keep it pending and retry automatically.</p><p>The exact UI can change.</p><p>But the failure should not be invisible.</p><p>Because if the user thinks the message was sent, but it was not, this becomes a trust problem.</p><h3>Key takeaways</h3><p>Offline-First is not a feature you add at the end.</p><p>It is a constraint you design around from day one.</p><p>The network should improve the experience, not control it.</p><p>The local database is the single source of truth.</p><p>The server is still important, but it is a sync target from the mobile app&#39;s point of view.</p><p>The UI should show the local state clearly.</p><p>A pending message should look pending.</p><p>A failed message should look failed.</p><p>A sent message should look sent.</p><p>A good Offline-First design is not about hiding network problems.</p><p>It is about making the app behave safely when those problems happen.</p><p>For our chat app, the first rule is simple:</p><blockquote><em>Save the message locally first. Then sync.</em></blockquote><p>Everything else comes from that decision.</p><h3>What comes next</h3><p>Now we understand the mindset.</p><p>But this creates a bigger question:</p><p>What does this architecture actually look like in practice?</p><p>If the UI reads from the local database, who updates the database?</p><p>If messages are saved locally first, who sends them later?</p><p>Where do pending operations live?</p><p>Who decides when to retry?</p><p>And what happens if we skip one of these parts?</p><p>In the next article, we will design the full Offline-First architecture for our chat app.</p><p>We will see why each layer exists, how data moves through the system, and why Offline-First needs more than just a local database.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c9da1b091d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>