R8, shrinking and obfuscation
Why it matters
- R8 runs only in minified builds, so a missing keep rule causes crashes that appear in release and never in debug. You need to know how to find and fix them fast.
- Release crash reports show names like
at a.b.c(SourceFile). Without the matchingmapping.txtuploaded (or used withretrace), you cannot read them. - Senior interviews ask about
-keepversus-keepclassmembersversus-keepnames, and why R8 full mode (the default since AGP 8.0) breaks reflection-heavy code. - Library authors who skip
consumer-rules.propush keep-rule problems onto every app that depends on them.
The simple explanation
- R8 is an editor working on a manuscript: it cuts chapters nobody reads (shrinking), tightens sentences (optimization), and replaces character names with initials (obfuscation).
mapping.txtis the key that turns initials back into names.- A keep rule is a note to the editor: "do not cut or rename this."
consumer-rules.prois a note that a library's author attaches for the editor of every app that uses the library.
What does R8 do in an Android build? R8 is the compiler that turns your app's bytecode into DEX and, when you set isMinifyEnabled = true on a build type, also shrinks, optimizes and obfuscates it. It has been the default instead of ProGuard since AGP 3.4. Shrinking removes classes, methods and fields that nothing reachable uses. Optimization inlines, merges classes and removes dead branches. Obfuscation renames what is left to short names. isShrinkResources = true then removes unused resources.
R8 only sees direct code references. Anything found by name at runtime (reflection, Class.forName, JNI, Gson-style serialization, classes named in XML outside the manifest and layouts) looks unused or renameable unless a keep rule says otherwise.
Full mode has been the default since AGP 8.0. Compared with the older "compatibility mode", it assumes less: for example, it does not keep default constructors or generic signatures of classes that no rule keeps. That gives smaller apps but breaks code that relied on those implicit keeps. You can turn it off with android.enableR8.fullMode=false in gradle.properties, but the real fix is a correct keep rule.
Rules come from the files listed in proguardFiles(...) (your proguard-rules.pro plus the default proguard-android-optimize.txt) and from rules that libraries ship. An Android library declares its rules with consumerProguardFiles("consumer-rules.pro"); AGP packages them into the AAR and applies them when an app that depends on it is minified. The library's own proguard-rules.pro is not passed to consumers.
| Rule | Effect |
|---|---|
-keep class X { ... } | Keeps class X (not removed, not renamed) and the members listed in the braces |
-keepclassmembers class X { ... } | Keeps the listed members only if X itself is kept or used |
-keepnames class X | Prevents renaming, but X can still be removed if unused (same as -keep,allowshrinking) |
-assumenosideeffects class X { ... } | Tells R8 the listed methods have no side effects, so calls whose result is unused are removed |
-keepattributes SourceFile,LineNumberTable | Keeps line number information for readable stack traces |
After a minified build, R8 writes mapping.txt to app/build/outputs/mapping/release/. Crash tools need the mapping file of the exact build that crashed: Play Console reads it from your app bundle (AGP 4.1+), the Crashlytics Gradle plugin uploads it automatically, and the retrace command-line tool uses it locally.
Notes
isMinifyEnabled = trueturns on shrinking, optimization and obfuscation. Without it R8 only compiles to DEX, which is why debug builds do not show keep-rule crashes.- Full mode is the default since AGP 8.0. Opt out with
android.enableR8.fullMode=falseingradle.propertiesonly as a short-term workaround while you add the missing rules. - Use
proguard-android-optimize.txtas the default file. Optimization must be on for-assumenosideeffectsto remove anything. - Use the narrowest rule that works.
-keep class com.example.** { *; }disables shrinking and renaming for a whole package and is a common cause of bloated apps. @Keepfromandroidx.annotationworks because the annotation library ships rules that keep annotated classes and members. It is handy for one class; a rule file is clearer for patterns.- Libraries: put rules consumers need in
consumer-rules.proand declare it withconsumerProguardFiles. An app can add a rule in its ownproguard-rules.proto work around a library bug, but the fix belongs in the library. mapping.txtchanges with every build. Keep it per release (CI artifact), let the Crashlytics plugin upload it, and rely on Play reading it from the app bundle.retraceships in the Android SDK command-line tools (cmdline-tools/latest/bin/retrace):retrace mapping.txt stacktrace.txtprints the trace with original names.- To keep exact line numbers, add
-keepattributes SourceFile,LineNumberTableand optionally-renamesourcefileattribute SourceFileto hide real file names. -printusage usage.txtlists what R8 removed and-printseeds seeds.txtlists what your keep rules matched. Both help when a rule is too broad or missing.- Libraries such as kotlinx.serialization, Retrofit and OkHttp ship their own R8 rules inside the artifact. Check a library's docs before writing rules for it, especially for full mode.
Code example
This shows two classic R8 cases, a Gson DTO whose field names must survive and plugins loaded by class name, followed by the matching rules.
package com.example
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
// Gson reads and writes fields by reflection.
data class UserDto(
@SerializedName("id") val id: Long,
@SerializedName("display_name") val displayName: String,
)
fun parseUser(json: String): UserDto = Gson().fromJson(json, UserDto::class.java)
// Plugins are created by class name, for example from remote config.
interface ExportPlugin {
fun export(): String
}
class CsvExportPlugin : ExportPlugin {
override fun export(): String = "csv"
}
fun loadPlugin(className: String): ExportPlugin =
Class.forName(className).getDeclaredConstructor().newInstance() as ExportPlugin# app/proguard-rules.pro
# Gson: keep the DTO fields that are read by reflection
-keepclassmembers class com.example.UserDto { <fields>; }
# Plugins: keep implementations, their names and the no-arg constructor
-keep class * implements com.example.ExportPlugin { public <init>(); }
# Strip verbose and debug logging in release
-assumenosideeffects class android.util.Log {
public static int v(...);
public static int d(...);
}
# Readable line numbers in crash reports
-keepattributes SourceFile,LineNumberTable
-renamesourcefileattribute SourceFile// library/build.gradle.kts: ship rules to every consuming app
android {
defaultConfig {
consumerProguardFiles("consumer-rules.pro")
}
}-keepclassmembers ... { <fields>; }keeps the DTO's fields and their@SerializedNameannotations. The class is used directly inparseUser, so it is not removed; only its fields needed protecting.-keep class * implements ExportPlugin { public <init>(); }keeps every plugin's class name, soClass.forNamefinds it, and the constructor, which full mode would otherwise not keep.- The
-assumenosideeffectsblock removesLog.vandLog.dcalls in release. Code that builds the message may remain if R8 cannot prove it is side-effect free. - The library snippet is what makes its
consumer-rules.proapply in apps that depend on it.
Run the idea in plain Kotlin
fun main() {
val mappingTxt = """
com.example.data.UserRepository -> a.b:
com.example.data.User load(long) -> a
com.example.ui.ProfileViewModel -> a.c:
void refresh() -> b
""".trimIndent()
// Parse class lines and member lines into lookup tables.
val classes = mutableMapOf<String, String>()
val members = mutableMapOf<String, String>()
var currentObfuscated = ""
for (line in mappingTxt.lines()) {
if (!line.startsWith(" ")) {
val (original, obfuscated) = line.removeSuffix(":").split(" -> ")
classes[obfuscated] = original
currentObfuscated = obfuscated
} else {
val (signature, obfuscated) = line.trim().split(" -> ")
val name = signature.substringAfter(" ").substringBefore("(")
members[currentObfuscated + "." + obfuscated] = name
}
}
val trace = listOf("at a.c.b(SourceFile:40)", "at a.b.a(SourceFile:12)")
val frame = Regex("at (.+)\\.(\\w+)\\((.*)\\)")
for (line in trace) {
val (cls, method, location) = frame.find(line)!!.destructured
val realClass = classes[cls] ?: cls
val realMethod = members[cls + "." + method] ?: method
println(line + " -> at " + realClass + "." + realMethod + "(" + location + ")")
}
}Expected output:
at a.c.b(SourceFile:40) -> at com.example.ui.ProfileViewModel.refresh(SourceFile:40)
at a.b.a(SourceFile:12) -> at com.example.data.UserRepository.load(SourceFile:12)
Real retrace also maps line numbers, because R8 records line ranges in mapping.txt when it inlines or moves code.
In production
- After upgrading to AGP 8, release builds parsed API responses into DTOs whose fields were all default values, so the profile screen showed blank names. Debug builds were fine.
- The DTOs had no
@SerializedNameannotations and no keep rules. Under R8 the fields were renamed, so Gson could not match the JSON keys, and nothing threw. - Earlier builds had worked by accident through a broad legacy rule that someone removed during cleanup.
- Added
@SerializedNameto every DTO field and a-keepclassmembers class com.example.data.dto.** { <fields>; }rule. - Added a release-build UI test that loads a real JSON fixture through the minified app and checks the parsed values, so the next missing rule fails CI instead of production.
- Planned a move to kotlinx.serialization, whose generated serializers do not need field-name reflection.
- An internal analytics library created its backends with
Class.forNameon names from a config file. - Its keep rule sat in the library's
proguard-rules.pro, which is used only when minifying the library itself, so consuming apps never received it. - Each app team hit
ClassNotFoundExceptionin release and added its own copy of the rule, with slightly different patterns.
- Moved the rule to
consumer-rules.pro, declared it withconsumerProguardFiles, and published a new version; the app-side copies were deleted. - Added a minified sample app to the library's CI that starts each backend, so a missing consumer rule fails the library build.
- Documented the rule change in the changelog, since consumer rules change what R8 keeps in every app.
Common mistakes
- Not keeping the mapping file of each release. Without it, crash traces from that build stay unreadable forever. Let the Crashlytics plugin upload it, ship app bundles so Play has it, and archive it in CI.
- Using -keep when -keepclassmembers would do. If the class is already used directly and only its fields matter for serialization,
-keepclassmemberslets R8 still shrink and rename everything else. - Putting a library's rules in proguard-rules.pro. Consumers only get rules from
consumerProguardFiles. Ship them inconsumer-rules.pro. - Turning off full mode to hide a crash.
android.enableR8.fullMode=falsehides the missing rule. Find the class with-printusageor the stack trace and add a targeted rule. - Shipping -dontobfuscate to make traces readable. It turns off renaming (shrinking still runs), so the app is larger and easier to reverse engineer. Use
mapping.txtandretraceinstead. - Disabling minification after a release-only crash.
isMinifyEnabled = falsein release removes shrinking and obfuscation entirely. Treat it as a quick experiment to confirm R8 is the cause, then add the rule.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What does R8 do, and when does it shrink your code?”
“How do you debug a crash that only happens in release?”
“What is the difference between -keep, -keepclassmembers and -keepnames?”
“What is consumer-rules.pro and when do you use it?”
Quiz
What is the default R8 behaviour for minified builds with Android Gradle Plugin 8.0 and later?
What file does R8 generate that you need to deobfuscate production crash traces?
What does -assumenosideeffects do?
A library loads a plugin with Class.forName. Where should its keep rule live so that every app depending on the library works when minified?
0 of 4 answered
Mini task
15-minute exercise: Enable R8, break it, and retrace
-
In
app/build.gradle.kts, in thereleasebuild type, setisMinifyEnabled = true,isShrinkResources = trueandproguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro"). For quick local testing, also setsigningConfig = signingConfigs.getByName("debug"). -
Add an interface
ExportPluginand a classCsvExportPluginthat nothing references directly. On a button click, load it withClass.forName(BuildConfig.APPLICATION_ID + ".CsvExportPlugin")(enablebuildFeatures.buildConfigif needed) so R8 cannot see the class name as a constant. -
Build with
./gradlew assembleRelease, install it and tap the button. You should get aClassNotFoundException. Searchapp/build/outputs/mapping/release/mapping.txtforCsvExportPlugin; it is missing because R8 removed it. -
Save the crash lines from logcat to
stacktrace.txtand runretrace app/build/outputs/mapping/release/mapping.txt stacktrace.txt. Confirm your own frames show original names. -
Add
-keep class * implements com.example.ExportPlugin { public <init>(); }(use your package) toproguard-rules.pro, rebuild, and confirm the button works andmapping.txtnow listsCsvExportPluginwith its original name. -
Add the
-assumenosideeffectsblock forLog.vandLog.d, rebuild, and confirm with the APK Analyzer in Android Studio that those calls are gone from the DEX bytecode.
Done condition: a minified release build where you broke and fixed a reflection lookup with one narrow keep rule, a stack trace you decoded with retrace, and Log.d calls stripped from release.