A Room migration or a missing R8 keep rule can put an Android app in a crash loop before Remote Config loads. A flag can't reach that code, so tests and a startup guard have to.
"...once an app has the bad configuration it will continue to crash before it's able to successfully fetch the corrected configuration."
Lyft's engineers wrote that in 2022 about feature flags that crashed their app at launch. Turning the flag off remotely didn't help, and they usually had to ship a hotfix. Their answer was Safe Mode, which locks the flags read before a launch crash to their local defaults for the rest of the session. The post's list of future work ends on a question: what other things cause crash loops on launch?
My release gate piece ended its checklist with one line about the code no flag can reach: startup code, database migrations, manifest changes and R8 keep rules. A reader pointed out under a recent post that an unverified Room migration in Application.onCreate() crash-loops before a Remote Config flag is even evaluated. That's right, and one line wasn't enough. This is the longer version for Android, covering Room migrations and R8 keep rules, with the tests and guards that belong in front of them.
A flag only works if the code asks for it
Android calls Application.onCreate() "when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created" (Application reference). Content providers come first. That includes App Startup, which runs its initializers through a single InitializationProvider, and any library that starts itself the same way.
Remote Config doesn't fit inside that window. fetchAndActivate() returns a Task that finishes whenever the network call does, and the Android guide says the default minimum fetch interval is 12 hours, so configs "won't be fetched from the backend more than once in a 12 hour window, regardless of how many fetch calls are actually made." The loading strategies guide describes a pattern where the app activates values fetched in an earlier session right away, then fetches new ones in the background for the next startup. In a crash loop the process often dies before that background fetch finishes, and inside the 12-hour window the fetch may not reach the backend at all. Real-time updates skip the interval, but only once the listener is running.
The obvious answer is to block startup on a fetch with a short timeout. Firebase's own Strategy 2 does that behind a loading screen, and it's reasonable for A/B tests. Lyft considered a forced refresh for crash loops and turned it down for two reasons, paraphrased here from the post. A forced refresh would have kept users out of the app until someone reverted the bad change, and the network call needed extra dependencies set up first, which had themselves caused launch crashes before.
On Android, two causes deserve a release rule of their own, and neither one reads a flag.
Room runs migrations when it opens the database
The RoomDatabase.Builder reference says that when the version on the device doesn't match the latest schema, Room runs the migrations, and "if it cannot find the set of Migrations that will bring the database to the current version, it will throw an IllegalStateException." The migration guide adds that "an incorrectly defined migration can cause your app to crash."
Where that crash lands depends on where your first query sits. If it runs from Application.onCreate() or an App Startup initializer, the crash comes before the first screen draws. Moving the open later doesn't stop the crash in an app whose first screen reads the database. It just gives your own code a chance to run first. And nothing changes before the next launch. The file on disk is at the old version, the code still has no path from it, so Room throws again.
Android's own ContentProvider.onCreate() docs already warn about this kind of startup work. They say to defer "opening, upgrading, and scanning databases" until the provider is used, partly because deferring "stops database errors (such as a full disk) from halting application launch." The same reasoning fits any code on the startup path.
Wrapping the database open in a flag doesn't help either. Room doesn't consult Remote Config before it migrates, and an app that can't open its database while the flag is off can't show the user their data.
There's also a catch in the rollback from the release gate piece, which was re-shipping the previous code under a higher version code. If the bad build already migrated someone's database to a newer version, the old code arrives at a database newer than it knows about, and Room needs a migration going down. This is what that looks like, from a public bug report on Kotatsu, an open-source Android app, where the app displayed it right after opening:
A migration from 24 to 23 was required but not found. Please provide the necessary Migration path via RoomDatabase.Builder.addMigration(Migration ...) or allow for destructive migrations via one of the RoomDatabase.Builder.fallbackToDestructiveMigration* methods.
A database at version 24 and code expecting 23. fallbackToDestructiveMigrationOnDowngrade gets past it by dropping and recreating the tables, which deletes all of the user's data. The safer rollback never goes down. The rollback build keeps the @Database version and schema the bad build shipped, or moves one version higher with a migration back to the old shape, so Room only ever migrates forward and the user keeps their rows. That makes the rollback something other than a pure revert of the code.
The guide's warning about fallbackToDestructiveMigration is just as blunt: Room "permanently deletes all data from the tables in the user's database" when it falls back. My opinion is that it shouldn't go into a production builder just to stop a crash. A crash loop at least shows up in your crash reports and in Android vitals. Wiped tables don't show up in either one. You can log one through RoomDatabase.Callback.onDestructiveMigration(), but by then the data is already gone. If one old version really can't be migrated, fallbackToDestructiveMigrationFrom limits the loss to that version, and that choice deserves a named reviewer. (Since Room 2.7 these builder functions take a dropAllTables argument, and the no-argument versions are deprecated.)
R8 misses only exist in the build you ship
R8 removes code it thinks is unused and shortens class, field and method names. Google recommends turning it on only for the final build you test before publishing, which is usually the release build. Follow that advice and your debug builds never run R8's output.
The trouble is code R8 can't see being used. The keep rules overview names reflection, such as a method looked up by name with Class.getDeclaredMethod(), and calls across JNI. R8 can rename or remove those targets, "leading to a ClassNotFoundException or a NoSuchMethodException at runtime." Since AGP 8.0, R8 runs in full mode by default, which the R8 page says makes "stricter assumptions about how your code uses reflection" and might need extra keep rules.
R8 can't follow this pattern. Optional modules list their startup plugins by class name in a string-array resource, and the app builds them at launch.
interface StartupPlugin {
fun install(app: Application)
}
// Optional modules list their class names in a string-array resource,
// so the core app never references them directly.
fun installStartupPlugins(app: Application, classNames: List<String>) {
for (name in classNames) {
val plugin = Class.forName(name)
.getDeclaredConstructor()
.newInstance() as StartupPlugin
plugin.install(app)
}
}
A debug build runs this fine. In a minified build, nothing in the code names those plugin classes, so R8 can remove or rename them, and Class.forName throws ClassNotFoundException. If installStartupPlugins runs from Application.onCreate(), it throws on every launch. R8's compatibility FAQ says classes "only instantiated using reflection should be kept explicitly with a -keep rule," and that in full mode keeping a class doesn't keep its default constructor, which is why the rule names <init>():
# proguard-rules.pro (with AGP 9.3's new DSL: src/main/keepRules/startup.keep)
-keep class * implements com.example.startup.StartupPlugin {
<init>();
}
No flag can reach this one. The code is missing from the APK, and a keep rule only takes effect in a new build. If your own code does the reflection, Jetpack Keep lets you annotate the call instead of maintaining rules by hand, and its lint checks flag reflective calls you didn't annotate. It's still in alpha, so compare the generated rules when you upgrade it.
Google's Test the optimization page says keep rules on rarely used code "can be difficult to test" locally, and suggests staged rollouts while you watch for crash regressions. Startup code is the opposite of rarely used, though. Every user runs it on every launch, so one launch of the minified build catches it before a user does. Two notes from the troubleshooting page also matter. mapping.txt is bundled into your app bundle, so Play gets it, but the local file is overwritten on every build, so keep a copy per release for retrace and for any crash tool that doesn't read it from the bundle. And app/build/outputs/mapping/configuration.txt lists every merged rule, including the ones your libraries add.
The checklist
The code below uses Room 2.8.5 (androidx.room) with AGP 8.13.2, Gradle 8.14.3, Kotlin 2.2.21 and KSP 2.2.21-2.0.5, and the runtime checks ran on an API 35 emulator. On AGP 9.3 you need Gradle 9.5.0 or newer, you drop the org.jetbrains.kotlin.android plugin because Kotlin is built in, and you need KSP 2.3.14 or newer, since the 2.2.21 line of KSP refuses to run with built-in Kotlin. Room 3.0 moved to androidx.room3, and the current migration guide shows that version. The same approach applies to both, but on Room 3 the open and test calls go through the driver (SQLiteConnection) instead of openHelper.
1. Export schemas and commit them. The guide says to keep the exported JSON in version control "so that you can recreate lower versions of the database for testing." The folder also collects schemas from development builds that never shipped, and step 3 has to know about those. The same Gradle file adds a release copy that CI can install, signed with the debug key the way the Macrobenchmark setup does it.
// app/build.gradle.kts (excerpt, AGP 8.x legacy DSL)
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android") // not needed on AGP 9.x, which has built-in Kotlin
id("com.google.devtools.ksp")
id("androidx.room")
}
android {
buildFeatures {
buildConfig = true
}
buildTypes {
getByName("release") {
isMinifyEnabled = true
isShrinkResources = true
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro",
)
}
// Same R8 setup as release, signed with the debug key so CI can install it.
create("releaseCheck") {
initWith(getByName("release"))
signingConfig = signingConfigs.getByName("debug")
matchingFallbacks += listOf("release")
}
}
}
room {
schemaDirectory("$projectDir/schemas")
}
dependencies {
implementation("androidx.room:room-runtime:2.8.5")
ksp("androidx.room:room-compiler:2.8.5")
androidTestImplementation("androidx.room:room-testing:2.8.5")
}
2. Keep one list of migrations. The app's builder and the test read the same array, so a migration added in one place is in the other.
@Database(entities = [Note::class], version = 3)
abstract class AppDatabase : RoomDatabase() {
abstract fun noteDao(): NoteDao
companion object {
@Volatile private var instance: AppDatabase? = null
fun getInstance(context: Context): AppDatabase =
instance ?: synchronized(this) {
instance ?: Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"app.db",
)
.addMigrations(*ALL_MIGRATIONS)
.build()
.also { instance = it }
}
}
}
// One list, read by the app's builder and by the migration test.
val ALL_MIGRATIONS = arrayOf(MIGRATION_1_2, MIGRATION_2_3)
3. Test an upgrade from every shipped version. The guide recommends a test that covers all migrations from the earliest version. This one starts from each exported schema in turn, because a user who skipped five releases walks a different chain than someone who updated last week. A schema that only existed on a branch may have no path to latest and would then fail the loop. List it in neverShipped instead of writing a migration for a version nobody ever had.
@RunWith(AndroidJUnit4::class)
class ShippedSchemasMigrationTest {
private val instrumentation = InstrumentationRegistry.getInstrumentation()
@get:Rule
val helper = MigrationTestHelper(instrumentation, AppDatabase::class.java)
// Schemas exported during development that no release ever shipped,
// for example setOf(5) if version 5 only lived on a branch.
private val neverShipped = emptySet<Int>()
@Test
fun everyExportedSchemaUpgradesToLatest() {
// Exported schemas land in test assets as <database class>/<version>.json.
val versions = instrumentation.context.assets
.list(AppDatabase::class.java.canonicalName!!)!!
.map { it.removeSuffix(".json").toInt() }
.sorted()
assertTrue("No older schemas found in test assets", versions.size > 1)
for (version in versions.dropLast(1) - neverShipped) {
val name = "upgrade-from-$version"
helper.createDatabase(name, version).close()
val db = Room.databaseBuilder(
instrumentation.targetContext,
AppDatabase::class.java,
name,
)
.addMigrations(*ALL_MIGRATIONS)
.build()
helper.closeWhenFinished(db)
// Opening runs every migration from `version` and validates the final schema.
db.openHelper.writableDatabase
}
}
}
This test checks schemas. For migrations that move rows around, also keep a single-version test that inserts rows at the old version and reads them back after runMigrationsAndValidate, as the guide shows.
4. Add a startup crash guard. Crash reporters already expose the raw signal. BugSnag's launch crash docs describe crashedDuringLaunch and consecutiveLaunchCrashes, and Crashlytics has didCrashOnPreviousExecution(), which reports any crash on the previous run. A small counter does the job without either.
The counter has to count the right thing. Application.onCreate() runs for every process start, including a push message, a WorkManager job or a broadcast receiver, and none of those reach your first screen. Count there and two background wakes put a healthy user into safe mode. So this guard counts only fresh launches of the launcher Activity. On Android 11 and later it also asks the OS how the last launch ended. ActivityManager.getHistoricalProcessExitReasons() returns recent ApplicationExitInfo records, and REASON_CRASH ("died because of an unhandled exception in Java code") is a different reason from REASON_USER_REQUESTED, which the docs say covers swiping the app away from Recents. The helper below counts REASON_CRASH, REASON_CRASH_NATIVE, REASON_ANR and REASON_EXCESSIVE_RESOURCE_USAGE as failed launches. The last one is there because, on an API 35 emulator, a second crash within about a minute left the process behind the "keeps stopping" dialog (nobody dismissed it, as in CI), and the system later killed it for excessive resource use instead of recording a crash. Counting REASON_ANR also catches a launch that hangs.
// Android 11+ keeps a short history of why the app's processes died.
fun Context.crashedSince(sinceMillis: Long): Boolean? {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return null
val am = getSystemService(ActivityManager::class.java)
return am.getHistoricalProcessExitReasons(packageName, 0, 10).any {
it.timestamp >= sinceMillis &&
it.reason in FAILED_LAUNCH_EXITS
}
}
// A process that crashes again soon after a crash can sit behind the "keeps stopping"
// dialog and be killed later for excessive resource use, so that reason counts too.
private val FAILED_LAUNCH_EXITS = setOf(
ApplicationExitInfo.REASON_CRASH,
ApplicationExitInfo.REASON_CRASH_NATIVE,
ApplicationExitInfo.REASON_ANR,
ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE,
)
It writes with commit() because the SharedPreferences docs say apply() only "starts an asynchronous commit to disk," and this state has to be on disk before the risky code runs.
class StartupGuard(
private val prefs: SharedPreferences,
private val versionCode: Long,
// true or false on Android 11+, null on older versions where the OS can't say.
private val crashedSince: (Long) -> Boolean?,
private val maxFailedLaunches: Int = 2,
) {
/** Call from the launcher Activity, once per fresh user launch. Returns true for safe mode. */
fun onUserLaunch(nowMillis: Long = System.currentTimeMillis()): Boolean {
val sameBuild = prefs.getLong(KEY_VERSION, -1L) == versionCode
var failed = if (sameBuild) prefs.getInt(KEY_FAILED, 0) else 0
val lastUnfinished = sameBuild && prefs.getBoolean(KEY_UNFINISHED, false)
// An unfinished launch counts unless the OS says it didn't end in a crash.
if (lastUnfinished && crashedSince(prefs.getLong(KEY_STARTED_AT, 0L)) != false) {
failed++
}
// A small synchronous write on purpose: it has to reach disk before risky startup work runs.
prefs.edit()
.putLong(KEY_VERSION, versionCode)
.putInt(KEY_FAILED, failed)
.putLong(KEY_STARTED_AT, nowMillis)
.putBoolean(KEY_UNFINISHED, true)
.commit()
return failed >= maxFailedLaunches
}
/** Call when the first screen is up and startup work has finished. Also backs "try again". */
fun onLaunchCompleted() {
prefs.edit().putInt(KEY_FAILED, 0).putBoolean(KEY_UNFINISHED, false).commit()
}
/** For workers, receivers and other entry points: skip database work while this is true. */
fun isInSafeMode(): Boolean =
prefs.getLong(KEY_VERSION, -1L) == versionCode &&
prefs.getInt(KEY_FAILED, 0) >= maxFailedLaunches
private companion object {
const val KEY_VERSION = "version_code"
const val KEY_FAILED = "failed_launches"
const val KEY_STARTED_AT = "last_launch_started_at"
const val KEY_UNFINISHED = "last_launch_unfinished"
}
}
Then wire it so the database opens inside the guarded window. If the open on Dispatchers.IO throws, withContext rethrows into the coroutine on the main thread, so the crash shows up as FATAL EXCEPTION: main. A failed migration now counts as a failed launch, and after two of those the app comes up in safe mode instead of crashing a third time.
class App : Application() {
// No launch counting here: this runs for every process start, including
// push messages, WorkManager jobs and broadcast receivers.
val startupGuard: StartupGuard by lazy {
StartupGuard(
prefs = getSharedPreferences("startup_guard", MODE_PRIVATE),
versionCode = BuildConfig.VERSION_CODE.toLong(),
crashedSince = { since -> crashedSince(since) },
)
}
}
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val guard = (application as App).startupGuard
// Count fresh launches only, not rotation or restore after process death.
val safeMode =
if (savedInstanceState == null) guard.onUserLaunch() else guard.isInSafeMode()
if (safeMode) {
setContent {
SafeModeScreen(onTryAgain = {
guard.onLaunchCompleted()
startActivity(Intent(this@MainActivity, MainActivity::class.java))
finish()
})
}
return
}
setContent { AppContent() }
lifecycleScope.launch {
// Risky startup work runs inside the guarded window, so a failed
// migration counts as a failed launch.
withContext(Dispatchers.IO) {
AppDatabase.getInstance(applicationContext).openHelper.writableDatabase
}
guard.onLaunchCompleted()
}
}
}
In safe mode the first screen skips optional work and keeps the database closed. It can still start Play's immediate in-app update once the fixed build is out, and "try again" clears the count and starts a fresh launch. If the bug is still there, one tap allows two more crashes before safe mode comes back. The count resets when the version code changes, so the fixed build starts clean.
The guard has limits. Other entry points (a worker, a receiver, a deep link into a different Activity) still open the database on their own, so they should check isInSafeMode() and skip that work, for example by returning Result.retry() from a worker. Crashes before the launcher Activity, in Application.onCreate(), a content provider or an App Startup initializer, never reach the counter, which is one more reason to keep risky work out of those places. Moving the count into Application.attachBaseContext() would see them, since AOSP's handleBindApplication creates the Application (which calls attachBaseContext()) before it installs content providers, but that runs for background process starts too. Before Android 11, a swipe during launch still counts as a failure, so tune the threshold from your own crash data. And ship it quietly first. Lyft rolled Safe Mode out with a "shadow" setting that only logged, and after shipping found it engaging at low volume on an unrelated thread-safety bug at launch.
5. Launch the minified build on top of the last release. This runs in CI on an emulator, using the releaseCheck type from step 1.
#!/usr/bin/env bash
# Upgrade smoke test: install the last release, then this build over it.
set -euo pipefail
PKG=com.example.app
APK=app/build/outputs/apk/releaseCheck/app-releaseCheck.apk
launch_and_check() {
adb logcat -b all -c # clear every buffer, including old crashes
adb shell am start -W -S -n "$PKG/.MainActivity" # -S force-stops it first
sleep 10 # give startup work and the database open time to finish
if adb logcat -b crash -d | grep -q "$PKG"; then
adb logcat -b crash -d
echo "Startup crash: $1"
exit 1
fi
}
adb uninstall "$PKG" || true
git checkout "$LAST_RELEASE_TAG"
./gradlew :app:assembleReleaseCheck
adb install "$APK"
launch_and_check "last release"
git checkout "$CANDIDATE_SHA"
./gradlew :app:assembleReleaseCheck
adb install -r "$APK" # -r keeps the app's data, so the real upgrade runs
launch_and_check "candidate, first launch"
launch_and_check "candidate, second launch"
adb install -r reinstalls "keeping its data," so the candidate opens a database the last release created and has to migrate it. The same launch runs R8's output, which a debug build and most unit tests never touch. It works from the first release that includes releaseCheck. Until then, cherry-pick the build type onto the last release tag. It also only covers the newest upgrade path on a nearly empty database, so it's a check on startup code and R8. Step 3 covers older schemas, and the single-version test covers rows.
6. Give these changes the slowest rollout, and name what you wait for. Halting a Play staged rollout means "no additional users will receive the app version," and users who already got it "will remain on that version" (Play Console Help). A small first step still strands that small group, so it only helps if you're watching the right number. For startup changes, that's crash-free users and sessions for the new build in Crashlytics, which you can filter by build, or the user-perceived crash rate per version code from the Play Developer Reporting API. Vitals comes from users who opted in to share usage and diagnostics data, and the API reports its own freshnessInfo, so check which period the data actually covers before you expand. A diff that touches the @Database version, a Migration, startup code in Application.onCreate() or an initializer, or a keep rules file waits at the first step until that number is steady against the previous build. If a coding agent wrote that diff, a human reviews those files no matter how small the change looks.
This post sticks to Android. iOS has its own versions of startup work and data migrations, and App Store phased release only limits automatic updates, since anyone can download the update manually at any time.
Flags still earn their place for the code that reads them. Everything on this list runs earlier than that, so it has to be proven before the release starts.




Top comments (3)
The Kotatsu example is the one that will stick with me — a database sitting at version 24 with code expecting 23, and the only escape being a destructive migration that wipes the user's data. The startup guard is the practical takeaway for me: counting REASON_CRASH through getHistoricalProcessExitReasons and opening in safe mode with the database closed after two failed launches feels like something every app with a Room migration should have. One question on the guard's blind spot: you note crashes in Application.onCreate or a content provider never reach the counter — have you found a practical way to cover that window, or is counting in attachBaseContext the only honest answer and just not worth the background-process noise?
Good question. Counting launches in attachBaseContext() is noisy, but reading crashes there isn't. ApplicationExitInfo records a crash in Application.onCreate() or a provider like any other, so on Android 11 and later attachBaseContext() can call getHistoricalProcessExitReasons(), keep the REASON_CRASH entries for its own process name that are newer than the last completed launch, and set a safe mode flag without writing anything. A background start then only pays for that one lookup. The harder part is acting on the flag. Your own init in onCreate() can check it, but an App Startup initializer runs before onCreate(), so it only becomes skippable if you remove it from the manifest and call AppInitializer yourself behind the same check. On Android 15, ApplicationStartInfo also reports why the process started, which could separate launcher starts from push or job starts, though it's worth checking how early that record is filled in before relying on it.
The Kotatsu 24-to-23 example is the whole piece in one bug. Downgrade with no migration path leaves only the destructive one.