Feature flags and remote config

Learn feature flags on Android with Firebase Remote Config: in-app defaults, fetchAndActivate, minimum fetch interval, kill switches and flag cleanup. About 25 minutes.

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 a Map<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 a Task<Boolean> that is true when 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) and getDouble(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, "", 0 or 0.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 call activate().

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.

StepAPIPurpose
FallbacksetDefaultsAsync(map)Values used before anything is activated
SettingssetConfigSettingsAsync(settings)Minimum fetch interval, fetch timeout
Pull and applyfetchAndActivate()Fetch, then activate in one call
ReadgetBoolean(key)Read the active value, synchronously
Real-timeaddOnConfigUpdateListener(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() returns false for a key that has never been activated. That silently turns a feature off.
  • fetchAndActivate() returns Task<Boolean>: true if this call activated newly fetched values. With kotlinx-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() and getDouble() 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; call activate() when it is safe for the UI.
  • remoteConfig.getValue(key).source tells 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 FeatureFlags interface 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"
    }
}
  • setDefaultsAsync takes a plain Map<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; CancellationException is 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 reads isCheckoutV2Enabled() once and puts the result into its UI state; tests pass a fake FeatureFlags.
  • 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 missing in-app default turned a feature off for new installs
  • A team rolled out checkout_v2_enabled to 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() returned false until 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.
The fix
  • 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).source so the team can see when a device is running on defaults instead of server values.
A stale flag outlived its feature
  • enable_new_search reached 100% a long time ago, but the if branch 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.
The fix
  • 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() returns false for 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)

  1. In your Remote Config wrapper, add a key such as <feature>_kill_switch and give it a default of false in the setDefaultsAsync map.
  2. In the function that reads the feature flag, check the kill switch first and return false when it is true.
  3. In the Firebase console, create the parameter with a default value of false and publish.
  4. 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 to false and confirm it returns.
  5. Write unit tests with a fake FeatureFlags: kill switch on with feature flag on gives false; kill switch off with feature flag on gives true.
  6. 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.

Next: Recomposition and stability