Performance monitoring in production

Learn Android performance monitoring in production with Firebase Performance traces, Android vitals, JankStats, ApplicationExitInfo and P95 per release. About 25 minutes.

Why it matters

  • Local testing cannot reproduce the real mix of low-end devices, slow networks, thermal throttling and full storage your users have.
  • Startup, jank and network regressions rarely fail a unit test. You find them in production data, compared release by release.
  • Senior engineers are expected to answer "is this release slower?" with numbers: percentiles per version, not a feeling from one test phone.
  • Android vitals core metrics (user-perceived crash and ANR rates, excessive partial wake locks, memory) affect your app's visibility on Google Play, so they are a business metric, not just an engineering one.

The simple explanation

  • A restaurant owner cannot watch every plate leave the kitchen.
  • They time orders (traces), count complaints and returns (crash and ANR rates) and read the inspector's report (Android vitals).
  • A slow steak for one table is an anecdote; slow steaks for the slowest tenth of tables every Friday is a pattern worth fixing.

How do you monitor Android app performance in production? You collect performance telemetry from real devices and compare it per app version. Android vitals in Play Console gives you crash, ANR, startup, rendering, battery and memory metrics without any code. Firebase Performance Monitoring (or a similar tool) adds automatic app start, screen rendering and network request traces, plus custom traces for your own flows. JankStats reports janky frames with the screen state attached, and ApplicationExitInfo tells you why the process ended last time.

ComponentFocusTool
Android vitalsCrash and ANR rates, startup, rendering, battery, memoryGoogle Play Console (no SDK)
TracesDuration of app start, screens, network calls and custom flowsFirebase Performance Monitoring, OpenTelemetry
FramesJanky frames tagged with UI stateJankStats (androidx.metrics:metrics-performance)
Exit reasonsWhy the process died: crash, ANR, low-memory kill and moreApplicationExitInfo (API 30+)

Key metrics to watch

  1. User-perceived crash and ANR rates. Android vitals measures them as the share of daily active users affected. The overall bad behavior thresholds are 1.09% for crashes and 0.47% for ANRs, and 8% for each on any single phone model. Above them, Play may reduce your app's visibility and may show a warning on your store listing.
  2. Startup time. Track TTID (time to initial display, the first frame) and TTFD (time to full display, reported with reportFullyDrawn()). Firebase Performance records an automatic app start trace.
  3. Network latency. Firebase Performance captures HTTP requests (with its Gradle plugin) with response time, payload size and success rate. Compare it with your own custom traces to tell a slow backend from slow client work.
  4. Rendering. Android vitals reports slow and frozen frames, and JankStats tells you which screen and action produced them. Fix them locally with Perfetto and confirm with Macrobenchmark's FrameTimingMetric.
  5. Battery and memory. Excessive partial wake locks and memory usage are core vitals. Wake lock time held in the background or by a foreground service counts.

Always read percentiles (P50, P90, P95) per release. The average hides the slow tail where users actually give up.

Notes

  • Android vitals overall bad behavior thresholds: 1.09% user-perceived crash rate and 0.47% user-perceived ANR rate, both per daily active user, plus 8% for each on any single phone model.
  • Excessive partial wake locks is a core vital: Android vitals counts a session as excessive when the app's partial wake locks add up to 2 hours or more in 24 hours.
  • Startup has two numbers: TTID (first frame, reported by the system) and TTFD (real content, reported by reportFullyDrawn()). Report TTFD only once content is visible.
  • Firebase Performance custom traces: Firebase.performance.newTrace("name").trace { } or @AddTrace(name = "...") on a method. Each trace allows 32 metrics and 5 custom attributes; keep both free of PII.
  • Read ApplicationExitInfo on the next launch, off the main thread, with ActivityManager.getHistoricalProcessExitReasons(). Store the newest timestamp you reported so you do not upload the same exit twice.
  • REASON_LOW_MEMORY is only reported on devices where ActivityManager.isLowMemoryKillReportSupported() returns true.
  • Custom traces cost little but not nothing. Trace user-visible flows (screen load, checkout, search), not every function.
  • Use staged rollouts and compare the new version's metrics with the previous one before increasing the percentage.
  • Compare percentiles per release and per device tier. A regression on low-RAM devices can vanish in the overall number.
  • Keep trace names, attributes and URLs free of personal data, and respect the user's consent with isPerformanceCollectionEnabled.

Code example

This shows a Firebase Performance custom trace around a user-visible flow, the @AddTrace annotation on a plain method, and reading ApplicationExitInfo on the next launch.

import android.app.ActivityManager
import android.app.ApplicationExitInfo
import android.content.Context
import android.os.Build
import com.google.firebase.Firebase
import com.google.firebase.perf.metrics.AddTrace
import com.google.firebase.perf.performance
import com.google.firebase.perf.trace
import kotlinx.serialization.json.Json
 
class FeedRepository(private val api: FeedApi, private val dao: FeedDao) {
 
    // One custom trace for the whole refresh, with a metric and a low-cardinality attribute.
    suspend fun refreshFeed(): Int =
        Firebase.performance.newTrace("feed_refresh").trace {
            val items = api.getFeed()        // also recorded automatically as a network request trace
            dao.replaceAll(items)            // Room suspend call, already main-safe
            putMetric("item_count", items.size.toLong())
            putAttribute("feed_type", "home") // never user IDs or emails
            items.size
        }
}
 
// @AddTrace instruments a regular (non-suspend) method at build time via the Performance plugin.
@AddTrace(name = "parse_remote_config")
fun parseRemoteConfig(json: String): RemoteConfigDto =
    Json.decodeFromString(RemoteConfigDto.serializer(), json)
 
/** Call from a background coroutine at startup; reports exits newer than the last one reported. */
fun reportExitReasons(context: Context, lastReported: Long, send: (String, Long) -> Unit): Long {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return lastReported
    val am = context.getSystemService(ActivityManager::class.java)
    val exits = am.getHistoricalProcessExitReasons(context.packageName, 0, 10)
        .filter { it.timestamp > lastReported }
    exits.forEach { info ->
        val reason = when (info.reason) {
            ApplicationExitInfo.REASON_ANR -> "anr"
            ApplicationExitInfo.REASON_CRASH -> "crash"
            ApplicationExitInfo.REASON_CRASH_NATIVE -> "crash_native"
            ApplicationExitInfo.REASON_LOW_MEMORY -> "low_memory"
            else -> "other_${info.reason}"
        }
        send(reason, info.timestamp)
    }
    return exits.maxOfOrNull { it.timestamp } ?: lastReported
}
  • Trace.trace { } starts and stops the trace around the block; because it is inline, the block can call suspend functions.
  • @AddTrace suits short synchronous methods. For suspend functions, use the trace { } helper so the trace covers the whole call.
  • The repository does not switch dispatchers for Room or Retrofit suspend calls; they are already main-safe.
  • The exit-reason reader filters by timestamp, because the system keeps a history of recent exits and returns the same records on every launch.

Run the idea in plain Kotlin

The same trace from two releases: release 2.1 is faster for most users, but a small group got much slower. The average moves a little; P95 shows how bad the slow tail became.

fun percentile(values: List<Long>, p: Int): Long {
  val sorted = values.sorted()
  val rank = Math.ceil(p / 100.0 * sorted.size).toInt().coerceAtLeast(1)
  return sorted[rank - 1]
}

fun report(release: String, durationsMs: List<Long>) {
  val avg = durationsMs.average().toLong()
  println(release + ": avg=" + avg + " ms, P50=" + percentile(durationsMs, 50) +
      " ms, P95=" + percentile(durationsMs, 95) + " ms")
}

fun main() {
  val release20 = listOf(410L, 420, 430, 440, 450, 460, 470, 480, 490, 500,
      510, 520, 530, 540, 550, 560, 570, 580, 900, 950)
  val release21 = listOf(300L, 310, 320, 330, 340, 350, 360, 370, 380, 390,
      400, 410, 420, 430, 440, 450, 460, 470, 2400, 2600)

  report("feed_refresh 2.0", release20)
  report("feed_refresh 2.1", release21)

  val p95Before = percentile(release20, 95)
  val p95After = percentile(release21, 95)
  if (p95After > p95Before * 1.2) println("Regression: P95 grew from " + p95Before + " to " + p95After + " ms")
}

Expected output:

feed_refresh 2.0: avg=538 ms, P50=500 ms, P95=900 ms
feed_refresh 2.1: avg=596 ms, P50=390 ms, P95=2400 ms
Regression: P95 grew from 900 to 2400 ms

In production

ANR rate rose after a sync change
  • A new release's user-perceived ANR rate in Android vitals rose clearly above the previous version during the staged rollout, mostly on low-RAM devices.
  • The crash rate was unchanged, so the crash dashboard looked healthy.
  • The new code parsed a large sync payload in a BroadcastReceiver callback, which runs on the main thread.
The fix
  • The ANR clusters in Play Console, and REASON_ANR traces read with ApplicationExitInfo.getTraceInputStream() on the next launch, showed the main thread inside the parser.
  • The receiver now enqueues a WorkManager job, and the worker parses on a background thread.
  • The team halted the rollout, shipped the fix as a new version and watched the ANR rate per version return to the previous level.
Excessive partial wake locks flagged after an update
  • Android vitals flagged excessive partial wake locks for the new version, and users reported battery drain.
  • The wake lock breakdown in vitals pointed to the app's own upload wake lock tag.
  • An upload helper acquired a PowerManager.WakeLock without a timeout and released it only on success, so a failed upload left it held.
The fix
  • The upload moved into a CoroutineWorker with a network constraint. WorkManager holds and releases its own wake lock while the work runs.
  • Where a manual wake lock was still needed, it is acquired with a timeout and released in a finally block.
  • The team watched the excessive wake lock metric for the next version during its staged rollout before completing it.

Common mistakes

  • Reading only averages. An average of about 500 ms can come from 90% of users at 10 ms and 10% at 5 seconds. Read P50 and P95 (or P90) per release.
  • Tracing everything. Hundreds of fine-grained traces add overhead and noise. Trace user-visible flows and add finer traces only while investigating.
  • Ignoring Android vitals until it is red. Crossing a bad behavior threshold can reduce your app's visibility on Play. Watch the trend per release, not just the status.
  • Testing only on fast devices and emulators. Low-end devices expose problems with startup, memory and main-thread work that flagship phones hide. Include a low-RAM device in local checks.
  • Comparing releases without the same population. Early staged-rollout users are random but few. Wait for enough sessions before trusting a percentile.
  • Putting PII in trace attributes or URLs. User IDs in custom attributes or query strings end up in a third-party dashboard. Use coarse values.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“How do you know whether a new release performs worse in production?”

“What is the difference between a crash and an ANR?”

“Why monitor P95 latency instead of the average?”

“How would you investigate a rise in memory-related exits?”

Quiz

What is the overall Android vitals bad behavior threshold for user-perceived ANR rate?

Which API tells your app, on the next launch, why its previous process ended?

Why are percentiles such as P95 preferred over averages for latency?

Which startup metric needs a call to reportFullyDrawn()?

0 of 4 answered

Mini task

Task: Build a release performance comparison

  1. Create a function percentile(values: List<Long>, p: Int): Long using the nearest-rank method.
  2. Create two lists of 20 durations each for a trace called screen_load, one for release A and one for release B. Make release B faster at the median but add two very slow values.
  3. Print the average, P50 and P95 for each release.
  4. Print "Regression" if release B's P95 is more than 20% higher than release A's, otherwise "OK".
  5. In a real app, add a Firebase Performance custom trace named screen_load around one screen's data load, run the app, and find the trace in the Firebase console.

Done condition: the program shows release B with a lower P50 but a higher P95 than release A, prints "Regression", and your custom trace appears in the Firebase Performance dashboard.

Next: Release health and alerting