Design an offline-first notes app with sync
The question
Design an offline-first notes app for Android. Users can create, edit, and delete notes without a network connection. When connectivity returns, changes sync to a server. Walk me through the client architecture, local storage, sync mechanism, and how you handle conflicts.
Clarify before you design:
- Is this a single-user app (one person, several devices) or do multiple users share the same note?
- What is the expected note volume per user, say a few hundred or tens of thousands?
- Do we need real-time collaboration (two people editing the same note simultaneously) or is eventual consistency acceptable?
- What is the minimum Android version we target?
- Are notes plain text, or do we need rich text, attachments, or images?
- Is there a hard requirement for end-to-end encryption, or is transport security (TLS) sufficient?
- How fresh must other devices be: within seconds, within minutes, or when the user opens the app?
Requirements
Functional
- Create, read, update, and delete notes fully offline with no network dependency.
- Persist all local changes to Room immediately; the UI reflects the write before any network call.
- Sync pending changes to the server when connectivity is available, using an outbox pattern.
- Pull server-side changes the client has not seen, applying them to the local Room database.
- Detect and resolve conflicts when the same note was modified on both client and server.
- Support soft delete (tombstone) so deletions propagate to the server and other devices.
Non-functional
- The app must remain responsive (no ANR) even when the Room database holds tens of thousands of rows.
- Sync must be battery friendly: let WorkManager batch and defer it, and never poll the server in a loop. Note edits are tiny, so they sync on any connection; large attachments could wait for an unmetered network.
- Sync retries must use exponential backoff to avoid hammering the server on transient failures.
- The notes list must scroll smoothly with Paging 3, loading pages on demand instead of the whole table.
- User data must survive process death and configuration changes without loss.
- Flow collection must stop when the screen is not visible, so the app does no UI work in the background.
Out of scope
- Server-side storage engine, database sharding, or multi-region replication.
- Real-time collaborative editing with operational transformation or CRDTs between two live cursors.
- Authentication and authorization flows; assume a valid session token is already available.
High-level architecture
The client has three layers: UI, an optional Domain layer, and Data.
UI layer. Compose screens collect a StateFlow<UiState> from a ViewModel with collectAsStateWithLifecycle. The notes list is a separate Flow<PagingData<NoteUi>>, cached with cachedIn(viewModelScope) and collected with collectAsLazyPagingItems(). The editor keeps the draft in the ViewModel (backed by SavedStateHandle) and autosaves it to Room, so process death does not lose typed text.
Domain layer. Optional. A use case such as ResolveConflictUseCase holds the merge rules as plain Kotlin, which makes them easy to unit test. Small apps can skip this layer.
Data layer. Room is the single source of truth. NoteRepository is the only class that reads and writes it: it exposes Flow reads and suspend fun save(...) / suspend fun delete(...) writes. Three tables matter: notes (with a dirty flag and serverVersion), pending_ops (the outbox), and sync_state (the server's change token). Every write updates notes and inserts a pending_ops row in the same transaction, then enqueues a one-time unique SyncWorker. A periodic sync request is the safety net. The worker pushes the outbox through SyncApi (Retrofit over OkHttp), applies the server's answers, and pulls changes.
Data flow. User edits a note → ViewModel calls repository.save() → Room transaction writes notes and pending_ops → Room's Flow re-emits → UI updates. WorkManager runs SyncWorker when there is a network → it pushes the outbox → the server returns accepted ops and conflicts → conflicts are merged → Room is updated → Flow emits again.
State ownership. Room owns persistent state. ViewModel owns transient screen state (draft text, selection, error message). WorkManager owns sync scheduling. No global mutable singleton holds note data.
| Component | Responsibility |
|---|---|
| NoteRepository | The only door to Room. Writes the note and its outbox row in one transaction, enqueues sync, and exposes Flow reads to ViewModels. |
| Room database (notes, pending_ops, sync_state) | Local persistence and the source of truth. notes stores the current state with a dirty flag and serverVersion. pending_ops is the outbox queue. sync_state holds the server's change token. |
| SyncWorker (CoroutineWorker) | Unique one-time work after each write, plus a periodic safety net. Drains the outbox in batches, applies server responses, merges conflicts, and pulls changes. Waits for a network connection. |
| SyncApi (Retrofit interface) | HTTP contract. push sends a batch of ops with their op IDs and base versions; pull fetches changes since a server-issued token. |
| ConflictResolver | A pure function that decides what to do when a local edit and the server copy disagree: server order wins, per-field merge, or keep both as a conflict copy. |
| NotesViewModel | Holds StateFlow<UiState> for the editor and the list header, and the cached PagingData flow for the list. Sync errors are fields in UiState that the screen clears after showing them. |
| Room PagingSource + Pager | A DAO method returning PagingSource<Int, NoteEntity> feeds the list page by page. The ViewModel maps entities to UI models and caches the result. |
Data model and API
@Entity(tableName = "notes", indices = [Index(value = ["deleted", "updatedAt"])])
data class NoteEntity(
@PrimaryKey val id: String, // UUID created on the device
val title: String,
val body: String,
val updatedAt: Long, // local time, for display and sorting only
val deleted: Boolean = false, // tombstone
val serverVersion: Long? = null, // null until the server first accepts the note
val dirty: Boolean = false // has unsynced local changes
)
@Entity(tableName = "pending_ops")
data class PendingOp(
@PrimaryKey val opId: String, // UUID created with the write; the idempotency key
val noteId: String,
val opType: String, // "UPSERT" or "DELETE"
val baseVersion: Long?, // server version this edit was based on
val createdAt: Long,
val attempts: Int = 0
)
@Entity(tableName = "sync_state")
data class SyncState(
@PrimaryKey val id: Int = 0,
val changeToken: String? // issued by the server, never a device timestamp
)
data class NoteDto(val id: String, val title: String, val body: String, val deleted: Boolean, val version: Long)
data class OpDto(val opId: String, val noteId: String, val type: String, val baseVersion: Long?, val title: String?, val body: String?)
data class PushRequest(val ops: List<OpDto>)
data class AppliedOp(val opId: String, val noteId: String, val version: Long)
data class ConflictDto(val opId: String, val serverNote: NoteDto)
data class PushResponse(val applied: List<AppliedOp>, val conflicts: List<ConflictDto>)
data class PullResponse(val notes: List<NoteDto>, val nextToken: String, val hasMore: Boolean)
interface SyncApi {
@POST("sync/push")
suspend fun push(@Body request: PushRequest): Response<PushResponse>
@GET("sync/changes")
suspend fun pull(@Query("since") token: String?, @Query("limit") limit: Int): Response<PullResponse>
}- The op payload (title and body) is read from the
notesrow at push time, so a note edited ten times offline sends its latest text. - The server assigns every version. The client only stores and sends back the version it last saw.
Deep dives
Outbox pattern and sync loop
Every local write is one Room transaction: update the notes row (set dirty = true) and insert a row into pending_ops. Use withTransaction or a @Transaction DAO method. If the app dies between two separate writes, the note is saved but never synced.
SyncWorker reads the outbox ordered by createdAt, sends a batch (say 50 ops) to SyncApi.push, and handles the answer. For each applied op it stores the new serverVersion and deletes the outbox row. When a note has no outbox rows left, its dirty flag is cleared. The worker loops until the outbox is empty, so edits made while it runs are also sent.
The pull side asks for "changes since token X", where the token comes from the server and is stored in sync_state. A device timestamp is not used, because clock differences can skip changes. For each pulled note:
- If the local row is not dirty, write the server copy, including its version.
- If the pulled version is not newer than the local
serverVersion, skip it. This is usually the client's own push coming back. - If the local row is dirty (has pending ops), do not overwrite it. Run the conflict resolver against it, the same way as a rejected push.
The pull path writes through its own DAO method that never sets dirty and never inserts outbox rows. If pulled data could create outbox rows, every pull would trigger a push, and the client would sync forever (the echo loop below).
WorkManager constraints, backoff, and idempotency
After every write the repository calls enqueueUniqueWork("note-sync", ExistingWorkPolicy.APPEND_OR_REPLACE, request). APPEND_OR_REPLACE makes sure a write made during a running sync gets its own run afterwards, and it does not inherit a failed chain the way plain APPEND does. KEEP also works if the worker drains until the outbox is empty. Never use REPLACE: every edit would cancel a running upload.
The request has setRequiredNetworkType(NetworkType.CONNECTED) and setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS). A separate enqueueUniquePeriodicWork request (every few hours, with ExistingPeriodicWorkPolicy.KEEP) pulls changes even when the user makes no edits. The periodic request can add setRequiresBatteryNotLow(true); the after-edit request should not, because users expect their edits to sync.
For transient errors (IOException, 5xx, 429) the worker returns Result.retry(), and WorkManager waits with exponential backoff. For a permanent error (a 4xx that is not a conflict) retrying never helps. Mark that note as failed, show it in the UI, and move on so one bad op does not block the queue. An attempts cap gives the same protection against an op that keeps failing.
Idempotency matters: the server must treat each op ID as an idempotency key. If the network drops after the server commits but before the response arrives, the client retries with the same op ID and the server returns the original result instead of applying it twice.
Do not assume the work runs on time. In Doze and App Standby, WorkManager defers work until a maintenance window. A worker also gets about 10 minutes per run before the system stops it, so a long drain should save progress after each batch. Sync again when the app comes to the foreground, so the user sees fresh data on return. The server can send an FCM message to prompt a pull from another device.
Paging 3 and UI state from Flow
The notes DAO has a method like @Query("SELECT * FROM notes WHERE deleted = 0 ORDER BY updatedAt DESC") fun pagingSource(): PagingSource<Int, NoteEntity>, and Room generates the PagingSource. The ViewModel wraps it in a Pager with a PagingConfig(pageSize = 30), maps entities to UI models, and calls cachedIn(viewModelScope) so rotation does not reload. The screen calls collectAsLazyPagingItems() and gives LazyColumn a stable key (the note ID). When the worker writes to notes, Room invalidates the PagingSource and the list updates by itself.
Keep PagingData out of the UiState data class. Expose it as its own Flow, next to a StateFlow<UiState> for everything else (sync status, error message, pending count). The editor keeps the current draft in the ViewModel, saved in SavedStateHandle for short text, and autosaves to Room after a short pause in typing. Room is the real safety net: a Bundle has a size limit, and a long note can be too big for saved state.
Collect the screen's StateFlow with collectAsStateWithLifecycle. Plain collectAsState stops when the composable leaves composition, but keeps collecting while the app sits in the background. Do not load every note into a List in the ViewModel either. Paging loads pages as the user scrolls. By default it keeps the pages it has loaded, so set maxSize in PagingConfig if users can scroll through very large lists.
Soft deletes, tombstones, and cleanup
A hard delete removes the row from notes. The outbox has nothing to send for it, other devices keep showing the note, and the next pull brings it back. Instead, a delete sets deleted = true and dirty = true. This is a tombstone. The outbox records a DELETE op with the note ID and base version. The server marks the note deleted and sends the tombstone to other devices on their next pull.
The list query filters WHERE deleted = 0, so the user sees the note disappear immediately. The tombstone row stays in Room until the server has accepted the delete (no pending ops left for that note). After that, a periodic cleanup can purge it, for example tombstones older than 30 days. The server keeps its own tombstones long enough for devices that were offline to learn about the delete.
Conflict on delete: if the user deletes a note locally but the server has a newer edit, someone has to decide. A simple rule is that delete wins (the user explicitly chose to remove it). A safer rule for notes is that the edit wins and the note comes back, because losing text is worse than a note reappearing. Some apps ask the user: "This note was edited on another device. Keep the edit or delete it?" Keep the rule in one pure function, so changing it later is a small, tested change.
Trade-offs
| Decision | Options | What to pick and why |
|---|---|---|
| Conflict resolution strategy | Last-write-wins, per-field merge (title from one side, body from the other), server version or ETag check that rejects stale writes with 409 or 412. | Send the base version with every push and let the server reject stale writes. Then merge per field against the base, and keep a conflict copy when both sides changed the same field. Last-write-wins is acceptable for some single-user apps, but it must use the server's order, never device clocks. All three options need server support, so agree on the contract with the backend team early. |
| Sync trigger mechanism | WorkManager one-time work after each write plus periodic work, a foreground service that syncs continuously, a ConnectivityManager network callback that starts a sync. | WorkManager with a network constraint. It survives process death and reboots, waits for the network itself, and handles backoff. A foreground service costs battery, shows a permanent notification, and has strict start limits on newer Android versions. A network callback only works while the process is alive, so it misses changes after the app is killed. |
| Local storage: Room vs DataStore vs separate cache | Room as the single source of truth, a separate in-memory cache plus Room, DataStore for small key-value state. | Room as the single source of truth for notes. A separate cache creates two sources of truth and sync bugs. DataStore is fine for preferences (theme, sync settings) but not for a large set of records you query and page. |
| List rendering: Paging 3 vs manual pagination vs loading all rows | Paging 3 with a Room PagingSource, manual LIMIT/OFFSET queries, loading all notes into a List in the ViewModel. | Paging 3. It loads pages on demand, prefetches, reloads when the table changes, and plugs into LazyColumn with collectAsLazyPagingItems. Loading all rows wastes memory and slows the first frame on large accounts. Manual paging means rebuilding what Paging already does. |
| Outbox granularity: per-op rows vs a single JSON blob per note | One pending_ops row per change (create, update, delete), or a single JSON column on the notes row holding a diff. | Per-op rows. They keep the order of operations, handle deletes cleanly, carry their own idempotency key, and are easy to inspect in a debugger. A JSON blob is harder to partially apply and harder to reason about in conflict resolution. |
What breaks in production
- After a release, server traffic from the app jumped far above normal and some users reported battery drain.
- The pull path saved server copies through the same
save()method the editor used. That method marked the note dirty and added an outbox row. - So every pull created new pushes, every push changed versions, and the next run pulled them again. The unique sync work was re-enqueued after each run and never went idle.
- Give the pull path its own DAO method that writes the server copy with its version, clears
dirty, and never touches the outbox. Only user actions create outbox rows. - Skip pulled notes whose version is not newer than the local
serverVersion, so the client's own accepted push does not count as a remote change. - Add a test that runs push and pull against a fake server twice and asserts the outbox is empty and no further requests are sent.
- Track requests per active user and outbox depth in production, with an alert, so a loop shows up within hours instead of in reviews.
- Users reported that long notes disappeared after they switched to another app for a while and came back.
- The editor held the draft only in a Compose
remembervalue.remembersurvives recomposition, but not configuration changes or process death. The system had killed the app in the background. - No autosave to Room existed; the draft was written only on explicit save.
- Move the draft into the
ViewModeland keep a short copy inSavedStateHandle, which is restored after the system kills the process. - Add a debounced autosave: after about a second without typing, write the draft to Room. Coalesce outbox rows so a burst of autosaves for one note sends only its latest text.
- On reopen, the editor loads the note from Room, so even a draft too large for saved state is safe.
- Test it with "Don't keep activities" and by killing the app process from Android Studio while the editor is in the background.
Common mistakes in this round
- Keeping a separate in-memory cache alongside Room. Two sources of truth means the cache and Room can disagree after a sync pull. The UI shows stale data until the cache is manually refreshed, and bugs are hard to reproduce in tests.
- Calling the sync API from the UI, for example inside a LaunchedEffect. The call is cancelled when the user leaves the screen or the process dies, and nothing retries it. Writes go to Room and the outbox; WorkManager does the network part. (Retrofit
suspendcalls are already main-safe, so the problem is not the thread, it is the missing guarantee.) - No backoff or attempt cap on sync retries. A transient 503 from the server triggers immediate retries. Without exponential backoff the client hammers the server, and without an attempt cap a permanently bad op blocks the entire outbox.
- Hard-deleting rows from Room instead of setting a tombstone flag. The server never learns the note was deleted. Other devices keep showing it, and the next pull brings it back.
- Resolving conflicts with device clocks. Comparing
updatedAtfrom two phones picks the wrong winner when one clock is off. Send the base version and let the server detect stale writes. - Collecting flows in the background. Using
collectAsStatekeeps collecting while the app is in the background. UsecollectAsStateWithLifecyclefor state, andcollectAsLazyPagingItemswithcachedInfor the paged list. - Loading all notes into a List in the ViewModel for the list screen. On an account with 50,000 notes this allocates a large list, causes GC pressure, and delays the first frame. Paging 3 loads pages on demand.
Follow-up questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How does the app behave when the user is offline for three days and then reconnects?”
“What happens if two devices edit the same note at the same time?”
“How do you test the sync and conflict-resolution logic?”
“How do you keep the notes list fast when the user has 50,000 notes?”
Self-review checklist
- Room is the single source of truth; no parallel in-memory cache for notes.
- Writes go to Room and the outbox in one transaction; the UI updates before any network call.
- WorkManager handles sync with unique work (
APPEND_OR_REPLACE), a network constraint, exponential backoff, and a periodic safety net. - The server assigns versions; pushes send the base version, and pulls use a server change token.
- Pulls never overwrite notes with pending edits and never create outbox rows.
- Conflict resolution is explicit (server order, per-field merge, or conflict copy) and lives in one tested function.
- Deletes are soft (tombstone flag), not hard row removal, so the server and other devices learn about the delete.
- The notes list uses Paging 3 with
cachedInandcollectAsLazyPagingItems; screen state usescollectAsStateWithLifecycle. - The editor draft survives process death via the ViewModel's
SavedStateHandleplus a debounced autosave to Room. - The sync API is idempotent per op ID, so retries do not double-apply changes.