Skip to content
Commitwise
Menu
Android Development

Gradle and modularization

Split an Android app into feature and core modules, choose implementation or api for each dependency, keep versions in a version catalog and build logic in convention plugins, and make Gradle builds fast with the configuration cache, KSP and a dependency graph shaped for incremental builds.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

The shop app is one :app module with 200,000 lines of Kotlin. A one-line change in a view model triggers a two-minute build. Twelve module-level build.gradle.kts files each say compileSdk = 35 and pin their own Retrofit version (three different ones). The cart team and the product team both edit the same package, and every merge is a conflict.

Modularization on Android means splitting the app into Gradle modules with clear dependencies: :feature:cart, :core:network, :core:designsystem. Together with a few Gradle habits (a version catalog, convention plugins, the right dependency configurations), it gives faster incremental builds, clearer ownership and code that can be tested on its own. This lesson covers both the module graph and the Gradle setup that keeps it maintainable.

New to some of these? Open what you need, or skip ahead.

Basics:What is Gradle?

Gradle is the build tool Android uses. It reads build scripts (build.gradle.kts, written in Kotlin), downloads libraries, compiles code and packages the app. settings.gradle.kts lists the project’s modules; each module has its own build.gradle.kts saying what kind of module it is and what it depends on.

Basics:What is a module?

A module is a part of the project that is compiled on its own, with its own folder, build file and dependencies. :app is a module; so is a library like :core:network. Code in one module can only use another module’s code if it declares a dependency on it. See moduleModuleA unit of code compiled on its own and imported by name, such as an app target, a framework or a Swift package target.Open in glossary →.

Part Not started

Splitting the app into modules

Imagine a shopping mall where every shop shares one big room. Moving one shelf disturbs everyone. Give each shop its own space, with shared corridors and a shared delivery entrance, and shops can change without bothering each other.

A modular Android app usually looks like this:

  • :app: small. It creates the app, sets up navigation and connects the features.
  • :feature:* modules: :feature:cart, :feature:product. Each owns its screens and view models.
  • :core:* modules: :core:designsystem (theme, buttons), :core:network, :core:database, :core:data (repositories), :core:model (plain data classes).

The rule: features use core modules, never each other. When the cart needs to open a product, it doesn’t import :feature:product; :app connects them through navigation.

In each module’s build file you list its dependencies with one of two words:

  • implementation: “I use this inside my module.” Modules that depend on me don’t see it.
  • api: “My public functions use these types, so whoever depends on me needs them too.”

Use implementation almost always.

The common graph (see Now in Android) is :app → :feature:* → :core:*, with :core:model (pure Kotlin data), :core:data (repositories), :core:network, :core:database, :core:designsystem and :core:testing. Feature-to-feature edges are forbidden; navigation is wired in :app from routes each feature exposes (a small :feature:x:api module with route types and entry functions when other features must reference them). Dependency configurations decide both visibility and ABI propagation: implementation keeps a dependency off consumers’ compile classpath, so a change in it doesn’t recompile them; api exposes it, which is correct only when its types appear in your public signatures (a repository returning Flow<User> from :core:model). Pure Kotlin/JVM modules (kotlin("jvm")) build faster than Android libraries and keep domain code free of Android. Hilt works across modules (@InstallIn modules are aggregated in the app), which requires :app to depend on every module contributing bindings, transitively.

// settings.gradle.kts
include(":app")
include(":core:model", ":core:network", ":core:data", ":core:designsystem")
include(":feature:cart", ":feature:product")
// feature/cart/build.gradle.kts
plugins {
    alias(libs.plugins.shop.android.feature)          // a convention plugin: see the next part
}

android {
    namespace = "com.example.shop.feature.cart"
}

dependencies {
    implementation(project(":core:data"))            // repositories: used inside, not exposed
    implementation(project(":core:designsystem"))
    implementation(libs.androidx.lifecycle.viewmodel.compose)
}
// core/data/build.gradle.kts
dependencies {
    api(project(":core:model"))                      // CartRepository returns Flow<Cart>: Cart is part of my API
    implementation(project(":core:network"))         // Retrofit stays hidden behind the repository
    implementation(project(":core:database"))
}
// app: the only place that knows both features
NavHost(navController, startDestination = ProductListRoute) {
    productGraph(onOpenCart = { navController.navigate(CartRoute) })
    cartGraph(onOpenProduct = { id -> navController.navigate(ProductRoute(id)) })
}
  • settings.gradle.kts lists every module; :feature:cart is the folder feature/cart.
  • :feature:cart uses repositories from :core:data with implementation: the cart’s code can call them, but modules depending on the cart don’t see :core:data through it.
  • :core:data uses api for :core:model, because its functions return Cart and Product. Anyone calling the repository needs those classes.
  • Navigation lives in :app: each feature exposes a cartGraph(...) with lambdas like onOpenProduct, and :app decides where they lead.

Predict the output

The app module depends on :feature:profile. :feature:profile declares implementation(project(":core:model")). Code in :app uses the User class from :core:model directly, without its own dependency on :core:model. What happens?

Practice: extract the design system

  1. Create the module: File → New → New Module → Android Library, named :core:designsystem, package com.example.shop.core.designsystem.
  2. Move the theme: Color.kt, Type.kt, Theme.kt and shared components like ShopButton go into the new module. Resources (colors, icons) move to its res/ folder.
  3. Fix visibility: Kotlin’s default is public, so the functions are already visible. Mark helpers you don’t want others to use internal.
  4. Add the dependency: every module that uses the theme adds implementation(project(":core:designsystem")).
  5. Build and run: the app looks the same, and a change in a feature module no longer rebuilds the design system.
Spot the bugTwo features that need each other

Tap the line with the bug.

// feature/cart/build.gradle.kts
dependencies {
    implementation(project(":core:data"))
    implementation(project(":feature:product"))   // to show ProductCard in the cart
}

// feature/product/build.gradle.kts
dependencies {
    implementation(project(":core:data"))
    implementation(project(":feature:cart"))      // for the "Add to cart" button state
}

Keeping the graph honest

  • Enforce rules in CI: a module-graph check (for example the module-graph-assert plugin, or a small script over settings.gradle.kts and build files) that fails on :feature → :feature edges.
  • Dependency drift: dependency-guard snapshots each module’s resolved dependencies so unexpected transitive changes show up in review.
  • Dynamic feature modules (Play Feature Delivery) invert the dependency (:dynamic depends on :app) and add install-time complexity; use them only for large optional features, not as a modularization strategy.
  • :app → :feature:* → :core:* (model, data, network, database, designsystem, testing). No feature → feature edges; :app wires navigation, or features expose :api route modules.
  • implementation by default (private, limits recompilation); api only for types in your public signatures.
  • Pure Kotlin/JVM modules for domain code: faster, Android-free.
  • Hilt aggregates @InstallIn modules in the app: :app must (transitively) depend on all of them.
  • Enforce the graph in CI (module-graph assertions, dependency-guard); dynamic feature modules only for large optional features.

Check this part

  1. The cart needs a product card UI that the product feature also uses. Where should it live?

  2. What does implementation(project(":core:network")) mean for modules that depend on yours?

  3. When is api the right configuration?

  4. Why does api(libs.retrofit) in :core:network slow builds?

Use three layers: a thin :app module, :feature:* modules for screens, and :core:* modules (designsystem, data, network, database, model). Features depend on core modules, never on each other; :app wires navigation. Use implementation for dependencies that stay internal and api only for types that appear in your module's public API, because api leaks dependencies and widens recompilation. Hilt works across modules as long as :app depends on them.

Part Not started

Version catalogs, convention plugins and fast builds

With many modules, two kinds of repetition creep in:

  • Versions: every module writes "com.squareup.retrofit2:retrofit:2.11.0", and sooner or later two modules use different versions.
  • Configuration: every module repeats compileSdk = 35, minSdk = 26, the Kotlin and Compose setup.

Gradle has an answer for each:

And a few switches make builds faster for everyone: the configuration cache, the build cache, and KSP instead of the older kapt for annotation processing (Room, Hilt).

The version catalog (libs.versions.toml) centralizes coordinates, versions, bundles and plugin aliases with type-safe accessors; pair it with Renovate or Dependabot. Convention plugins in an included build (build-logic, via includeBuild("build-logic") in pluginManagement) replace subprojects {}/allprojects {} and buildSrc (whose changes invalidate the whole build): shop.android.library, shop.android.feature, shop.jvm.library, shop.android.compose. Speed: enable the configuration cache (org.gradle.configuration-cache=true) and keep configuration side-effect free (no exec, file reads or System.getenv at configuration time without providers); the build cache (local, plus remote in CI) with parallel execution; KSP instead of kapt (kapt generates Java stubs and is much slower; Room, Hilt and Moshi support KSP); non-transitive R classes (default since AGP 8) so resource changes don’t recompile dependents; avoid api; limit what :app does. Diagnose with Android Studio’s Build Analyzer and --scan build scans, and watch for tasks that are never up to date.

// build-logic/convention/src/main/kotlin/AndroidFeatureConventionPlugin.kt
class AndroidFeatureConventionPlugin : Plugin<Project> {
    override fun apply(target: Project) = with(target) {
        with(pluginManager) {
            apply("com.android.library")
            apply("org.jetbrains.kotlin.android")
            apply("org.jetbrains.kotlin.plugin.compose")
            apply("com.google.devtools.ksp")
            apply("com.google.dagger.hilt.android")
        }
        extensions.configure<LibraryExtension> {
            compileSdk = 36
            defaultConfig.minSdk = 26
            buildFeatures.compose = true
        }
        val libs = extensions.getByType<VersionCatalogsExtension>().named("libs")
        dependencies {
            add("implementation", project(":core:designsystem"))
            add("implementation", libs.findLibrary("hilt.android").get())
            add("ksp", libs.findLibrary("hilt.compiler").get())          // KSP, not kapt
        }
    }
}
# gradle/libs.versions.toml
[versions]
agp = "8.13.0"
kotlin = "2.2.20"
ksp = "2.2.20-2.0.3"
hilt = "2.57.1"
retrofit = "3.0.0"

[libraries]
retrofit = { module = "com.squareup.retrofit2:retrofit", version.ref = "retrofit" }
hilt-android = { module = "com.google.dagger:hilt-android", version.ref = "hilt" }
hilt-compiler = { module = "com.google.dagger:hilt-compiler", version.ref = "hilt" }
# Used by the build-logic build, not by app modules
android-gradlePlugin = { module = "com.android.tools.build:gradle", version.ref = "agp" }

[plugins]
android-library = { id = "com.android.library", version.ref = "agp" }
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
hilt = { id = "com.google.dagger.hilt.android", version.ref = "hilt" }
shop-android-feature = { id = "shop.android.feature" }        # our convention plugin
# gradle.properties
org.gradle.configuration-cache=true
org.gradle.caching=true
org.gradle.parallel=true
org.gradle.jvmargs=-Xmx4g -XX:+UseParallelGC
  • [versions] holds each version once; [libraries] and [plugins] refer to them. Updating Retrofit is now a one-line change.
  • AndroidFeatureConventionPlugin applies everything a feature module needs: the Android and Kotlin plugins, Compose, Hilt with KSP, the SDK levels and the design system. A feature’s own build file only adds its namespace and its specific dependencies.
  • gradle.properties turns on the configuration cache (Gradle remembers how the build was set up), the build cache (reuses outputs of tasks that already ran with the same inputs) and parallel module builds.

Production puzzles

Predict the output

A convention plugin sets versionName from the current git commit: val sha = Runtime.getRuntime().exec("git rev-parse --short HEAD").inputStream.reader().readText().trim(). The configuration cache is on. What happens?

Spot the bugWhy does everything rebuild?

Tap the line with the bug.

// core/network/build.gradle.kts
dependencies {
    api(libs.retrofit)
    api(libs.okhttp)
    api(libs.kotlinx.serialization.json)
    api(project(":core:model"))
}

Exercisehard

Modularize a 200k-line app

One :app module, 200,000 lines, 3 teams (Shopping, Account, Platform), a 2-minute incremental build, kapt for Room and Hilt. Plan the first quarter of work and how you’ll prove it helped.

›

Pick the steps that pay off before any module is extracted, then the order of extraction.

SolutionTry it yourself first
  1. Baseline: incremental build time for a typical change (a view model edit), clean build, CI time, measured with build scans.
  2. Quick wins first: move to KSP for Room and Hilt, enable the configuration and build caches, add a version catalog and convention plugins. These help immediately and make module creation cheap.
  3. Extract core modules: :core:model (pure Kotlin), :core:designsystem, :core:network, :core:database, :core:data. Mostly mechanical moves with internal cleanups.
  4. Features by team: :feature:catalog, :feature:cart (Shopping), :feature:account (Account), with navigation through :app. Ownership goes into CODEOWNERS.
  5. Guardrails: a CI check forbidding feature → feature edges, implementation by default in convention plugins, and a remote build cache for CI and developers.
  6. Prove it: compare the same change’s incremental build time and CI duration after each step; expect incremental builds to improve most.
Exerciseeasy

Move versions to a catalog

Three modules declare implementation("com.squareup.retrofit2:retrofit:2.9.0"), implementation("com.squareup.retrofit2:retrofit:2.11.0") and implementation("com.squareup.retrofit2:converter-kotlinx-serialization:2.11.0"). Write the catalog entries and the new dependency lines.

›

One version entry can be shared by both Retrofit artifacts.

SolutionTry it yourself first
// in each module
implementation(libs.retrofit)
implementation(libs.retrofit.kotlinx.serialization)
[versions]
retrofit = "2.11.0"

[libraries]
retrofit = { module = "com.squareup.retrofit2:retrofit", version.ref = "retrofit" }
retrofit-kotlinx-serialization = { module = "com.squareup.retrofit2:converter-kotlinx-serialization", version.ref = "retrofit" }

All modules now use the same version, and dashes in catalog names become dots in Kotlin (retrofit-kotlinx-serialization → libs.retrofit.kotlinx.serialization).

  • libs.versions.toml for coordinates, versions, bundles, plugin aliases; Renovate or Dependabot on top.
  • Convention plugins in an included build-logic build, not buildSrc (whole-build invalidation) or subprojects {}.
  • Configuration cache: no side effects at configuration time; use providers.exec/providers.environmentVariable. Build cache (remote in CI), parallel.
  • KSP over kapt; non-transitive R classes; implementation over api.
  • Diagnose with Build Analyzer and build scans; track incremental build time for a typical change.

Check this part

  1. Where should library versions live in a multi-module project?

  2. What does a convention plugin replace?

  3. Why prefer an included build-logic build over buildSrc?

  4. What breaks the configuration cache?

Keep versions in gradle/libs.versions.toml and shared build configuration in convention plugins (an included build-logic build), so module build files stay a few lines long. Speed builds up with the configuration cache, the build cache and parallel execution, KSP instead of kapt, non-transitive R classes, and nothing expensive at configuration time. Measure with Build Analyzer and build scans.

Key takeaways

  • Split the app into :app, :feature:* and :core:* modules; features never import each other.
  • Use implementation for dependencies; api only when your public functions use their types.
  • Keep versions in a version catalog and shared setup in convention plugins.
  • Turn on the configuration and build caches, and use KSP instead of kapt.
  • Shape the graph for ownership and recompilation: thin app, wide graph, private dependencies.
  • Enforce module rules in CI; they erode quickly otherwise.
  • Keep configuration side-effect free and build logic in an included build.
  • Measure build times before and after, on the changes developers actually make.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.