Feature flags and remote config
Why it matters
- Feature flags let you ship code to the Play Store turned off, roll it out to a percentage of users, and turn it off again without a new release. Senior interviewers ask how you would do exactly that.
- Firebase Remote Config is the most common way to do it on Android, and its details (in-app defaults,
fetchAndActivate(), the 12-hour default minimum fetch interval, when new values take effect) decide whether a flag behaves the way you expect. - A kill switch, a flag that turns a risky feature off, is often the fastest way to stop a bad rollout, because a fix through Play Store review and staged rollout takes much longer to reach users.
- Flags are also technical debt. Every flag left in the code after rollout is a branch nobody tests, so cleanup is part of the lifecycle.
The simple explanation
- A feature flag is a light switch: you can turn a room on or off without rewiring the building.
- In-app defaults are the switch positions printed on the wiring plan: what you get before anyone has touched a switch.
- A kill switch is the breaker for one wing: one flip cuts power to that wing whatever the room switches say.
- Cleanup is removing the switch once the room is permanently lit.
What is Firebase Remote Config? A cloud service that stores parameters (key-value pairs, optionally with conditions such as app version, country or a random percentage of users). The Android SDK keeps three sets of values on the device: defaults you set in code, the last fetched values, and the active values your code reads.
setDefaultsAsync(...)takes aMap<String, Any>or an XML resource. These values are used until a fetched value has been activated, for example on first launch with no network.fetch()downloads values;activate()makes the fetched values active.fetchAndActivate()does both and returns aTask<Boolean>that istruewhen this call activated newly fetched values.- The default minimum fetch interval is 12 hours. Within that interval, a fetch returns cached values instead of calling the server. Set it low in development builds only; fetching too often gets throttled (
FirebaseRemoteConfigFetchThrottledException). getBoolean(key),getString(key),getLong(key)andgetDouble(key)are synchronous and read the active value. If a key has neither an active value nor a default, they return a static value:false,"",0or0.0.- Activated values are stored on disk, so after one successful activation the app keeps using them on later launches, even offline.
- Real-time updates:
addOnConfigUpdateListener(...)gets notified when you publish a new template in the console. The SDK fetches the new values automatically, but you still decide when to callactivate().
When should new values take effect? Activating while a screen is open can change behaviour under the user. Firebase's loading strategies boil down to two common choices: fetch and activate behind a short splash or loading state at startup, or activate the values fetched last time at startup and fetch new ones in the background for the next launch.
A kill switch is a separate flag, such as checkout_v2_kill_switch, with an in-app default of false. The code checks it before the feature flag; when it is true the feature is off regardless of rollout percentage. For it to work fast, the app must actually fetch: real-time updates, or a fetch at every startup with a short enough interval.
Flag lifecycle: add the flag with a safe default, test internally, roll out by percentage while watching crash and business metrics, go to 100%, then remove the old code path, and delete the parameter from the console once app versions that still read it are no longer in use.
| Step | API | Purpose |
|---|---|---|
| Fallback | setDefaultsAsync(map) | Values used before anything is activated |
| Settings | setConfigSettingsAsync(settings) | Minimum fetch interval, fetch timeout |
| Pull and apply | fetchAndActivate() | Fetch, then activate in one call |
| Read | getBoolean(key) | Read the active value, synchronously |
| Real-time | addOnConfigUpdateListener(listener) | Hear about new templates; call activate() yourself |
Notes
- Set in-app defaults with
setDefaultsAsync()for every parameter the app reads. They cover first launch, offline first launch, and keys that are missing on the server. - Without a default,
getBoolean()returnsfalsefor a key that has never been activated. That silently turns a feature off. fetchAndActivate()returnsTask<Boolean>:trueif this call activated newly fetched values. Withkotlinx-coroutines-play-services, call.await()and catch failures; the app keeps its current active values.- The default minimum fetch interval is 12 hours (43,200 seconds). Use a low value only in debug builds; production apps that fetch too often get throttled.
getBoolean(),getString(),getLong()andgetDouble()read active values from memory and never call the network.- Activated values are persisted. A Firebase outage does not reset flags to defaults for users who have activated values before.
addOnConfigUpdateListener()(real-time Remote Config) fires after you publish a new template. The values are fetched for you; callactivate()when it is safe for the UI.remoteConfig.getValue(key).sourcetells you whether a value came from the server (VALUE_SOURCE_REMOTE), your defaults (VALUE_SOURCE_DEFAULT) or neither (VALUE_SOURCE_STATIC). Log it in debug builds.- Hide Firebase behind a small
FeatureFlagsinterface in a core module. Feature modules depend on the interface, and tests use a fake that returns fixed values. - Read flags in the ViewModel or data layer and put the result into UI state. A Composable that calls
getBoolean()directly is tied to Firebase, hard to preview and test, and can show different values on different screens if values are activated mid-session. - Remove a flag in two steps: delete the old code path in a release, then delete the console parameter once old app versions that read it are no longer in use. Deleting the parameter first sends those old versions back to their in-app defaults.
Code example
A small FeatureFlags interface that feature modules depend on, and a Firebase implementation that sets defaults, configures the fetch interval, fetches once at startup and checks a kill switch before the feature flag.
import com.google.firebase.remoteconfig.FirebaseRemoteConfig
import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.tasks.await
// :core:flags (no Firebase dependency)
interface FeatureFlags {
fun isCheckoutV2Enabled(): Boolean
}
// :core:flags-firebase (the only module that knows about Firebase)
class FirebaseFeatureFlags(
private val remoteConfig: FirebaseRemoteConfig,
private val isDebugBuild: Boolean,
) : FeatureFlags {
suspend fun initialize() {
remoteConfig.setDefaultsAsync(
mapOf(
CHECKOUT_V2 to false,
CHECKOUT_V2_KILL_SWITCH to false,
)
).await()
remoteConfig.setConfigSettingsAsync(
FirebaseRemoteConfigSettings.Builder()
.setMinimumFetchIntervalInSeconds(if (isDebugBuild) 0L else 3_600L)
.build()
).await()
}
// Called once at startup, for example behind the splash screen
suspend fun fetchAndActivate() {
try {
remoteConfig.fetchAndActivate().await()
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
// Network error or throttling: keep the current active values
}
}
override fun isCheckoutV2Enabled(): Boolean {
if (remoteConfig.getBoolean(CHECKOUT_V2_KILL_SWITCH)) return false
return remoteConfig.getBoolean(CHECKOUT_V2)
}
private companion object {
const val CHECKOUT_V2 = "checkout_v2_enabled"
const val CHECKOUT_V2_KILL_SWITCH = "checkout_v2_kill_switch"
}
}setDefaultsAsynctakes a plainMap<String, Any>, and both setup calls are awaited so the first fetch uses the right interval.- The fetch is wrapped so a network error or throttling keeps the current active values instead of crashing;
CancellationExceptionis rethrown. - The kill switch is read first, so turning it on disables checkout v2 whatever its rollout percentage.
- Feature modules see only
FeatureFlags. A ViewModel readsisCheckoutV2Enabled()once and puts the result into its UI state; tests pass a fakeFeatureFlags. - A 1-hour interval is an example. Pick one that balances how fast a kill switch must spread against fetch volume, or add real-time updates.
Run the idea in plain Kotlin
No Firebase here: a small class models the three value sets (defaults, fetched, active), the minimum fetch interval with a fake clock, and a kill switch.
class FakeRemoteConfig(private val minFetchIntervalSec: Long) {
private val defaults = mutableMapOf<String, Boolean>()
private var fetched: Map<String, Boolean>? = null
private val active = mutableMapOf<String, Boolean>()
private var lastFetchAt: Long? = null
var server = mapOf<String, Boolean>() // what the console holds
var now = 0L // fake clock, in seconds
fun setDefaults(values: Map<String, Boolean>) { defaults.putAll(values) }
fun fetchAndActivate(): Boolean {
val last = lastFetchAt
if (last == null || now - last >= minFetchIntervalSec) {
fetched = server // network call
lastFetchAt = now
}
val pending = fetched ?: return false
if (pending == active) return false
active.clear()
active.putAll(pending)
return true
}
fun getBoolean(key: String): Boolean = active[key] ?: defaults[key] ?: false
}
fun checkoutV2(rc: FakeRemoteConfig): Boolean =
if (rc.getBoolean("checkout_v2_kill_switch")) false else rc.getBoolean("checkout_v2_enabled")
fun main() {
val rc = FakeRemoteConfig(minFetchIntervalSec = 3600)
rc.setDefaults(mapOf("checkout_v2_enabled" to false, "checkout_v2_kill_switch" to false))
println("First launch, defaults only: " + checkoutV2(rc))
rc.server = mapOf("checkout_v2_enabled" to true, "checkout_v2_kill_switch" to false)
println("fetchAndActivate -> " + rc.fetchAndActivate() + ", checkout v2: " + checkoutV2(rc))
// Bug found: kill switch turned on in the console 10 minutes later
rc.server = mapOf("checkout_v2_enabled" to true, "checkout_v2_kill_switch" to true)
rc.now = 600
println("Inside interval -> " + rc.fetchAndActivate() + ", checkout v2: " + checkoutV2(rc))
rc.now = 3600
println("After interval -> " + rc.fetchAndActivate() + ", checkout v2: " + checkoutV2(rc))
}Expected output:
First launch, defaults only: false
fetchAndActivate -> true, checkout v2: true
Inside interval -> false, checkout v2: true
After interval -> true, checkout v2: false
The third line is why kill switches need a plan for propagation: within the minimum fetch interval the app keeps its cached values, unless real-time updates or a shorter interval are in place.
In production
- A team rolled out
checkout_v2_enabledto 100% in the console and later removed the old checkout's bug fixes, assuming everyone was on v2. - The parameter was never added to the in-app defaults, so
getBoolean()returnedfalseuntil the first fetch was activated. - New users who opened the app offline, or whose first fetch failed, were sent to the old checkout, which no longer worked well.
- They added every parameter the app reads to the defaults map, with the default matching what a user should see if Remote Config is unavailable.
- Parameter keys moved into one constants file next to the defaults map, and a unit test checks that every key has a default.
- Debug builds log
getValue(key).sourceso the team can see when a device is running on defaults instead of server values.
enable_new_searchreached 100% a long time ago, but theifbranch and the old search code stayed in the app.- A new developer fixed a bug in the old search path, not knowing that no user could reach it.
- Later someone deleted the parameter from the console during a cleanup. Users on old app versions, whose in-app default was
false, were switched back to the old search.
- Every new flag now gets an owner and a planned removal date in the flag's description and in a tracking issue.
- Cleanup happens in two steps: remove the old path and the flag check from the code, then delete the console parameter only after the versions that read it are rarely used (checked in Play Console version distribution).
- Flag defaults for released features are set to the rolled-out value, so a deleted parameter does not turn a shipped feature off.
Common mistakes
- No in-app defaults.
getBoolean()returnsfalsefor any key that was never activated, on first launch or when a fetch fails. Add a default in the same change that adds the flag. - Expecting a fetch on every call.
fetchAndActivate()returns cached values within the minimum fetch interval (12 hours by default), so a kill switch can take that long to reach users. Choose the interval deliberately or add real-time updates. - A zero interval in production. A minimum fetch interval of 0 is for development. In production it causes throttling and wasted requests.
- Activating in the middle of a flow. Calling
activate()while the user is in checkout can swap behaviour mid-screen. Activate at startup or at a safe point, and read flags into UI state once per screen. - Reading Firebase directly in Composables. It ties UI code to Firebase and makes previews and tests hard. Read flags behind an interface in the ViewModel and pass the result down.
- Deleting the console parameter at the same time as the code. Old app versions still read the key and fall back to their in-app default. Remove code first; delete the parameter after old versions are gone.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How does fetchAndActivate work, and why might you call fetch and activate separately?”
“How do you implement a kill switch on Android?”
“How do you test code that depends on feature flags?”
“When and how do you remove a feature flag?”
Quiz
On first launch, with no network and no setDefaultsAsync call, what does getBoolean("checkout_v2_enabled") return?
What is the default minimum fetch interval for Firebase Remote Config?
The kill switch checkout_v2_kill_switch is turned on in the console. With a 12-hour minimum fetch interval and no real-time listener, when does a device that fetched an hour ago see it?
A flag has been at 100% for months. What is the safe way to remove it?
0 of 4 answered
Mini task
Add a kill switch to an existing feature flag (20 min)
- In your Remote Config wrapper, add a key such as
<feature>_kill_switchand give it a default offalsein thesetDefaultsAsyncmap. - In the function that reads the feature flag, check the kill switch first and return
falsewhen it istrue. - In the Firebase console, create the parameter with a default value of
falseand publish. - In a debug build with a minimum fetch interval of 0, set the kill switch to
true, restart the app so it fetches and activates, and confirm the feature is off. Set it back tofalseand confirm it returns. - Write unit tests with a fake
FeatureFlags: kill switch on with feature flag on givesfalse; kill switch off with feature flag on givestrue. - Write down how fast the switch reaches production users with your production minimum fetch interval, and whether you need real-time updates.
Done when: the kill switch turns the feature off on a debug device, both tests pass, and you know how long the switch takes to reach users in production.