Modular offline-first app
What you will build
The finished app is a multi-module Android notes app that works fully offline and syncs in the background. Room is the single source of truth. Every edit is written to Room together with an outbox row, and a WorkManager worker pushes the outbox to a REST API when a network is available, then pulls changes from other devices. Conflicts are decided by versions the server assigns, never by device clocks. The build uses Gradle convention plugins in an included build-logic build, a version catalog, Hilt across modules, Jetpack Compose for the UI, and a CI workflow.
You need a backend you control. A few routes in any small server framework are enough: push a batch of ops, pull changes since a token. Google's public Now in Android sample is good inspiration for the module layout and build logic, but this project does not copy it and you do not need to match it.
This project shows an employer that you can structure a real codebase, not just a single-module demo. It covers module boundaries, offline-first data flow, conflict handling, testing with shared fakes, and CI. In an interview you can walk through the data flow from UI to Room to WorkManager to the server and back, with the trade-off at each step.
Skills you practise
- Multi-module Gradle with convention plugins in
build-logicand alibs.versions.tomlversion catalog - Module dependency rules: features depend on core modules, never on each other
- Room as the single source of truth, with an outbox table, tombstones and a tested migration
- WorkManager sync with unique work, a network constraint, exponential backoff and server-assigned versions
- Hilt across module boundaries, including
@HiltWorker - Shared test fakes and test rules in a
core:testingmodule - A CI pipeline for lint, unit tests and assemble, plus a baseline profile
Architecture
The app has seven Gradle modules, plus a :baselineprofile test module added in milestone 6. Dependencies point from :app toward the core modules. Feature modules depend on core modules and never on each other, and no module depends on :app.
:app is the shell: the Application class with @HiltAndroidApp, the WorkManager setup for Hilt, and the NavHost that wires feature destinations together. :feature:notes holds the Compose screens and NotesViewModel. It depends on :core:data for the NoteRepository interface and on :core:model for the Note type.
:core:model is a plain Kotlin (JVM) module with Note and other shared types. :core:database has the Room entities, DAOs, database and migrations. :core:network has the Retrofit API and DTOs. :core:data has the NoteRepository interface, its offline-first implementation, the SyncWorker, and the Hilt module that @Binds the implementation to the interface. :core:testing holds fakes and test rules that other modules add as test dependencies.
Data flow: the user edits a note. NotesViewModel calls NoteRepository.save(). In one Room transaction the repository updates the notes row (marked dirty) and inserts a pending_ops row, then enqueues unique sync work. Room's Flow re-emits and the UI updates before any network call. When a network is available, SyncWorker pushes the outbox in batches with each op's base version. The server applies ops it accepts, assigns new versions, and rejects stale ones with its current copy. The worker writes the results to Room, pulls other changes since a server-issued token, and Room emits again.
| Module or layer | Responsibility |
|---|---|
| app | Application with @HiltAndroidApp, HiltWorkerFactory setup for WorkManager, the NavHost, and the baseline profile consumer. Depends on the feature and core modules it wires together. |
| feature:notes | Compose screens, NotesViewModel and the notes navigation destinations. Depends on core:data and core:model, never on another feature. |
| core:model | Plain Kotlin types such as Note. No Android dependencies, so it builds fast and is easy to test. |
| core:database | Room entities (NoteEntity, PendingOpEntity, SyncStateEntity), NoteDao, the database class, exported schemas and migrations, and a Hilt module that provides them. |
| core:network | Retrofit SyncApi, @Serializable DTOs, the OkHttpClient, and a Hilt module that provides them. |
| core:data | NoteRepository interface and OfflineFirstNoteRepository, SyncWorker, mapping between entities, DTOs and models, and the @Binds Hilt module. |
| core:testing | FakeNoteRepository, a fake SyncApi, MainDispatcherRule, and Hilt test modules. Added with testImplementation or androidTestImplementation where needed. |
Milestones
1. Project skeleton and convention plugins
Create the module structure, a version catalog, and convention plugins so every module gets the same Kotlin, Android and Hilt setup.
- Add the seven modules to
settings.gradle.kts::app,:feature:notes,:core:model,:core:database,:core:network,:core:data,:core:testing. - Add
gradle/libs.versions.tomlwith[versions],[libraries]and[plugins]for AGP, Kotlin, KSP, Compose (through the Compose BOM), Room, WorkManager, Hilt, Retrofit, OkHttp and kotlinx.serialization. Use the current stable versions. - Create an included build in
build-logic/and addincludeBuild("build-logic")insidepluginManagementin the rootsettings.gradle.kts. Inbuild-logic/settings.gradle.kts, point alibscatalog at../gradle/libs.versions.toml. - Write binary convention plugins: Android application, Android library, Compose, Hilt (applies Hilt and KSP and adds the compiler), and JVM library for
:core:model. Register them withgradlePluginand add their IDs to the catalog's[plugins]section. Inside plugin code, read the catalog withVersionCatalogsExtension, because the type-safelibs.accessors only exist in build scripts. - Apply the plugins in each module with
alias(libs.plugins...). Declare module dependencies withimplementation(project(...)), and useapionly when a module's public signatures expose another module's types (for example:core:dataexposingNotefrom:core:model). - Add a module graph check. The Module Graph Assert plugin (
com.jraska.module.graph.assertion) can forbid edges with a regex rule; a small custom Gradle task that inspects project dependencies works too. Forbid feature to feature, core to feature, and anything to:app, and run its assert task in CI.
Done when: ./gradlew assembleDebug succeeds, module build files contain only plugin aliases, a namespace and dependencies, and the graph check fails if you temporarily add implementation(project(":feature:notes")) to :core:data.
Lessons: convention plugins and version catalogs, modularization strategies, api design between modules
2. Room database, outbox and migrations
Define the local schema in :core:database: notes with tombstones and server versions, an outbox table, and a sync token.
- Create
NoteEntitywithid(a UUID created on the device),title,body,updatedAt(local time, for sorting and display only),serverVersion: Long?,deleted(tombstone) anddirty. - Create
PendingOpEntity(the outbox) withopId(a UUID, used as the idempotency key),noteId,type(UPSERTorDELETE),baseVersionandcreatedAt. CreateSyncStateEntitywith the server's change token. - Write
NoteDaoas an abstract class. AddobserveVisible(): Flow<List<NoteEntity>>(WHERE deleted = 0),oldestOps(limit), and a@Transactionmethod that writes the note and its outbox row together. - Set the Room Gradle plugin's
schemaDirectoryand commit the exported schema. Then make a real change: add apinnedcolumn with a default value, bump to version 2, and add anAutoMigration(from = 1, to = 2)or a manualMigration(1, 2). - Write an instrumented
MigrationTestHelpertest that creates a version 1 database, inserts a row, migrates to 2, and checks the row survived with the default value. - Provide the database and
NoteDaofrom a Hilt@Module @InstallIn(SingletonComponent::class)in:core:database.
Done when: ./gradlew :core:database:connectedDebugAndroidTest passes, including the migration test, and a DAO test shows that saving a note always creates exactly one outbox row in the same transaction.
Lessons: room entities daos queries, room migrations, single source of truth
3. Network layer and error handling
Put Retrofit and OkHttp in :core:network so no other module builds HTTP requests itself.
- Define
@SerializableDTOs and aSyncApiinterface withsuspend fun push(@Body request: PushRequest): PushResponseandsuspend fun pull(@Query("since") token: String?, @Query("limit") limit: Int): PullResponse. A push carries op IDs and base versions; the response lists accepted ops with their new server versions and conflicts with the server's copy. - Build one
OkHttpClientwithHttpLoggingInterceptorin debug builds only, and a Retrofit instance with the kotlinx.serialization converter. - Provide
OkHttpClient,RetrofitandSyncApifrom a Hilt@Modulein:core:network. - Map failures in one place, not in an interceptor: a suspend Retrofit call throws
IOExceptionfor network problems andHttpExceptionfor non-2xx codes. Classify them as retryable (IOException, 5xx, 429) or permanent (other 4xx). If you wrap calls in a helper, rethrowCancellationException. - Write
MockWebServertests: a 503 is classified as retryable, a 400 as permanent, and a valid body parses intoPushResponse.
Done when: SyncApi is injectable through Hilt and the MockWebServer tests pass in ./gradlew :core:network:testDebugUnitTest.
Lessons: retrofit and okhttp, error handling and result types, serialization kotlinx vs moshi
4. Offline-first repository and sync worker
Implement NoteRepository in :core:data so Room is the single source of truth and WorkManager does all network work.
- Define the
NoteRepositoryinterface (observeNotes(): Flow<List<Note>>,save(note),delete(id)) andOfflineFirstNoteRepository. Bind it with@Bindsin a@Module @InstallIn(SingletonComponent::class)in:core:data. saveanddeletewrite the note and an outbox row in one transaction, then enqueue one-time unique work withExistingWorkPolicy.APPEND_OR_REPLACE, so an edit made during a running sync gets its own run. A delete setsdeleted = true(a tombstone) instead of removing the row.- Write
SyncWorkeras a@HiltWorkerCoroutineWorker. It pushes the outbox in batches of about 50 and commits each batch's results to Room before sending the next. Accepted ops are removed from the outbox and the note gets the server's version. Tombstones are purged only after the server accepts the delete. - Conflict policy: the server rejects an op whose base version is stale and returns its copy. The server copy wins and is written to Room. Write this rule as a pure function and document that a stale local edit is replaced.
- After pushing, pull changes since the stored token and save the new token from the server. Pulls write through a separate DAO method that never sets
dirtyand never creates outbox rows, so the client does not echo the server's changes back. - Give the request
setRequiredNetworkType(NetworkType.CONNECTED)andsetBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS). ReturnResult.retry()for retryable errors and give up after a cappedrunAttemptCount. Add a periodic unique request (every few hours) as a safety net for pulls. - In
:app, make theApplicationimplementConfiguration.Providerwith the injectedHiltWorkerFactory, and remove the defaultWorkManagerInitializerfrom the manifest. Without this, WorkManager cannot create the@HiltWorker. - Test the worker with
TestListenableWorkerBuilderand a fakeSyncApifrom:core:testing: a conflict leaves the server copy in Room with the server's version and an empty outbox, and anIOExceptionreturnsResult.retry()with the outbox untouched.
Done when: the worker tests pass, and on a device you can edit in airplane mode, turn the network back on, and see the outbox drain and the server hold the latest text.
Lessons: queued writes with workmanager, sync strategies and conflict resolution, design an offline first notes app
5. Feature module, navigation and Compose UI
Build :feature:notes so the UI reacts to Room and shows sync status.
- Write
NotesViewModelwith@HiltViewModel. Combinerepository.observeNotes()with sync status and exposeStateFlow<NotesUiState>usingstateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), NotesUiState()). - For sync status, expose a
Flowfrom:core:databuilt onWorkManager.getWorkInfosForUniqueWorkFlow("note-sync")plus the outbox row count, so the screen can show "Syncing" or "3 changes not synced". Model errors and one-off messages as fields in the UI state that the screen clears after showing them. - Build the list and editor screens. Collect state with
collectAsStateWithLifecycle, giveLazyColumnitems a stable key (the note ID), and get the ViewModel withhiltViewModel()inside the destination. - Expose the feature's destinations from the feature module as a
NavGraphBuilderextension with type-safe@Serializableroutes, and call it from theNavHostin:app. - Write
NotesViewModelunit tests withFakeNoteRepositoryandMainDispatcherRule(aStandardTestDispatcher) from:core:testing. - Write a
@HiltAndroidTestUI test in:appwith a custom test runner that usesHiltTestApplication. Replace the data bindings with fakes through@TestInstallIn, then type a note and assert it appears in the list.
Done when: ./gradlew :feature:notes:testDebugUnitTest and ./gradlew :app:connectedDebugAndroidTest pass, and the app shows a live-updating list with a sync status line.
Lessons: navigation across modules, viewmodel and ui state, viewmodel tests
6. CI, baseline profile and release build
Add a CI pipeline and a baseline profile, and make sure the minified release build works.
- Create a GitHub Actions workflow that uses
actions/checkout,actions/setup-java(distributiontemurin, the JDK your AGP version needs) andgradle/actions/setup-gradle, which caches Gradle files for you. Run./gradlew lint testDebugUnitTest assembleReleaseand the module graph check. Separate jobs are fine if you prefer. - Add a
:baselineprofilemodule with Android Studio's Baseline Profile Generator template. It applies theandroidx.baselineprofileplugin, adds thebaselineProfile(project(":baselineprofile"))dependency to:app, and addsprofileinstaller. Write the generator withBaselineProfileRule.collect()covering startup, opening a note and scrolling the list. - Run
./gradlew :app:generateBaselineProfileon a device or emulator and commit the generated rules. CI builds the release with the committed profile; it does not need a device for that. - Turn on
isMinifyEnabledandisShrinkResourcesfor release. R8 full mode is the default in current AGP versions. Room, WorkManager, Retrofit and kotlinx.serialization ship their own consumer keep rules, so add your own rules only for crashes you can reproduce in the release build. - Optional: add Dependency Guard (
com.dropbox.dependency-guard) to:app, baselinereleaseRuntimeClasspath, and rundependencyGuardin CI so unexpected dependency changes show up in review. - Turn on the Gradle build cache and configuration cache in
gradle.properties, and confirm the second CI run restores the cache and is faster.
Done when: CI is green on a clean checkout, the release APK contains assets/dexopt/baseline.prof (check with APK Analyzer), and the release build runs the edit, sync and pull flow without crashes.
Lessons: ci cd pipelines, app startup and baseline profiles, r8 shrinking and obfuscation
Key code
// :core:database
@Dao
abstract class NoteDao {
@Query("SELECT * FROM notes WHERE deleted = 0 ORDER BY updatedAt DESC")
abstract fun observeVisible(): Flow<List<NoteEntity>>
@Query("SELECT serverVersion FROM notes WHERE id = :id")
abstract suspend fun serverVersion(id: String): Long?
@Query("SELECT * FROM notes WHERE id = :id")
abstract suspend fun note(id: String): NoteEntity
@Query("SELECT * FROM pending_ops ORDER BY createdAt LIMIT :limit")
abstract suspend fun oldestOps(limit: Int): List<PendingOpEntity>
@Upsert
abstract suspend fun upsertNote(note: NoteEntity)
@Insert
abstract suspend fun insertOp(op: PendingOpEntity)
// The note and its outbox row are written together or not at all
@Transaction
open suspend fun saveLocal(note: NoteEntity, op: PendingOpEntity) {
upsertNote(note)
insertOp(op)
}
}
// :core:data
class OfflineFirstNoteRepository @Inject constructor(
private val noteDao: NoteDao,
private val workManager: WorkManager,
) : NoteRepository {
override fun observeNotes(): Flow<List<Note>> =
noteDao.observeVisible().map { rows -> rows.map { it.asModel() } }
override suspend fun save(note: Note) {
val base = noteDao.serverVersion(note.id)
noteDao.saveLocal(
note = note.asEntity(serverVersion = base, dirty = true),
op = PendingOpEntity(
opId = UUID.randomUUID().toString(),
noteId = note.id,
type = OpType.UPSERT,
baseVersion = base,
createdAt = System.currentTimeMillis(),
),
)
SyncWorker.enqueue(workManager)
}
override suspend fun delete(id: String) {
// Same shape: set deleted = true and add a DELETE op in one transaction
}
}
@HiltWorker
class SyncWorker @AssistedInject constructor(
@Assisted context: Context,
@Assisted params: WorkerParameters,
private val noteDao: NoteDao,
private val syncApi: SyncApi,
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
return try {
while (true) {
val ops = noteDao.oldestOps(limit = 50)
if (ops.isEmpty()) break
// Payload is read at push time, so ten offline edits send the latest text
val request = PushRequest(ops.map { op -> op.toDto(noteDao.note(op.noteId)) })
val response = syncApi.push(request)
// One transaction per batch: remove accepted ops, store server versions,
// write server copies for conflicts, purge tombstones the server accepted
noteDao.applyPushResult(response.asPushResult()) // mapped to a :core:database type
}
pullChanges() // since the stored server token; never creates outbox rows
Result.success()
} catch (e: IOException) {
retryOrFail()
} catch (e: HttpException) {
if (e.code() >= 500 || e.code() == 429) retryOrFail() else Result.failure()
}
}
private fun retryOrFail(): Result =
if (runAttemptCount < MAX_ATTEMPTS) Result.retry() else Result.failure()
companion object {
private const val MAX_ATTEMPTS = 5
fun enqueue(workManager: WorkManager) {
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)
}
}
}saveLocalis a@Transactionmethod on an abstract DAO class, so a crash can never leave a saved note without its outbox row.APPEND_OR_REPLACEqueues a new run after a running sync, so an edit made mid-sync is never dropped, and it does not inherit a failed chain the way plainAPPENDdoes.REPLACEwould cancel an upload in progress on every save.- Each batch is committed before the next one is sent. A worker run has about 10 minutes before the system stops it, and Doze can delay it, so progress must survive being stopped at any point.
- A permanent 4xx returns
Result.failure()here to keep the snippet short. In the full app, mark that op as failed and continue, so one bad op does not block the queue. @HiltWorkerlets Hilt inject the DAO and API into the worker through assisted injection. It needsHiltWorkerFactoryin the app's WorkManager configuration.
Pitfalls
- Two modules depending on each other: core:data imports a callback type from feature:notes.
:feature:notesalready depends on:core:data, so Gradle stops with a circular dependency error. The quick fixes (moving code into:appor copying the type) make the graph worse. Fix: move the shared interface into a core module that both can depend on, and let the graph check catch new feature edges in CI. - Bumping the Room version or changing an entity without a migration. The first query on an existing install throws
IllegalStateException, so every updated user crashes. Fix: export schemas, add anAutoMigrationorMigrationfor each version, and test it withMigrationTestHelper. - Using NetworkType.UNMETERED or setRequiresBatteryNotLow for after-edit sync. Edits then wait for Wi-Fi or a charged battery, and users on mobile data see "not synced" for hours. Fix: use
NetworkType.CONNECTEDfor the after-edit request. Stricter constraints suit the periodic safety-net request or large attachments. - A @HiltWorker without the Hilt WorkManager setup. WorkManager's default factory cannot call the
@AssistedInjectconstructor, so the worker fails to start and nothing syncs. Fix: implementConfiguration.Providerwith the injectedHiltWorkerFactoryand remove the defaultWorkManagerInitializerfrom the manifest. - Hardcoding a library version in one module's build file. The app resolves one version for its own classpath, but that module's own unit tests can resolve a different one, so tests pass against a version the app does not ship. Fix: take every version from
libs.versions.tomlthrough the convention plugins and module aliases. - Turning a Room Flow into a StateFlow with SharingStarted.Eagerly in a singleton repository. The subscription never ends, so every table change re-runs the query even when no screen is visible. Fix: return the cold
Flowfrom the repository and callstateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ...)in the ViewModel.
Code review finding
- The first version of the worker called
POST /notesfor each pending note, let the server create the ID, and marked the row synced after each response. - When the response was lost (a timeout after the server committed) or the worker was stopped between the server's commit and the local update, the row stayed pending.
- The retry posted the same note again, and the server created a second copy. Other devices pulled both.
- Create note IDs on the device (UUIDs) and give every outbox op its own
opId. The server treats the op ID as an idempotency key and returns the original result for a repeat, so a retry cannot apply an op twice. - Commit each batch's results to Room right after the response: remove accepted ops and store the server's version. Never hold a database transaction open across a network call.
- Keep exponential backoff and a cap on
runAttemptCount, and mark ops that fail permanently instead of retrying them forever. - Add a test with a fake server that saves an op and then throws
IOException, and assert that after the retry the server holds exactly one note.
Stretch goals
- Add a second feature module (
:feature:search) that reads throughNoteRepositoryin:core:data, with no dependency on:feature:notes, and search with a Room FTS table. - Replace the full-list
Flow<List<Note>>with Paging 3 and a RoomPagingSource, so large accounts load page by page. - Add a Macrobenchmark that measures cold start with
CompilationMode.None()and withCompilationMode.Partial(BaselineProfileMode.Require), and compare the two. - Instead of replacing a stale local edit, merge per field against the base version and save a "conflict copy" note when both sides changed the same field.
- Add a remote feature flag that can switch the periodic sync off without a new release.
- Write an instrumented test with
WorkManagerTestInitHelperthat checks the unique work policy and the network constraint.
Done checklist
- Seven modules build; features depend only on core modules, and the graph check fails CI if that rule is broken.
- Module build files use convention plugin aliases and catalog entries; no hardcoded versions.
- Every edit writes the note and its outbox row in one Room transaction, and the UI updates before any network call.
- Sync uses unique one-time work with
APPEND_OR_REPLACE,NetworkType.CONNECTED, exponential backoff and a capped attempt count, plus a periodic safety net. - Conflicts use server-assigned versions, never device clocks, and the rule lives in one tested function.
- Deletes are tombstones, purged only after the server accepts the delete.
- The Room migration from version 1 to 2 is tested with
MigrationTestHelper. :core:testingprovides the fakes andMainDispatcherRule, and the ViewModel and worker tests use them.- CI runs lint, unit tests and
assembleReleaseand is green on a clean checkout. - The release APK contains a baseline profile generated with
BaselineProfileRuleand theandroidx.baselineprofileplugin.
Talking about it in an interview
- I made Room the single source of truth instead of keeping a separate cache, so the UI only ever reads Room and the network only ever writes to Room. Every edit goes into an outbox table in the same transaction, so nothing is lost if the process dies before sync.
- Conflicts use versions the server assigns. Each push sends the version the edit was based on; if the server has moved on, it rejects the op and returns its copy, and the server copy wins. I avoided comparing
updatedAtfrom two phones because device clocks drift. The trade-off is that a stale local edit is replaced, so the next step would be a per-field merge or a conflict copy. - I used
@HiltWorkerso Hilt injects the DAO and API into the worker through assisted injection instead of a hand-writtenWorkerFactory. WorkManager still owns the worker's scheduling and lifecycle. The cost is Hilt setup in the app and a Hilt dependency in:core:data. - Convention plugins in an included
build-logicbuild keep the Android, Kotlin and Hilt setup in one place, and the version catalog makes a library bump a one-line change. The trade-off is thatbuild-logicis a small codebase of its own that needs an owner, and a graph check in CI keeps the module rules from eroding.