DEV Community

Cover image for Scalpel, Not Sledgehammer: Precise Keep Rules for Smaller, Faster Android Apps
Android Expert
Android Expert

Posted on Originally published at Medium

Scalpel, Not Sledgehammer: Precise Keep Rules for Smaller, Faster Android Apps

Almost every Android codebase carries one line that nobody wants to touch. It usually looks like -keep class com.yourapp.** { *; }, it was added at 2 a.m. to fix a release-only crash, and it has been quietly switching R8 off for large parts of the app ever since.

This post is about replacing that line with rules that say exactly what reflection needs and nothing more. It covers how to measure the damage, how to write conditional rules close to the code that needs them, and how to stop the problem from coming back in CI.

The numbers below come from an Android performance talk on type-safe keep rules and DEX optimization. Treat them as vendor-reported results, not as a promise for your app.

Why this is a runtime problem, not a build-size vanity metric

Memory on real devices is tight, and every class the runtime loads has a cost. A smaller, better-optimized DEX affects startup, jank, and ANRs, not just download size. Google Play is also raising the bar. From February 2027, apps with more than 10 MB of DEX code must reach at least 25% shrinking, optimization, and obfuscation on every upload (the floor for games is 50 MB of DEX). Play’s help page says that missing a requirement can affect an app’s visibility and publishing capability. Below the 10 MB floor the rule does not apply, and any shrinker counts, not just R8.

The payoff for tuning is measurable. According to the talk:

  • Adopting R8 yields an average 38% smaller DEX and a 16% drop in user-perceived ANRs.
  • Teams that tune their rules past 50% see a further 25% DEX reduction, 4% faster startup, and 17% fewer ANRs.
  • Grab reached 78% optimization, 79% shrinking, and 82% obfuscation with R8 full mode and refined rules. Combined with Baseline Profiles, that cut ANRs by 32% and startup latency by 35%.

impact-numbers

The three scores your rules are really editing

Every keep rule subtracts from three budgets at once.

three-metrics

A rule that keeps a class by name usually protects it from all three treatments together. That is why one lazy wildcard is so expensive: it does not cost you one optimization, it costs you every optimization for everything it matches.

Measure before you edit: the R8 configuration analyzer

Do not start by deleting rules. Start by finding out which rules are doing the damage. The R8 configuration analyzer produces an HTML report with three things worth your attention:

  • A keep-rule table with exact counts of classes, methods, and fields each rule retains. Sort by that count and your worst offenders sit at the top.
  • Subsumed rules, which are narrow rules fully eclipsed by a broader one. Deleting them changes nothing, but they show you which broad rule is the real culprit.
  • Unused rules, which match nothing and can be removed immediately.

It ships with AGP 9.3 and runs through a dedicated Gradle task, without a full release build:

./gradlew :app:analyzeReleaseR8Config
Enter fullscreen mode Exit fullscreen mode

The HTML report lands at app/build/reports/r8/r8-config-analyzer-release.html. A full assembleRelease also produces one, at build/outputs/mapping/release/configanalyzer.html. The standalone task additionally writes a protobuf (.pb) file next to it, which is what agent tooling reads. On older AGP versions you can get the analyzer by replacing the bundled R8 with version 9.3.7-dev or newer.

Failure mode: trusting the local number as the Play number

The analyzer evaluates rules before final DEX optimization and compilation. Its percentages will be close to the Play Console figures but not identical. If you set a hard target of “exactly 52%” locally and then miss it in Play, nothing is broken. Use the local report for direction and relative comparisons, and use Play-parity tooling (covered below) for gates.

Why reflection forces the wildcard

R8 works by static analysis. It can only keep what it can see being used. Reflection hides usage in three common ways:

  1. Dynamic instantiation of a class chosen at runtime.
  2. Optional classpath dependencies probed with Class.forName.
  3. Ad hoc serialization that reads or writes members by name.

Faced with an invisible call, the human reaction is to protect everything nearby. Here is a realistic example: a checkout screen that supports an optional wallet SDK, loaded only if the host app ships it.

sealed interface AuthResult {
    data class Approved(val token: String) : AuthResult
    data object Declined : AuthResult
}

interface WalletProvider {
    suspend fun authorize(amountMinor: Long): AuthResult
}

class WalletLoader {

    fun loadOrNull(className: String): WalletProvider? =
        runCatching {
            Class.forName(className)
                .getDeclaredConstructor()
                .newInstance() as WalletProvider
        }.getOrNull()
}
Enter fullscreen mode Exit fullscreen mode

This works in debug builds, provided the implementation has a public no-argument constructor. In release, R8 sees no direct reference to the implementation class, so it either strips it or renames it. runCatching swallows the resulting ClassNotFoundException or NoSuchMethodException, and loadOrNull quietly returns null. Nobody gets a crash. Customers just stop seeing the wallet button. That is the nastiest version of this bug, because the symptom is a conversion dip rather than a stack trace.

Failure mode: the 2 a.m. wildcard

-keep class com.shop.wallet.** { *; }
Enter fullscreen mode Exit fullscreen mode

This fixes the missing button, and it also freezes every class, method, and field in the package: no renaming, no removal, no inlining, and no merging at any call site that touches them. The cost does not appear as an error, only as a score that never recovers. The picture below shows the same reflective call under both rules. The grid is illustrative, not measured.

blast-radius

Failure mode: @Keep as false comfort

@Keep feels like the type-safe answer, but it has three weaknesses:

  • It is unconditional. The class is kept even if the code that needed it is deleted.
  • It cannot express “keep every subclass of this type” without annotating every implementation by hand.
  • It blocks whole-program optimization at every call site that touches the annotated element.

The talk goes further and notes that @Keep is discouraged, and effectively banned, in modern libraries. If a library you ship still depends on it, every consumer inherits the cost.

Failure mode: Kotlin shapes that reflection finds surprising

Kotlin generates structure that Java reflection code does not expect. Two examples that bite in release builds:

// Reached reflectively via the generated INSTANCE field
object DefaultWalletConfig : WalletConfig {
    override val timeoutMs: Long = 8_000
}

// Reflection on a sealed hierarchy sees every nested subclass,
// including ones nobody references directly
sealed interface WalletEvent {
    data class Authorized(val token: String) : WalletEvent
    data object Cancelled : WalletEvent
}
Enter fullscreen mode Exit fullscreen mode

A wildcard “fixes” both. A call-site rule fixes them properly, because it names exactly what the caller touches: the INSTANCE field in the first case, and the specific subclasses that are constructed in the second.

Type-safe rules at the call site with Jetpack Keep

Jetpack Keep moves the rule next to the reflection. You declare what a call site uses, and the build generates a conditional rule scoped to exactly that.

keep-workflow

The workflow:

  1. Add the androidx.annotation.keep:keep dependency and apply the androidx.annotation.keep Gradle plugin. Without the plugin, annotations compile but no keep rules are generated, and lint flags modules in that state.
  2. Lint flags reflective calls (Class.forName, getDeclaredConstructor, getDeclaredMethod, getDeclaredField) that have no matching annotation. Its quick fix, also runnable as ./gradlew lintFix, adds the right annotation with a placeholder such as className = TODO(). You replace the placeholder, so the code will not compile until you do.
  3. At build time, the plugin turns the annotations into precise rules limited to the constructors, fields, or methods that call site touches, and writes them to androidx.annotation.keep.rules.pro under the module's build directory.
  4. The output is standard consumer ProGuard syntax, so it works with older R8 versions, AARs, and external consumers. The tooling needs AGP 8.7 or newer.
// build.gradle.kts (version catalog aliases, as in the official setup)
plugins {
    alias(libs.plugins.androidx.annotation.keep)
}

dependencies {
    implementation(libs.androidx.annotation.keep)
}
Enter fullscreen mode Exit fullscreen mode

Here are two versions of the loader. The first targets a class that is part of your own code, so the compiler can check the reference and IDE renames keep it up to date. Use classConstant whenever the class is available at compile time:

import androidx.annotation.keep.UsesReflectionToConstruct

class BuiltInWallet : WalletProvider {
    override suspend fun authorize(amountMinor: Long): AuthResult =
        AuthResult.Approved(token = "demo")
}

class WalletLoader {

    @UsesReflectionToConstruct(classConstant = BuiltInWallet::class, parameterTypes = [])
    fun createBuiltIn(): WalletProvider =
        BuiltInWallet::class.java.getDeclaredConstructor().newInstance()
}
Enter fullscreen mode Exit fullscreen mode

The second targets an optional SDK class that is not on your compile classpath, so a name is the only option. Use className there. The two parameters are mutually exclusive:

class OptionalWalletLoader {

    @UsesReflectionToConstruct(
        className = "com.vendor.wallet.VendorWalletProvider",
        parameterTypes = [],
    )
    fun createVendorOrNull(): WalletProvider? =
        runCatching {
            Class.forName("com.vendor.wallet.VendorWalletProvider")
                .getDeclaredConstructor()
                .newInstance() as WalletProvider
        }.onFailure { error ->
            // Log in release too, so a missing class is visible.
            android.util.Log.w("Wallet", "Vendor provider unavailable", error)
        }.getOrNull()
}
Enter fullscreen mode Exit fullscreen mode

Let the quick fix generate the annotation skeleton, then review the diff. Parameter names are best confirmed against the androidx.annotation.keep reference for the version you use, as the API is still evolving.

Two design wins fall out of this:

  • The rule lives and dies with the code. Delete WalletLoader and the rule disappears with it, which fixes the "unused rules" problem at its source.
  • The conditional rule applies only if the call site survives shrinking, so dead code does not keep its dependencies alive.

Failure mode: a string no tool can read

If the class name arrives from remote config or user input, no annotation can describe it. The call site is genuinely dynamic. Your options are to constrain the input to a closed set you can enumerate with types, or to accept a narrowly scoped manual rule. Do not reach for a package wildcard because “it could be anything”.

If you ship a library, you ship its rules to everyone

Consumer rules travel with your AAR into every app that depends on it. A sloppy -keep in a library is a tax on every one of those apps. The Android CLI can audit this:

  • It flags unbounded consumer rules, high keep ratios, and rules that reference nothing in the library.
  • It measures the delta between standalone D8 and R8 builds. A well-behaved library should shrink to near zero bytes when nothing uses it.

That last check is a good smoke test: if an unused library still survives R8 at meaningful size, one of its rules is holding it in place.

Stop the regression: a gate in CI

Tuned rules rot. Someone adds a wildcard on a Friday, and the score slips two points without anyone noticing. The fix is to make the scores a build failure.

ci-gate

android analyze evaluates your bundle with the same logic and thresholds Google Play applies, and it can emit JSON for automation. The gate itself can stay tiny. The parsing step depends on the report you get from your toolchain version, so I leave it abstract and show only the comparison:

data class Scores(val shrinking: Double, val optimization: Double, val obfuscation: Double)

sealed interface GateResult {
    data object Pass : GateResult
    data class Fail(val regressions: List<String>) : GateResult
}

// Scores and tolerance are percentage points (78.0 means 78%), not ratios.
fun evaluateGate(current: Scores, baseline: Scores, tolerancePoints: Double = 0.5): GateResult {
    val regressions = buildList {
        if (current.shrinking < baseline.shrinking - tolerancePoints) add("shrinking")
        if (current.optimization < baseline.optimization - tolerancePoints) add("optimization")
        if (current.obfuscation < baseline.obfuscation - tolerancePoints) add("obfuscation")
    }
    return if (regressions.isEmpty()) GateResult.Pass else GateResult.Fail(regressions)
}
Enter fullscreen mode Exit fullscreen mode

Failure mode: a gate nobody can pass

If the baseline is set once and never moves, the first legitimate trade-off blocks every pull request, and the team learns to bypass the check. Store the baseline in version control, update it deliberately in the same pull request that justifies the change, and keep a small tolerance for noise.

A rollout order that works

  1. Measure. Generate the analyzer report and note your three scores.
  2. Delete the free wins. Remove unused rules, and remove subsumed rules after confirming the broad rule above them is intentional.
  3. Attack the biggest keep counts. Take the top rules by retained members and trace each back to the reflection that caused it.
  4. Convert call sites. Run the lint quick fix, fill in each placeholder, and delete the wildcard each annotation replaces.
  5. Test the release build, not debug. Exercise every reflective path in a minified build, and make sure silent fallbacks like runCatching { ... }.getOrNull() are logged in release so a missing class is visible.
  6. Lock it in. Add the CI gate and audit any libraries you publish.

AGP keeps improving the surrounding picture too. The talk credits AGP 9.2 with roughly 2x faster coroutine primitives, which Tinder associated with a 13% ANR reduction, and AGP 9.3 adds a redesigned R8 API with cleaner defaults and source-directory support for keep rules. There is also an agent skill that reads the analyzer output and points at oversized package-wide wildcards when you ask it to analyze your R8 configuration. Treat its findings as leads to verify, not as edits to accept blindly.

Takeaways

  • A broad keep rule is a debt that compounds across shrinking, optimization, and obfuscation at once.
  • Measure first. The analyzer’s keep counts, subsumed-rule list, and unused-rule list tell you where to cut.
  • Move rules to the call site with typed annotations so they are conditional, exact, and deleted together with the code.
  • Release-only reflection failures are often silent. Log them.
  • Gate the scores in CI, and keep the baseline honest.

The goal is not a perfect score. It is a configuration where every keep rule has a reason you can point to in the code.


📱 Go Beyond Using Jetpack Compose

If you’re building on Android, understanding what happens under the hood separates developers who use Compose from those who master it. I highly recommend “Mastering Jetpack Compose Internals”. It’s a deep, architecture-first walkthrough of the composition tree, the slot table, snapshot state, and the runtime that powers modern Android UI — capped off with a full case study building a real app called Mosaic.

Top comments (0)