Modular offline-first app

Build a multi-module offline-first Android app with Room, WorkManager sync, Hilt, Gradle convention plugins, a version catalog, CI and a baseline profile. About 40 hours.

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-logic and a libs.versions.toml version 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:testing module
  • 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 layerResponsibility
appApplication with @HiltAndroidApp, HiltWorkerFactory setup for WorkManager, the NavHost, and the baseline profile consumer. Depends on the feature and core modules it wires together.
feature:notesCompose screens, NotesViewModel and the notes navigation destinations. Depends on core:data and core:model, never on another feature.
core:modelPlain Kotlin types such as Note. No Android dependencies, so it builds fast and is easy to test.
core:databaseRoom entities (NoteEntity, PendingOpEntity, SyncStateEntity), NoteDao, the database class, exported schemas and migrations, and a Hilt module that provides them.
core:networkRetrofit SyncApi, @Serializable DTOs, the OkHttpClient, and a Hilt module that provides them.
core:dataNoteRepository interface and OfflineFirstNoteRepository, SyncWorker, mapping between entities, DTOs and models, and the @Binds Hilt module.
core:testingFakeNoteRepository, 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.

  1. Add the seven modules to settings.gradle.kts: :app, :feature:notes, :core:model, :core:database, :core:network, :core:data, :core:testing.
  2. Add gradle/libs.versions.toml with [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.
  3. Create an included build in build-logic/ and add includeBuild("build-logic") inside pluginManagement in the root settings.gradle.kts. In build-logic/settings.gradle.kts, point a libs catalog at ../gradle/libs.versions.toml.
  4. 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 with gradlePlugin and add their IDs to the catalog's [plugins] section. Inside plugin code, read the catalog with VersionCatalogsExtension, because the type-safe libs. accessors only exist in build scripts.
  5. Apply the plugins in each module with alias(libs.plugins...). Declare module dependencies with implementation(project(...)), and use api only when a module's public signatures expose another module's types (for example :core:data exposing Note from :core:model).
  6. 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.

  1. Create NoteEntity with id (a UUID created on the device), title, body, updatedAt (local time, for sorting and display only), serverVersion: Long?, deleted (tombstone) and dirty.
  2. Create PendingOpEntity (the outbox) with opId (a UUID, used as the idempotency key), noteId, type (UPSERT or DELETE), baseVersion and createdAt. Create SyncStateEntity with the server's change token.
  3. Write NoteDao as an abstract class. Add observeVisible(): Flow<List<NoteEntity>> (WHERE deleted = 0), oldestOps(limit), and a @Transaction method that writes the note and its outbox row together.
  4. Set the Room Gradle plugin's schemaDirectory and commit the exported schema. Then make a real change: add a pinned column with a default value, bump to version 2, and add an AutoMigration(from = 1, to = 2) or a manual Migration(1, 2).
  5. Write an instrumented MigrationTestHelper test that creates a version 1 database, inserts a row, migrates to 2, and checks the row survived with the default value.
  6. Provide the database and NoteDao from 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.

  1. Define @Serializable DTOs and a SyncApi interface with suspend fun push(@Body request: PushRequest): PushResponse and suspend 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.
  2. Build one OkHttpClient with HttpLoggingInterceptor in debug builds only, and a Retrofit instance with the kotlinx.serialization converter.
  3. Provide OkHttpClient, Retrofit and SyncApi from a Hilt @Module in :core:network.
  4. Map failures in one place, not in an interceptor: a suspend Retrofit call throws IOException for network problems and HttpException for non-2xx codes. Classify them as retryable (IOException, 5xx, 429) or permanent (other 4xx). If you wrap calls in a helper, rethrow CancellationException.
  5. Write MockWebServer tests: a 503 is classified as retryable, a 400 as permanent, and a valid body parses into PushResponse.

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.

  1. Define the NoteRepository interface (observeNotes(): Flow<List<Note>>, save(note), delete(id)) and OfflineFirstNoteRepository. Bind it with @Binds in a @Module @InstallIn(SingletonComponent::class) in :core:data.
  2. save and delete write the note and an outbox row in one transaction, then enqueue one-time unique work with ExistingWorkPolicy.APPEND_OR_REPLACE, so an edit made during a running sync gets its own run. A delete sets deleted = true (a tombstone) instead of removing the row.
  3. Write SyncWorker as a @HiltWorker CoroutineWorker. 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.
  4. 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.
  5. 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 dirty and never creates outbox rows, so the client does not echo the server's changes back.
  6. Give the request setRequiredNetworkType(NetworkType.CONNECTED) and setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS). Return Result.retry() for retryable errors and give up after a capped runAttemptCount. Add a periodic unique request (every few hours) as a safety net for pulls.
  7. In :app, make the Application implement Configuration.Provider with the injected HiltWorkerFactory, and remove the default WorkManagerInitializer from the manifest. Without this, WorkManager cannot create the @HiltWorker.
  8. Test the worker with TestListenableWorkerBuilder and a fake SyncApi from :core:testing: a conflict leaves the server copy in Room with the server's version and an empty outbox, and an IOException returns Result.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.

  1. Write NotesViewModel with @HiltViewModel. Combine repository.observeNotes() with sync status and expose StateFlow<NotesUiState> using stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), NotesUiState()).
  2. For sync status, expose a Flow from :core:data built on WorkManager.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.
  3. Build the list and editor screens. Collect state with collectAsStateWithLifecycle, give LazyColumn items a stable key (the note ID), and get the ViewModel with hiltViewModel() inside the destination.
  4. Expose the feature's destinations from the feature module as a NavGraphBuilder extension with type-safe @Serializable routes, and call it from the NavHost in :app.
  5. Write NotesViewModel unit tests with FakeNoteRepository and MainDispatcherRule (a StandardTestDispatcher) from :core:testing.
  6. Write a @HiltAndroidTest UI test in :app with a custom test runner that uses HiltTestApplication. 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.

  1. Create a GitHub Actions workflow that uses actions/checkout, actions/setup-java (distribution temurin, the JDK your AGP version needs) and gradle/actions/setup-gradle, which caches Gradle files for you. Run ./gradlew lint testDebugUnitTest assembleRelease and the module graph check. Separate jobs are fine if you prefer.
  2. Add a :baselineprofile module with Android Studio's Baseline Profile Generator template. It applies the androidx.baselineprofile plugin, adds the baselineProfile(project(":baselineprofile")) dependency to :app, and adds profileinstaller. Write the generator with BaselineProfileRule.collect() covering startup, opening a note and scrolling the list.
  3. Run ./gradlew :app:generateBaselineProfile on 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.
  4. Turn on isMinifyEnabled and isShrinkResources for 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.
  5. Optional: add Dependency Guard (com.dropbox.dependency-guard) to :app, baseline releaseRuntimeClasspath, and run dependencyGuard in CI so unexpected dependency changes show up in review.
  6. 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)
        }
    }
}
  • saveLocal is a @Transaction method on an abstract DAO class, so a crash can never leave a saved note without its outbox row.
  • APPEND_OR_REPLACE queues 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 plain APPEND does. REPLACE would 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.
  • @HiltWorker lets Hilt inject the DAO and API into the worker through assisted injection. It needs HiltWorkerFactory in the app's WorkManager configuration.

Pitfalls

  • Two modules depending on each other: core:data imports a callback type from feature:notes. :feature:notes already depends on :core:data, so Gradle stops with a circular dependency error. The quick fixes (moving code into :app or 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 an AutoMigration or Migration for each version, and test it with MigrationTestHelper.
  • 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.CONNECTED for 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 @AssistedInject constructor, so the worker fails to start and nothing syncs. Fix: implement Configuration.Provider with the injected HiltWorkerFactory and remove the default WorkManagerInitializer from 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.toml through 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 Flow from the repository and call stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ...) in the ViewModel.

Code review finding

Retried sync creates duplicate notes on the server
  • The first version of the worker called POST /notes for 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.
The fix
  • 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 through NoteRepository in :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 Room PagingSource, so large accounts load page by page.
  • Add a Macrobenchmark that measures cold start with CompilationMode.None() and with CompilationMode.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 WorkManagerTestInitHelper that 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:testing provides the fakes and MainDispatcherRule, and the ViewModel and worker tests use them.
  • CI runs lint, unit tests and assembleRelease and is green on a clean checkout.
  • The release APK contains a baseline profile generated with BaselineProfileRule and the androidx.baselineprofile plugin.

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 updatedAt from 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 @HiltWorker so Hilt injects the DAO and API into the worker through assisted injection instead of a hand-written WorkerFactory. 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-logic build 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 that build-logic is a small codebase of its own that needs an owner, and a graph check in CI keeps the module rules from eroding.