DEV Community

Cover image for The Process That Vanished: A Field Guide to Android Memory Failures Under Per-App Limits
Android Expert
Android Expert

Posted on Originally published at Medium

The Process That Vanished: A Field Guide to Android Memory Failures Under Per-App Limits

Most Android crash reports come with a stack trace and a suspect. The failures in this post come with neither. The process is simply gone, or the app is alive but crawling, or a native crash lands thousands of instructions away from the code that caused it.

Android 17 raised the stakes by enforcing per-app memory limits that scale with device RAM. At the same time, Crashlytics has been growing tools aimed at exactly these blind spots: ANR insights, heap dumps for low-memory events, and GWP-ASan reports. This guide is how I would organize a team’s response: classify the failure first, pick the matching instrument, and avoid the traps that make each fix look finished when it is not.

It is inspired by the Android Dev Summit 2026 session on memory troubleshooting with Firebase Crashlytics, but the examples, code and opinions here are my own. Where a claim rests on a single third-party report, I say so.

memory-failure-landscape


1. What actually changed in Android 17

Until now, the only per-app memory ceiling most of us thought about was the Java heap limit. It is old, it varies by device, and it only covers one kind of memory.

Android 17 adds a system service, the Memory Limiter, that watches app processes through the Linux cgroup v2 hierarchy. Per the platform documentation, it sets limits by how visible a process is and by the device’s RAM tier, and it skips core system processes. The kernel-level mechanism is memory.high: when an app crosses it, the kernel reclaims clean file-backed pages and pushes cold anonymous pages out to swap so the process stays under its line. Under the standard platform configuration, devices below roughly 3.2 GiB of MemTotal, and devices at about 18 GiB or more, get no limits at all, and OEMs can ship their own tiers. There is no allowlist for individual apps, and apps cannot query their assigned limit at runtime.

Two consequences matter for how you debug.

The limit is about anonymous memory, not just the Java heap. Native buffers, direct ByteBuffers, bitmaps decoded to native memory, and library allocations all count. A flat Java heap does not prove you are safe.

The failure is a staircase, not a cliff. Before the kill there is a stretch where the app is slowed by reclaim and swap. Users experience it as jank, slow screens and ANRs, with no crash report at all.

memory-limiter-stages

Google’s own guidance frames the final stage bluntly: the system kills the process and there is no associated stack trace. That single fact is why the rest of this post leans on exit records and heap dumps instead of exceptions.

You can poke at this on a real device. The platform exposes adb shell am memory-limiter status to inspect the current limits, plus subcommands to ignore or manually set limits on a process. They do nothing on devices that impose no limits, so check status first.


2. Triage before tooling

The most expensive habit in stability work is opening the heap profiler because the word “memory” appeared in a ticket. Start with two questions: is there an app-level stack trace, and if not, what does the OS say about how the process ended?

triage-decision-tree

Everything below hangs off that tree. We will take the branches in the order they usually cost teams the most time.


3. ANRs: ask what the main thread was waiting for

input-anr-anatomy

An input ANR means the main thread did not respond to a touch or key event within about five seconds. The instinct is to hunt for slow computation. In production, the usual culprit is a wait: a lock held by a background thread, a disk read on a cold cache, or a synchronous call across a process boundary.

That reframing changes what you read in a main-thread trace. Look at the top frames and ask what they are blocked on, then follow that dependency to the other thread or process.

Failure mode: blocking startup on the network

The classic version is an Application.onCreate that waits for remote configuration before the first screen can draw:

// Anti-pattern: the main thread now depends on the network
class ShopApp : Application() {
    override fun onCreate() {
        super.onCreate()
        val flags = runBlocking { configClient.fetchFlags() } // can wait for a long time
        FeatureFlags.install(flags)
    }
}
Enter fullscreen mode Exit fullscreen mode

On a good network this passes every test. On a captive portal or a flaky radio it freezes launch. The fix is to make the default state usable and let the real value arrive later, observable and cancellable:

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import com.google.firebase.Firebase
import com.google.firebase.crashlytics.crashlytics

class FeatureGate(
    scope: CoroutineScope,
    private val fetch: suspend () -> Map<String, Boolean>,
) {
    private val _flags = MutableStateFlow(DEFAULTS)
    val flags: StateFlow<Map<String, Boolean>> = _flags.asStateFlow()

    init {
        scope.launch {
            try {
                // A hung fetch must not linger in a long-lived scope; keep defaults on timeout
                withTimeoutOrNull(FETCH_TIMEOUT_MS) { fetch() }
                    ?.let { _flags.value = DEFAULTS + it }
            } catch (e: CancellationException) {
                throw e // never swallow cancellation
            } catch (e: Exception) {
                Firebase.crashlytics.recordException(e) // keep defaults, report once
            }
        }
    }

    private companion object {
        const val FETCH_TIMEOUT_MS = 5_000L
        val DEFAULTS = mapOf("new_checkout" to false, "image_prefetch" to true)
    }
}
Enter fullscreen mode Exit fullscreen mode

Three details deserve attention. The timeout matters because this coroutine lives in whatever scope the caller passes, and a fetch that never returns would otherwise live as long as that scope. (Use withTimeoutOrNull here: withTimeout throws a CancellationException subclass, which the handler below would rethrow and swallow silently.) Catching Exception without rethrowing CancellationException is a quiet bug that turns scope cancellation into a normal-looking failure. And the defaults must be genuinely safe, because for a while they are the only truth the app has.

Failure mode: the ANR that is secretly a memory problem

If ANR reports cluster on low-RAM devices and show the main thread waiting on page faults or I/O, treat them as possible Memory Limiter symptoms rather than threading bugs. A process under reclaim pressure gets slower at everything. Cross-check the ANR cohort against device RAM tier before you spend a week on lock ordering.


4. Out-of-memory errors and heap dumps

A Java OutOfMemoryError is the friendlier cousin of a limiter kill: it throws, so you get a trace. The trace points at whichever allocation happened to fail, which is rarely the code that leaked. It is the last straw, not the camel.

This is where a heap dump earns its keep. For out-of-memory crashes and Memory Limiter kills, Crashlytics can collect heap dumps and store them in Cloud Storage, and the Android CLI can list, describe and download them as Perfetto traces. At the time of writing, heap dump collection is offered through an early access program, so check availability for your project before building a process around it.

heap-dump-workflow

A typical session looks like this:

# See what low-memory events your app produced this week
android signals heaps list --firebase-app=<app-id> --kind=all --timeframe=7d

# Read the custom keys and logs from the same crashed session
android signals heaps describe firebase/<heap-id> --firebase-app=<app-id>

# Pull the dump locally as a Perfetto trace
android signals heaps download firebase/<heap-id> --output=./heaps --firebase-app=<app-id>
Enter fullscreen mode Exit fullscreen mode

Once the trace is open, sort by retained size, not shallow size. A small object that pins a big graph is the usual villain, and the path from that object to a GC root is your explanation.

Failure mode: heap dumps are user data

A heap dump is a snapshot of process memory. It can contain auth tokens, message text, form input and anything else that was live. Before enabling collection, decide who can download dumps, how long they are retained, and whether your privacy disclosures cover it. Scrub secrets from memory where you can, and do not treat the dump as a debugging artifact that lives outside your data-handling rules.

Failure mode: a cache sized by count

Heaps do not fill because of one giant object. They fill because a collection has no budget. An LruCache created with an entry count looks bounded, but ten thousand small entries and ten thousand decoded images are very different bills.

import android.app.ActivityManager
import android.content.Context
import android.util.LruCache
import androidx.core.content.getSystemService

/** An LruCache that is bounded in bytes, not in entries. */
class ByteBudgetCache<K : Any, V : Any>(
    maxBytes: Int,
    private val weigh: (V) -> Int,
) : LruCache<K, V>(maxBytes) {
    override fun sizeOf(key: K, value: V): Int = weigh(value).coerceAtLeast(1)
}

fun Context.imageCacheBudgetBytes(): Int {
    val classMb = getSystemService<ActivityManager>()?.memoryClass ?: 64
    return (classMb * 1024 * 1024) / 8 // an eighth of the heap class, as an upper bound
}
Enter fullscreen mode Exit fullscreen mode

Treat that budget as a ceiling, not a guarantee. The heap class only describes Java heap headroom, and the new limit covers more than the heap. Pair the cache with a trim listener so it shrinks when the system asks:

import android.content.ComponentCallbacks2
import android.content.res.Configuration
import android.util.LruCache

class CacheTrimmer(private val cache: LruCache<*, *>) : ComponentCallbacks2 {
    override fun onTrimMemory(level: Int) {
        when {
            level >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE -> cache.evictAll()
            level >= ComponentCallbacks2.TRIM_MEMORY_BACKGROUND -> cache.trimToSize(cache.size() / 2)
            level >= ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN -> cache.trimToSize(cache.size() * 3 / 4)
        }
    }

    override fun onConfigurationChanged(newConfig: Configuration) = Unit
    override fun onLowMemory() = cache.evictAll()
}

// In Application.onCreate:
// registerComponentCallbacks(CacheTrimmer(imageCache))
Enter fullscreen mode Exit fullscreen mode

Failure mode: the listener that outlives its screen

The other common leak is a long-lived object holding a reference to something short-lived. A process-wide singleton that accepts callbacks and never drops them will retain every screen that ever registered.

// Anti-pattern: every registered lambda pins its Activity forever
object PriceTicker {
    private val listeners = mutableListOf<(Price) -> Unit>()
    fun register(listener: (Price) -> Unit) { listeners += listener }
}
Enter fullscreen mode Exit fullscreen mode

A lifecycle-aware stream removes the bookkeeping, because collection stops and the reference disappears with the lifecycle:

import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.*

object PriceTicker {
    private val _prices = MutableSharedFlow<Price>(
        replay = 1,
        onBufferOverflow = BufferOverflow.DROP_OLDEST,
    )
    val prices: SharedFlow<Price> = _prices.asSharedFlow()

    fun publish(price: Price) { _prices.tryEmit(price) }
}

// In a Fragment (needs these imports)
// import androidx.lifecycle.Lifecycle
// import androidx.lifecycle.lifecycleScope
// import androidx.lifecycle.repeatOnLifecycle
// import kotlinx.coroutines.launch
viewLifecycleOwner.lifecycleScope.launch {
    viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
        PriceTicker.prices.collect(::render)
    }
}
Enter fullscreen mode Exit fullscreen mode

Even this has a trap. replay = 1 keeps the last value alive for the life of the process. If Price carries a large payload, you have replaced a listener leak with a payload leak.


5. Memory Limiter kills: reading the process’s last words

With no stack trace, the evidence lives in the OS’s exit records. ActivityManager.getHistoricalProcessExitReasons returns ApplicationExitInfo entries for your app's recent process deaths, including a reason code, a description and memory figures. Read them on the next launch and ship the interesting ones to your crash backend.

One update before the code. Early write-ups from third-party SDK vendors said limiter kills surface as REASON_OTHER with a marker in the description. The current ApplicationExitInfo reference now lists a dedicated REASON_MEMORY_LIMITER constant (value 17, added in SDK 37.2), alongside REASON_ANOMALY. Prefer the constant where it exists. Keep the description match only as a fallback for older builds, and treat it as a heuristic. Always log the raw description alongside your verdict so you can revise the rule later.

import android.app.ActivityManager
import android.app.ApplicationExitInfo
import android.content.Context
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.content.getSystemService
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

sealed interface ExitVerdict {
    data class MemoryPressure(val pssKb: Long, val rssKb: Long, val raw: String) : ExitVerdict
    data class Hang(val raw: String) : ExitVerdict
    data class NativeCrash(val raw: String) : ExitVerdict
    data object Benign : ExitVerdict
}

// ApplicationExitInfo.REASON_MEMORY_LIMITER (17) exists from SDK 37.2. If you compile against
// an older SDK, mirror the value locally; on newer SDKs, use the platform constant instead.
private const val REASON_MEMORY_LIMITER = 17

@RequiresApi(Build.VERSION_CODES.R)
fun ApplicationExitInfo.toVerdict(): ExitVerdict {
    val text = description.orEmpty()
    return when (reason) {
        ApplicationExitInfo.REASON_LOW_MEMORY,
        ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE,
        REASON_MEMORY_LIMITER -> ExitVerdict.MemoryPressure(pss, rss, text) // both pss and rss are in kB
        ApplicationExitInfo.REASON_OTHER -> // fallback heuristic for builds without the dedicated reason
            if (text.contains("MemoryLimiter", ignoreCase = true)) {
                ExitVerdict.MemoryPressure(pss, rss, text)
            } else ExitVerdict.Benign
        ApplicationExitInfo.REASON_ANR -> ExitVerdict.Hang(text)
        ApplicationExitInfo.REASON_CRASH_NATIVE -> ExitVerdict.NativeCrash(text)
        else -> ExitVerdict.Benign
    }
}

interface ExitCursorStore {
    suspend fun read(): Long
    suspend fun write(timestamp: Long)
}

@RequiresApi(Build.VERSION_CODES.R)
class ExitReporter(
    private val context: Context,
    private val cursor: ExitCursorStore,
    private val sink: (ExitVerdict, ApplicationExitInfo) -> Unit,
    private val io: CoroutineDispatcher = Dispatchers.IO,
) {
    suspend fun reportNew() = withContext(io) {
        val am = context.getSystemService<ActivityManager>() ?: return@withContext
        val seen = cursor.read()
        val fresh = am.getHistoricalProcessExitReasons(context.packageName, 0, 20)
            .filter { it.timestamp > seen }
            .sortedBy { it.timestamp }

        fresh.forEach { info -> sink(info.toVerdict(), info) }
        fresh.lastOrNull()?.let { cursor.write(it.timestamp) }
    }
}
Enter fullscreen mode Exit fullscreen mode

The details that keep this from becoming a new problem:

  • Run it off the main thread. Reading exit records is I/O. Doing it inline in Application.onCreate would be an ironic way to cause an ANR.
  • Keep a timestamp cursor. Without it you will report the same death on every launch and inflate your own numbers.
  • Sort before you advance the cursor. If you store a timestamp from an unsorted list, you can skip real events.
  • Filter benign exits. Users swiping the app away and the OS reclaiming cached processes are not incidents.

Give the dump a story with custom keys

An anonymous dump says what was in memory. Custom keys say what the app was doing. Record cheap, bounded context at moments that matter, such as screen transitions or the start of a heavy pipeline.

import android.app.ActivityManager
import android.content.Context
import android.os.Debug
import androidx.core.content.getSystemService
import com.google.firebase.Firebase
import com.google.firebase.crashlytics.crashlytics

fun recordMemoryContext(context: Context, screen: String) {
    val system = ActivityManager.MemoryInfo().also {
        context.getSystemService<ActivityManager>()?.getMemoryInfo(it)
    }
    val runtime = Runtime.getRuntime()

    Firebase.crashlytics.apply {
        setCustomKey("screen", screen)
        setCustomKey("java_heap_mb", (runtime.totalMemory() - runtime.freeMemory()) shr 20)
        setCustomKey("native_heap_mb", Debug.getNativeHeapAllocatedSize() shr 20)
        setCustomKey("system_avail_mb", system.availMem shr 20)
        setCustomKey("system_low_memory", system.lowMemory)
    }
}
Enter fullscreen mode Exit fullscreen mode

getNativeHeapAllocatedSize() counts only the native (malloc) heap, so it will miss graphics, binder and some mapped memory. Treat it as a trend line, and pair it with Debug.getPss() if you need a closer match to what the limiter sees. Do not call this in a tight loop, and do not log user content in keys. Crashlytics limits how many keys a report can hold, so spend them on the dimensions you will actually filter by.


6. Native memory growth with a flat Java heap

When total memory climbs but the Java heap does not move, the allocator you are fighting lives below the JVM. Common sources include direct buffers, image and video codecs, ML runtimes and third-party native libraries.

Kotlin code can create this problem without a line of C++. A direct buffer allocated per frame is a textbook case: each small Java object is cheap, but its backing memory is native and is only released when the garbage collector gets around to the owner.

// Anti-pattern: native memory churn that the Java heap graph will not reveal
fun processFrame(width: Int, height: Int): ByteBuffer {
    val buffer = ByteBuffer.allocateDirect(width * height * 4)
    // ... fill and hand off ...
    return buffer
}
Enter fullscreen mode Exit fullscreen mode

Pool and reuse instead, and make the ceiling explicit:

import java.nio.ByteBuffer

class FrameBufferPool(
    private val frameBytes: Int,
    private val capacity: Int = 3,
) {
    private val free = ArrayDeque<ByteBuffer>()

    @Synchronized
    fun acquire(): ByteBuffer =
        // clear() resets position and limit only; contents are NOT zeroed, so overwrite before reuse
        (free.removeLastOrNull() ?: ByteBuffer.allocateDirect(frameBytes)).apply { clear() }

    @Synchronized
    fun release(buffer: ByteBuffer) {
        if (free.size < capacity) free.addLast(buffer)
    }
}
Enter fullscreen mode Exit fullscreen mode

The failure mode here is trusting a Java heap dump to explain a native problem. A heap dump shows the small owner objects, not the megabytes behind them. For this class of bug, correlate the native_heap_mb key from the previous section with release versions and screens, then use native allocation profiling on a reproducing device.


7. Native corruption: when the crash is a decoy

Heap corruption is the nastiest class. A buffer overflow or use-after-free writes to memory it should not touch, and the process crashes later, somewhere unrelated. The stack trace blames innocent code.

GWP-ASan is a sampling allocator that traps these bugs at the moment of misuse for a small fraction of allocations. The result is a crash report pointing at the real offending access, with allocation and deallocation stacks. You opt in per app on Android 11 and later:

<application
    android:gwpAsanMode="always"
    ... >
</application>
Enter fullscreen mode Exit fullscreen mode

Crashlytics can collect these reports so you can triage them alongside everything else.

Failure mode: reading silence as safety

GWP-ASan samples, so it sees a slice of allocations, not all of them. No reports in a week does not mean no bugs. It means the sampled slice did not trip, so you need enough sessions to give a rare bug a chance. Also remember that memory-safety bugs are often security bugs, so route confirmed reports through the same channel you use for vulnerabilities.


8. A field checklist of mistakes worth naming

These are the traps I see most often, collected in one place.

  • Catching OutOfMemoryError and carrying on as if nothing happened. Allocating in the handler, such as building an error dialog or a big log string, can throw again. Free something first, retry at most once at reduced quality, and then fail visibly.
  • Fixing the throw site of an OOM. The failing allocation is rarely the leak. Go to the dominator tree.
  • Sizing caches by entry count. Bound by bytes, and trim on onTrimMemory.
  • Treating the Java heap class as the whole budget. The limiter counts native and anonymous memory too.
  • Holding a privileged state longer than needed. A foreground service that keeps a large working set gets less benefit of the doubt under per-app enforcement than it once did, so release big structures when idle.
  • Swallowing CancellationException. It converts cooperative cancellation into mysterious half-finished work.
  • Reporting exit reasons on every launch without a cursor. You will drown real signals in repeats.
  • Matching a description string as if it were an API. Log the raw text and expect the rule to change.
  • Collecting heap dumps without a data-handling plan. Treat them as sensitive from day one.
  • Reading a quiet GWP-ASan dashboard as a clean bill of health. Sampling needs volume.

9. A rollout plan you can start Monday

  1. Instrument first. Ship the exit-record reporter and the memory custom keys. They are cheap and they give every later investigation a baseline.
  2. Segment by device RAM tier. Memory problems hide inside averages. A healthy overall rate can conceal a failing low-RAM cohort.
  3. Test under limits. On a device that imposes them, use am memory-limiter status and your heaviest user journeys, then watch for slowdowns as well as kills.
  4. Budget your caches and buffers. Replace unbounded collections with byte-bounded ones and add trim handling.
  5. Enroll in heap dump collection if you can. Decide retention and access before the first dump arrives.
  6. Enable GWP-ASan on a slice of users. Pick a rollout that gives rare bugs room to show up.
  7. Revisit after each release. Memory behavior regresses silently, so compare per-version limiter and OOM rates the way you compare crash-free sessions.

🔚 Closing thought

Per-app memory limits make an old truth harder to ignore: memory is a budget your app spends over its entire session, not a number you check in a profiler once. The tooling is finally catching up to that reality, with exit records for the deaths that leave no trace, heap dumps for the leaks that hide behind innocent stack frames, and sampling allocators for the corruption that crashes far from home.

The skill is in the sequence. Classify the failure, pick the instrument that matches its fingerprint, and be honest about what each tool cannot see.


Sources


📱 Go Beyond Using AI — Learn How to Actually Build It Into Your Android Apps

If you’re building Android apps in 2026, “adding AI” can’t just mean bolting on a chatbot API — it means understanding on-device inference, model trade-offs, and production realities well enough to ship a feature users actually trust. I highly recommend “Mastering Android AI: App to Intelligence” It’s a practical, code-first journey through the entire Android AI stack — from ML Kit and LiteRT to Gemma, Gemini, and MediaPipe — covering everything from your first “hello inference” screen to thermal throttling, model drift monitoring, and full applied projects like an AI-powered camera app and a health companion, with hands-on Kotlin builds at every step.

Top comments (0)