Design an offline-first notes app

Learn how to design an offline-first Android notes app: Room as source of truth, a WorkManager outbox, idempotency keys, and server-versioned conflicts. About 25 minutes.

Why it matters

  • Users expect notes, email, and task apps to work offline. Interviewers expect you to start from local storage, not from a network call.
  • The outbox pattern and conflict resolution are the parts that cause real production bugs: lost writes, duplicate entries, and stale UI after a failed sync.
  • WorkManager unique work, constraints, battery, and what happens when an OEM kills the app are common follow-up questions that separate mid from senior answers.
  • This pattern reuses in the chat app (local outbox for messages) and the file upload service (resumable chunks), so the mental model transfers across the module.

The simple explanation

  • You keep a paper notebook at home. That is your Room database.
  • You write notes anytime, even with no internet. Each write also drops a slip into a 'to-mail' pile (the outbox).
  • When the mail truck comes (WorkManager), you send the pile and collect updates from the office (server).
  • The office stamps every page it accepts with a version number. If your slip was based on an older version, the office sends it back and you merge.
  • You never stop writing because the mail truck is late. The notebook is always current.

How do you design an offline-first notes app on Android? Make the local Room database the source of truth: the UI reads notes from Room via Flow, and every edit writes the note and an outbox row in one transaction. A WorkManager worker, enqueued as unique work with a network constraint, pushes the outbox with idempotency keys and pulls remote changes. The server assigns a version to every accepted write, so stale edits are detected and merged instead of silently overwritten. The app never blocks on the network.

LayerRoleKey API
UI / ViewModelRender from Flow<Note>Room + Flow
RepositoryWrite note + outbox row, enqueue syncwithTransaction, suspend fun
OutboxQueue unsynced writes@Entity in Room
Sync workerPush, pull, resolve conflictsCoroutineWorker, enqueueUniqueWork
APIREST with idempotency and versionsIdempotency-Key, If-Match or a version field, change token

Conflict resolution is the hardest part. Each synced note stores the version the server last gave it, and a push sends that base version. If the server has moved on (the same user edited on another device), it rejects the write with 409 Conflict (or 412 with If-Match). The client fetches the current copy, merges against its base (field-level, server wins, or keep both as a conflict copy) and pushes again with the new version. Plain last-write-wins is acceptable for some single-user apps, but it should use the server's order, never the phone's clock. Real-time collaborative editing needs CRDTs or operational transforms, which is a different design.

Sync triggers: after every local write, enqueueUniqueWork("note-sync", ExistingWorkPolicy.APPEND_OR_REPLACE, request) with a NetworkType.CONNECTED constraint and exponential backoff; WorkManager runs it when the network returns, so no manual connectivity listener is needed. Add a sync when the app comes to the foreground, a periodic request as a safety net, and optionally an FCM message from the server that says "something changed".

Security: if notes are sensitive, encrypt the database with SQLCipher (net.zetetic:sqlcipher-android, passed to Room through openHelperFactory(SupportOpenHelperFactory(passphrase))). Generate a random passphrase and store it encrypted with a key held in the Android Keystore; Keystore keys themselves cannot be exported.

Observability: log sync duration, conflict count, and outbox depth. Alert if outbox depth exceeds a threshold, which signals a stalled sync.

Offline-first writes and sync
Offline-first writes and sync The user saves a note. The repository writes the note and an outbox row to Room in one transaction, and the UI, which reads notes from Room through a Flow, shows it at once. The repository enqueues unique sync work. When online, the sync worker pushes the outbox with an idempotency key. On success it stores the new version and clears the outbox row. On a 409 conflict it fetches the server copy, merges and retries. Idempotency key on every push. On 409: fetch, merge, push again SAVE NOTE NOTE + OUTBOX SHOWN AT ONCE enqueueUniqueWork PUSH OUTBOX VERSION OR 409 SAVE VERSION UI note editor Repository writes locally Room notes + outbox Sync worker WorkManager Server sync API
A save never waits for the network: it lands in Room with an outbox row, and a unique sync job pushes it later, merging on a 409 conflict.

Notes

  • Room is the source of truth; the network is a remote replica. The UI reads from Flow<Note>, never from a raw network response.
  • Every local write updates the notes table and inserts an outbox row inside one withTransaction block (or a @Transaction DAO method) so they stay consistent.
  • Enqueue sync as unique work with ExistingWorkPolicy.APPEND_OR_REPLACE and a NetworkType.CONNECTED constraint, so a write made during a running sync gets its own run afterwards. Never use REPLACE, which cancels a running upload.
  • Expedited work (setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)) is for short work the user is waiting for, has a quota, and only supports network and storage constraints. Ordinary note sync does not need it.
  • Create the idempotency key with the local write and store it in the outbox row, so every retry sends the same key and a timeout cannot create a duplicate note. Client-generated note IDs (UUIDs) help too: creating the same ID twice is a no-op.
  • Versions come from the server. On 409 or 412, fetch the current copy, merge against the base, and retry with the new version; resending the same request fails forever.
  • Pull with a server-issued change token ("give me everything changed since token X"), not the newest updatedAt the client has seen, so clock differences cannot skip changes.
  • When pulling, do not overwrite a note that still has pending local edits; merge it the same way as a rejected push.
  • Deletes are writes too: keep a tombstone (deleted = true) in Room until the server confirms, or the note reappears on the next pull.
  • The notes list can use Room's PagingSource directly. RemoteMediator is not needed when a sync worker keeps the whole set up to date.
  • Encrypt the database with SQLCipher (SupportOpenHelperFactory) only if notes are sensitive, and protect the passphrase with a Keystore key.
  • Sync when the app comes to the foreground too, not only from the background schedule, so the user sees fresh data on return.
  • Log outbox depth, sync duration, and conflict count. A growing outbox depth signals a stalled sync.
  • Some OEM battery managers kill apps aggressively, and then no scheduled work runs until the user opens the app. You cannot fully fix that; show a "not synced" badge and sync on app open.

Code example

The write path and the push half of the sync worker. Pull and merge are left as comments; the conflict handling follows the sync-strategies lesson.

import android.content.Context
import androidx.room.Dao
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Upsert
import androidx.room.withTransaction
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import java.io.IOException
import java.util.UUID
import java.util.concurrent.TimeUnit
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.Header
import retrofit2.http.PUT
import retrofit2.http.Path
 
@Entity(tableName = "notes")
data class NoteEntity(
    @PrimaryKey val id: String,      // UUID created on the device
    val title: String,
    val body: String,
    val serverVersion: Long?,        // null until the server first accepts it
)
 
@Entity(tableName = "outbox")
data class OutboxEntry(
    @PrimaryKey val idempotencyKey: String, // created with the local write
    val noteId: String,
    val createdAt: Long,
)
 
@Dao
interface NotesDao {
    @Upsert suspend fun upsert(note: NoteEntity)
    @Query("SELECT * FROM notes WHERE id = :id") suspend fun get(id: String): NoteEntity?
    @Insert suspend fun enqueue(entry: OutboxEntry)
    @Query("SELECT * FROM outbox ORDER BY createdAt LIMIT :limit") suspend fun pending(limit: Int): List<OutboxEntry>
    @Query("DELETE FROM outbox WHERE idempotencyKey = :key") suspend fun remove(key: String)
}
 
data class NoteBody(val title: String, val body: String, val baseVersion: Long?)
data class NetworkNote(val id: String, val title: String, val body: String, val version: Long)
 
interface NotesApi {
    @PUT("notes/{id}")
    suspend fun put(
        @Path("id") id: String,
        @Header("Idempotency-Key") key: String,
        @Body note: NoteBody,
    ): Response<NetworkNote> // 409 when baseVersion is stale
}
 
class NoteRepository(private val db: NotesDb, private val workManager: WorkManager) {
    suspend fun save(id: String, title: String, body: String) {
        val dao = db.notesDao()
        db.withTransaction {
            val base = dao.get(id)?.serverVersion
            dao.upsert(NoteEntity(id, title, body, serverVersion = base))
            dao.enqueue(OutboxEntry(UUID.randomUUID().toString(), id, System.currentTimeMillis()))
        }
        val request = OneTimeWorkRequestBuilder<SyncWorker>()
            .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
            .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
            .build()
        workManager.enqueueUniqueWork("note-sync", ExistingWorkPolicy.APPEND_OR_REPLACE, request)
    }
}
 
class SyncWorker(
    context: Context,
    params: WorkerParameters,
    private val db: NotesDb,   // provided by a WorkerFactory, for example Hilt's
    private val api: NotesApi,
) : CoroutineWorker(context, params) {
 
    override suspend fun doWork(): Result {
        val dao = db.notesDao()
        try {
            while (true) {
                val batch = dao.pending(limit = 20)
                if (batch.isEmpty()) break
                for (entry in batch) {
                    val note = dao.get(entry.noteId)
                    if (note == null) { dao.remove(entry.idempotencyKey); continue }
                    val response = api.put(note.id, entry.idempotencyKey, NoteBody(note.title, note.body, note.serverVersion))
                    when {
                        response.isSuccessful -> db.withTransaction {
                            val saved = response.body() ?: return@withTransaction
                            // Keep local text (it may have changed since); adopt the new server version
                            dao.get(note.id)?.let { dao.upsert(it.copy(serverVersion = saved.version)) }
                            dao.remove(entry.idempotencyKey)
                        }
                        response.code() == 409 -> {
                            // Fetch the server copy, merge against the base, save it with the
                            // server's version as the new base; the row stays queued and is retried
                            return Result.retry()
                        }
                        response.code() >= 500 || response.code() == 429 -> return Result.retry()
                        else -> dao.remove(entry.idempotencyKey) // permanent error: mark the note failed in a real app
                    }
                }
            }
            // Pull: GET changes since the stored change token, skip notes with pending edits
            return Result.success()
        } catch (e: IOException) {
            return Result.retry()
        }
    }
}
  • The note and its outbox row are written in one transaction, then sync is enqueued as unique work with APPEND_OR_REPLACE, so an edit made during a running sync always gets a later run.
  • The idempotency key is created with the write, so a retried request after a timeout sends the same key and the server returns the original result.
  • The push sends the server version the edit was based on; the client never invents versions. On success it stores the new version but keeps the local text, because the user may have typed more while the request was in flight (that newer edit has its own outbox row).
  • Only IOException, 5xx and 429 retry with backoff. CancellationException is not caught, so WorkManager can stop the worker cleanly.

Run the idea in plain Kotlin

data class Note(val id: String, val text: String, val version: Long)

data class OutboxEntry(val key: String, val noteId: String, val text: String, val baseVersion: Long)

// The server owns versions and remembers idempotency keys it has already applied
class FakeServer {
  val notes = mutableMapOf("n1" to Note("n1", "milk", 1))
  private val applied = mutableMapOf<String, Note>()

  fun put(e: OutboxEntry): Pair<Int, Note> {
      applied[e.key]?.let { return 200 to it }           // retry of a write already applied
      val current = notes.getValue(e.noteId)
      if (e.baseVersion != current.version) return 409 to current
      val saved = Note(e.noteId, e.text, current.version + 1)
      notes[e.noteId] = saved
      applied[e.key] = saved
      return 200 to saved
  }
}

fun main() {
  val server = FakeServer()

  // Phone A edits offline from version 1; the response to its first try is lost
  val a = OutboxEntry("key-a", "n1", "milk, eggs", baseVersion = 1)
  println("A push: " + server.put(a).first)
  println("A retry after timeout: " + server.put(a).first + ", version=" + server.notes.getValue("n1").version)

  // Phone B also edited offline from version 1
  val b = OutboxEntry("key-b", "n1", "milk, bread", baseVersion = 1)
  val (code, current) = server.put(b)
  println("B push: " + code + ", server has v" + current.version + " '" + current.text + "'")

  // B merges against the server copy and retries with the server's version as its base
  val merged = OutboxEntry("key-b", "n1", "milk, eggs, bread", baseVersion = current.version)
  val (code2, saved) = server.put(merged)
  println("B merged push: " + code2 + ", v" + saved.version + " '" + saved.text + "'")
}

Expected output:

A push: 200
A retry after timeout: 200, version=2
B push: 409, server has v2 'milk, eggs'
B merged push: 200, v3 'milk, eggs, bread'

In production

Outbox entries lost after a Room schema migration
  • A schema change to the outbox table was written as a manual Migration that created a new table, dropped the old one and renamed the new one, but forgot the INSERT INTO ... SELECT that copies the rows.
  • The migration ran without errors, so nothing crashed. Users who had unsynced edits when they updated the app lost those changes: the notes stayed on the device but were never uploaded.
  • The outbox depth metric dropped to zero on update day for those users, which was only noticed later.
The fix
  • Fixed the migration to copy the rows, and shipped a follow-up that re-queues every note whose serverVersion was null or whose local copy differed from the last synced one.
  • Added migration tests with MigrationTestHelper that create the old schema, insert outbox rows, run the migration and assert the rows are still there.
  • Exported Room schemas (room.schemaLocation) so schema changes show up in code review, and used auto-migrations where Room can generate them.
WorkManager not firing on certain OEM launchers
  • Users on some devices reported that edits made offline did not reach their other devices until hours later.
  • Sync metrics split by manufacturer showed the delay was concentrated on a few OEMs with aggressive battery managers that stop background work for apps the user has not opened recently.
  • The app only synced from background WorkManager work, so on those devices nothing ran until the system allowed it.
The fix
  • Added a sync whenever the app comes to the foreground (ProcessLifecycleOwner), so opening the app always pushes pending edits.
  • Showed a small "not synced yet" badge on notes with pending outbox rows, plus a "Sync now" action, so users know what state they are in.
  • Kept tracking sync delay per manufacturer. A foreground service was rejected: it cannot be started from the background on Android 12+ in this situation, and it would not stop an OEM from killing the app.

Common mistakes

  • Reading from the network response in the UI instead of from Room. The UI shows stale or missing data when the network is slow or offline. Always expose a Flow from Room so the UI reflects local state immediately.
  • Writing to the notes table and the outbox table in separate transactions. If the app is killed between the two writes, the note is saved but the outbox entry is missing, so the change never syncs. Wrap both in withTransaction or a @Transaction DAO method.
  • Omitting the Idempotency-Key header on the push API. A network timeout causes the client to retry, and the server creates a duplicate note. Always send a stable key (the outbox entry id) and have the server deduplicate on it.
  • Storing the SQLCipher passphrase in plain SharedPreferences. The file is private to the app, but it is plain text on a rooted device and can end up in backups. Encrypt the passphrase with a Keystore key (or use a library that does) and exclude it from backups.
  • Resolving conflicts with the phone's clock. Comparing updatedAt from two devices picks the wrong winner when a clock is off. Send the server version the edit was based on and let the server detect stale writes.
  • Scheduling sync only through a periodic WorkManager request. The minimum interval is 15 minutes and it can be delayed further. Enqueue one-time unique work after every write and sync when the app comes to the foreground.
  • Using ExistingWorkPolicy.REPLACE for the sync. Every new edit cancels the running sync, possibly mid-request. Use APPEND_OR_REPLACE, or KEEP with a worker that drains until the outbox is empty.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“How do you structure the data layer for an offline-first notes app?”

“How do you handle conflicts when two devices edit the same note?”

“How do you schedule and trigger background sync on Android?”

“How do you keep the UI consistent during and after a sync?”

Quiz

In an offline-first architecture, what is the source of truth?

What does the outbox pattern solve?

Which WorkManager constraint prevents sync during low battery?

What HTTP status code should the server return when a client write conflicts with the server version?

0 of 4 answered

Mini task

15-minute exercise: wire a minimal offline-first sync loop

  1. Create a Room database with two entities: Note (id, title, body, serverVersion) and OutboxEntry (idempotencyKey, noteId, createdAt), and a DAO like the one in this lesson.
  2. Write NoteRepository.save(...) that, inside one withTransaction, upserts the note and inserts an OutboxEntry with a fresh UUID key, then enqueues SyncWorker with enqueueUniqueWork("note-sync", ExistingWorkPolicy.APPEND_OR_REPLACE, request).
  3. Write SyncWorker extending CoroutineWorker, pushing against a fake NotesApi that stores versions and returns 409 for a stale baseVersion. Return Result.retry() on IOException and 5xx, not on 409.
  4. Give the request Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build() and setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS).
  5. Test the worker with TestListenableWorkerBuilder and a fake API that fails once with an IOException after saving.
  6. Done condition: turn on airplane mode, edit a note, kill the app, and reopen. The note appears immediately from Room. Turn the network back on: the worker runs, the outbox row is removed, the note's serverVersion is updated, and the fake server holds the note exactly once.
Next: Design an image loading library