Hacker News

Finding and fixing Android memory leaks with Perfetto, SQL, and AI agents

A single unregistered callback in an Android app can quietly pin an entire destroyed Fragment, its view hierarchy, and tens of megabytes of decoded Bitmap buffers in memory. Do that a few times across navigation transitions and a smooth experience turns into aggressive garbage collection pauses, background process kills (lmkd), or an outright OutOfMemoryError.

Every complex, asynchronous application encounters memory leaks sooner or later. Modern Android apps juggle overlapping lifecycles: Activities, Fragments, Compose UI trees, ViewModels, coroutine scopes, hardware callbacks, and window-level observers. When any two of those lifecycles fall out of sync, memory stays reachable long after its work is done.

At Google, I work on Android platform system health. To keep our own applications and the broader Android ecosystem fast and reliable, my colleagues and I built a comprehensive suite of memory profiling and analysis tools directly into Perfetto, and we open-sourced the entire stack so every developer can use the exact same workflows.

In this post, I will walk through how to hunt down Android memory leaks across four complementary layers of the Perfetto ecosystem:

  • Capturing heap profiles on any Android device with zero app code changes.
  • Interactive visual forensics in the Perfetto Web UI using the Heap Dump Explorer, dominator flamegraphs, and bitmap metadata inspectors.
  • Programmatic analysis with PerfettoSQL, from ad-hoc queries in the browser to automated local CI checks with trace_processor and fleet-wide analysis across thousands of traces with BigTrace.
  • Agentic root-cause analysis using the open-source Perfetto AI Skill, where coding agents combine heap graph queries with repository-wide code search and automated test generation to diagnose, fix, and verify memory leaks end to end.

What makes Perfetto different as a heap analyzer

If you have debugged Java memory leaks before, you have likely used standard JVM .hprof snapshots. Traditional HPROF dumps serialize every primitive field and byte array payload in the process, producing massive files that are slow to transfer and disconnected from what the rest of the operating system was doing when memory spiked. (If you want a refresher on how Android and the Linux kernel account for virtual memory areas, anonymous pages, RSS, PSS, and swap, see the Debugging memory usage on Android case study.)

Perfetto approaches memory analysis differently:

  • Lightweight reference graphs (android.java_hprof): Rather than dumping raw primitive contents, Perfetto's ART heap profiler records the complete object retention graph: every live Java/Kotlin object, its class, its shallow size, its native allocation size (via libcore.util.NativeAllocationRegistry), and the exact named member fields connecting owners to referents. Because no string payloads or pixel buffers leave the process, it is fast, privacy-safe, and works on non-debuggable builds. (When you do need full primitive/bitmap pixel contents on a debuggable build, Perfetto also imports standard ART .hprof files.)
  • Unified timeline context (Memory Counters): Because a heap snapshot is just one data source in a Perfetto trace, you can correlate object retention directly against kernel memory counters (anon_rss, swap, oom_score_adj), CPU scheduling slices, GC pauses, and app lifecycle events on the exact same timeline.
  • Java and Native (heapprofd) under one roof: Android memory pressure frequently crosses the JNI boundary. A tiny 64-byte Kotlin wrapper object might retain a 24 MB native hardware buffer. Perfetto lets you inspect both ART object retention graphs and native C/C++ callstack allocations or ART allocation profiles in a single tool.

Anatomy of real-world Android memory leaks

Before opening a trace, it helps to recognize the structural patterns that cause memory leaks in production Android code. Across hundreds of investigations, almost every memory issue falls into one of six recurring engineering patterns.

Lifecycle mismatch in callback registries

Short-lived UI components frequently register callbacks on longer-lived registries without binding the registration to their own lifecycle.

// LEAK: Registered on the Activity's registry without passing a LifecycleOwner.
// The Activity outlives the Fragment and retains the callback (and Fragment) indefinitely.
class PhotoAttachmentLauncher(private val fragment: Fragment) {
  private lateinit var launcher: ActivityResultLauncher
  fun init() {
    launcher = fragment.requireActivity().activityResultRegistry.register(
      "pick_photo", ActivityResultContracts.GetContent(), ::onPhotoPicked
    )
  }
}

In Kotlin and Java, method references (::onPhotoPicked) and lambdas implicitly capture their enclosing this reference (PhotoAttachmentLauncher), which in turn holds a strong reference to the destroyed Fragment and its entire view hierarchy.

// FIX: Use the Fragment's lifecycle-aware registration API so the callback
// is automatically unregistered when the Fragment is destroyed.
class PhotoAttachmentLauncher(private val fragment: Fragment) {
  private val launcher = fragment.registerForActivityResult(
    ActivityResultContracts.GetContent(), ::onPhotoPicked
  )
}

The example code above was inspired by a real bug in Google Messages that our engineers found with Perfetto.

Window-root vs. local view scope mismatches

A subtle variation occurs when helper functions attach listeners to window-level roots, such as activity.window.decorView or a window-shared ViewTreeObserver, to update a short-lived child view or Fragment.

// LEAK: decorView lives as long as the Activity, retaining the listener lambda
// which captures 'this' (a short-lived RecyclerView inside a Fragment).
fun View.applyNavigationBarPadding(decorView: View) {
  ViewCompat.setOnApplyWindowInsetsListener(decorView) { _, insets ->
    updatePadding(bottom = insets.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom)
    insets
  }
}

Attaching the listener directly to the target View (or removing window-level observers inside view.doOnDetach { ... }) ensures the callback's lifetime never exceeds the view it updates:

// FIX: Scope the insets listener directly to the target view.
fun View.applyNavigationBarPaddingSafe() {
  ViewCompat.setOnApplyWindowInsetsListener(this) { _, insets ->
    updatePadding(bottom = insets.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom)
    insets
  }
}

Based on a real leak in YouTube.

Unbounded asset retention in long-lived listeners

When a component registers itself with a long-lived service or singleton cache and stores decoded Bitmap instances without an eviction ceiling or lifecycle teardown, a small structural leak quickly balloons into hundreds of megabytes.

// FIX: Implement Closeable (or bind to Lifecycle) to unregister listeners
// and release heavy graphics buffers immediately on teardown.
class ThemePreviewController(
  private val themeService: ThemeService
) : Closeable {
  private var previews: List = emptyList()
  init {
    themeService.addListener(this)
  }
  override fun close() {
    themeService.removeListener(this)
    previews = emptyList()
  }
}

Based on a real leak in the Pixel Watch companion app.

Cancelled asynchronous teardowns

One of the trickiest modern Kotlin leaks happens when cleanup code is launched inside a coroutine scope that gets cancelled at the exact same moment:

// LEAK: When the Fragment is destroyed, uiScope is cancelled immediately.
// The launched coroutine is aborted before cameraController.unbind() executes!
fun onClose() {
  uiScope.launch { cameraController?.unbind() }
}

Because uiScope is cancelled as part of teardown, the cleanup coroutine throws CancellationException before unbind() runs, leaving hardware buffers and preview surfaces pinned in memory. Wrapping critical teardown work in NonCancellable guarantees completion:

// FIX: Run asynchronous teardown under NonCancellable so cleanup finishes
// even when the parent UI scope is being cancelled.
fun onClose() {
  uiScope.launch(NonCancellable) { cameraController?.unbind() }
}

Based on a real leak in Google Camera.

Executor queue backlogs and reactive allocation churn

Not every memory spike is a permanent reference leak:

  • Executor queue bloat: When slow disk or database I/O blocks a single-threaded executor, thousands of pending lambdas accumulate in unbounded task queues, retaining every string or context captured in their closures. Using bounded queues (LinkedBlockingQueue(capacity)) and isolating slow I/O onto dedicated pools prevents runaway heap growth. (Based on a real issue in Google Photos.)
  • Reactive stream churn: Chaining multi-step collection transformations (list.filter { ... }.groupBy { ... }.mapValues { ... }) inside high-frequency Kotlin Flow emissions allocates dozens of intermediate lists and maps per frame. Flattening hot paths into single-pass loops and caching decoded immutable models eliminates hundreds of megabytes of hourly garbage collection churn. (Based on a real issue in Google Home.)

Three ways to capture heap profiles with Perfetto

You do not need to modify your app's build files or add runtime dependencies to capture a heap profile. Perfetto provides three ways to record memory snapshots depending on your workflow (see Recording Android traces locally for the full cookbook).

Quick capture with official CLI helper scripts

The fastest way to capture a Java heap dump or native heap profile from a connected Android device is with the standalone helper scripts in the Perfetto repository:

# Download the official helper scripts
curl -O https://raw.githubusercontent.com/google/perfetto/main/tools/java_heap_dump
curl -O https://raw.githubusercontent.com/google/perfetto/main/tools/heap_profile
chmod +x java_heap_dump heap_profile
# 1. Capture an ART Java/Kotlin heap graph snapshot
./java_heap_dump -n com.example.myapp -o ./heap_dump.perfetto-trace
# 2. Or profile C/C++ native heap allocations (heapprofd)
./heap_profile -n com.example.myapp -o ./native_profile_dir

You can also pass --wait-for-oom to java_heap_dump to automatically capture a snapshot at the exact moment an OutOfMemoryError is thrown (see the OOM heap dump guide).

Browser-based recording and live monitoring with Memscope

If you prefer a graphical workflow:

  • Open ui.perfetto.dev in Chrome or Edge and click Record new trace in the left sidebar.
  • Connect your Android device via WebUSB or ADB.
  • Under Memory, enable Java heap dumps (and optionally Native heap profiling) and enter your target package name (for example, com.example.myapp).
  • Click Start Recording, exercise the user journey in your app, and let the trace open automatically in the browser.

If you are not yet sure which process is leaking, try Memscope in the Perfetto sidebar: it connects to your device over WebUSB, displays live per-process anon_rss + swap sparklines in real time, and lets you click Profile on any growing process to record periodic ART heap dumps, smaps snapshots, and native heap profiles with a single click.

Custom multi-source TraceConfig for timeline correlation

When investigating complex regressions, you often want a heap dump plus continuous process RSS, swap, and /proc/[pid]/smaps counters in the same trace. You can combine android.java_hprof with linux.process_stats in a single .pftxt trace configuration:

buffers: { size_kb: 65536 fill_policy: DISCARD }
# Periodically record RSS, swap, and oom_score_adj for timeline correlation
data_sources: { config { name: "linux.process_stats" process_stats_config { scan_all_processes_on_start: true proc_stats_poll_ms: 250 } } }
# Capture the ART Java/Kotlin object retention graph + smaps breakdown
data_sources: { config { name: "android.java_hprof" java_hprof_config { process_cmdline: "com.example.myapp" dump_smaps: true } } }
duration_ms: 10000

Record the combined trace with record_android_trace:

curl -O https://raw.githubusercontent.com/google/perfetto/main/tools/record_android_trace
chmod +x record_android_trace
./record_android_trace -c memory_config.pftxt -o combined_memory.perfetto-trace

Interactive visual forensics in the Perfetto Web UI

When you open a trace containing a Java heap dump in ui.perfetto.dev, Perfetto surfaces memory data in two places: on the timeline tracks and inside the dedicated Heap Dump Explorer (as well as the Memory Overview page if your trace includes smaps snapshots).

Finding the heap snapshot on the timeline

In the timeline view, expand your application's process track group. You will see an ART heap dump track containing a diamond marker for each captured snapshot:

Clicking any diamond marker opens the interactive flamegraph panel for that exact point in time.

Reading the Heap Dump Explorer and Flamegraph

The Heap Dump Explorer (accessible from the left sidebar or via Open in Heapdump Explorer on any flamegraph node) combines Overview, Flamegraph, Classes, Objects, Dominators, Bitmaps, Strings, Arrays, and OOM Callstack tabs in one workspace:

When reading a heap flamegraph in Perfetto, keep three key concepts in mind:

  • Self Size vs. Dominated (Retained) Size: If you sort raw heap objects by Object Size along shortest paths, the top entries in almost every Android app will be byte[], java.lang.String, int[], and java.lang.Object[]. That tells you what the bytes are made of, not why they are alive. Switching the metric dropdown to Dominated Object Size reorganizes the flamegraph around the dominator tree so that each node's width represents the exact memory that would be freed if that object became unreachable.
  • Spotting the "Leak Column" (and pivoting on suspects): In a healthy heap, retained memory fans out broadly across independent subsystems. In a memory leak, you will see a tall, un-narrowing column descending from a GC root (such as ViewRootImpl, an ActivityResultRegistry, or a static singleton) straight into dozens of retained Fragment, View, or custom controller instances. You can also use the filter
Read on Hacker News ↗ ← Back to News

Comments

No comments yet. Start the discussion.