On-Device LLMs for Mobile AI Agents: Architecture Choices and a Post-Mortem of What Went Wrong

    This post-mortem walks through the three engineering problems that decide whether an on-device LLM agent on a phone is actually usable: stability, performance, and concurrency. It explains why a popular community cross-platform plugin triggered device-level reboots instead of ordinary app crashes, and how replacing it with the official native inference engine fixed the problem; how to structure the engine and conversation lifecycle with a single long-lived engine instance; and how to serialize and prioritize concurrent agents competing for one GPU. It also includes a model-selection table, a troubleshooting order, and a reusable pre-launch checklist.

    Why put an LLM on the phone in the first place

    In on-device AI products, “fully offline” is increasingly treated as a feature rather than a fallback. It means the user’s personal data never leaves the device, which sidesteps privacy compliance risk; the product keeps working with no network; and you avoid cloud inference cost and latency jitter. For an application centered on local life logging and personal knowledge management, shipping its own LLM — especially letting users pick their own model — is a genuinely competitive capability.

    A recent wave of open-source small models optimized for mobile (typically in the 2–4 billion parameter range, combined with quantization and memory mapping) has made this practical: weights are small enough to control, the model fits into phone RAM or GPU memory, and inference latency lands within acceptable bounds.

    But being able to “get the model running” is not the finish line, and treating it as one tends to hide the real engineering work: stability, performance, and concurrency. This post-mortem is organized around those three.

    Step 1: Watch out for the stability trap in community wrapper layers

    The easiest path is to pull in an existing cross-platform plugin. It wraps the underlying on-device inference engine, exposes a tidy API, and you are running in a few lines of code. That works fine for a prototype. Then, after running on real devices for an extended period, I hit a serious problem: the whole device occasionally rebooted — not just the app crashing.

    That distinction matters. An app crash is an application-layer exception; you can catch it and recover. A device reboot usually means a native call triggered a kernel- or driver-level fault, and the application layer never gets a chance to compensate. It is worth being precise about attribution here: I am not claiming every wrapper layer is necessarily defective. Findings like this need a complete evidence chain before you draw conclusions:

    • Write down the reproduction conditions. It reproduced only on a specific device model, a specific OS version, and a specific wrapper version; changing the device or the version made it disappear.
    • Keep the logs. Capture kernel logs, crash tombstones, and the wrapper’s call sequence so the evidence can be compared side by side.
    • Run a controlled experiment to isolate responsibility. On the same phone, with the same model file and the same OS version: the official reference sample app (calling the native API directly) ran stably, while the community cross-language wrapper reproduced the reboot. With the dependency chain, model file, and hardware all held constant, the only variable left is the extra cross-language bridge (Dart-to-Kotlin communication). That points to the wrapper’s handling of memory management, thread scheduling, or native object lifetime as the likely culprit — not as a universal rule.

    Risk and operations guidance. In on-device AI, where memory and threads are extraordinarily sensitive, a native call can cause more than an app crash: device reboot, overheating, battery drain, even data becoming inaccessible. So:

    • Run high-risk validation on backed-up devices and user data, so nothing becomes unrecoverable.
    • Ship the capability through gradual rollout, validating on a small percentage of users first.
    • Tell users up front that the local model consumes compute and may cause heat and battery drain.
    • Keep a kill switch: when something breaks, fall back to a cloud model in one step, or disable the local model entry point entirely.

    The lesson. The abstraction convenience of a community wrapper can come at the cost of stability. In production, be willing to bypass the wrapper and go back to the official native API — and let controlled experiments plus log evidence make the argument, rather than piling try-catch blocks in the application layer.

    Step 2: Go native and rebuild the call chain

    Once I dropped the wrapper, I built my own bridge layer directly on the official on-device inference library (the native Kotlin dependency on Android). The architecture went from an opaque cross-language plugin to a transparent, layered call chain:

    1. Dart (business / Agent layer)
    2. │ MethodChannel / Platform Channel
    3. ▼
    4. Kotlin bridge plugin (Plugin)
    5. │ direct calls
    6. ▼
    7. Official on-device inference engine (Engine)

    The core design is one global engine instance with conversations created on demand. Loading model weights is a heavyweight operation — moving multiple gigabytes of weights into GPU memory takes time and consumes resources — so it must never be repeated per inference. Each conversational turn, by contrast, should be a lightweight, short-lived object.

    Production code cannot stop at the happy path, though. Permissions, validation, fallback, initialization failure, and resource release all have to be handled up front:

    1. // 0. Permissions and file validation: Android requires runtime permissions declared in the Manifest;
    2. // the model file must exist and be non-empty, or initialization crashes outright
    3. val modelFile = File(modelPath)
    4. require(modelFile.exists() && modelFile.length() > 0) {
    5. "Model file missing or empty: $modelPath"
    6. }
    7. // 1. Backend selection: fall back to CPU when GPU is unavailable instead of
    8. // throwing an exception that would crash the app
    9. val backend = runCatching { Backend.GPU() }
    10. .getOrElse {
    11. Log.w(TAG, "GPU unavailable, falling back to CPU", it)
    12. Backend.CPU()
    13. }
    14. // 2. Initialize the engine globally, once. Handle failures explicitly and trigger a fallback.
    15. val engine = try {
    16. Engine(EngineConfig(
    17. modelPath = modelPath,
    18. backend = backend,
    19. maxNumTokens = 10000, // context limit; must match device memory
    20. cacheDir = context.cacheDir.absolutePath,
    21. )).also { it.initialize() }
    22. } catch (t: Throwable) {
    23. Log.e(TAG, "Engine initialization failed, falling back to cloud model", t)
    24. null // upper layer switches to the cloud provider or disables the local model entry point
    25. }
    26. // 3. Per-conversation temporary object; use ensures close/release even on exceptions
    27. engine?.createConversation(config)?.use { conversation ->
    28. conversation.sendMessageAsync(userText).collect { token ->
    29. // Stream tokens back one by one so the UI can render a typewriter effect
    30. }
    31. }
    32. // 4. The engine is a global singleton and should be released explicitly on app exit
    33. // or on memory-pressure warnings
    34. // engine?.release()

    This “heavyweight long-lived asset, short-lived per-conversation objects” pattern matches the official reference app. After switching to it, inference speed returned to normal and the device reboots stopped.

    The bigger win is maintainability. On the Dart side, I implemented the local model client against exactly the same LLMClient interface as the cloud providers, which keeps all of the above invisible to the upper Agent logic — moving from cloud to on-device is a single configuration change with zero business code changes. That is the value of programming to an interface: push “which model to use” down into configuration, and contain the “how to call it” differences inside each implementation.

    So that the conclusions are reproducible, I fixed the measurement methodology. Test device model, OS version, model quantization type, inference backend, concurrency level, peak memory, power draw, and time-to-first-token / generation speed were all collected under the same baseline environment, and every comparison draws on the same conditions.

    Step 3: Resource contention and serialization under multi-agent concurrency

    One more problem is easy to miss after localizing inference: concurrency. A mature local Agent app typically runs several roles at once — one that handles cards, one that maintains the knowledge base, one that analyzes images and audio — and if they all hit the same inference engine simultaneously, things go wrong.

    Unlike a server-side engine, an on-device engine is not naturally equipped with multiple instances or elastic scaling. Usually only one copy of the model weights resides in GPU memory, so when multiple sessions contend for it, you may get unstable results, broken session isolation, or out-of-memory failures — depending on the engine implementation. Concurrency governance therefore has to be explicit. The simplest option is a global lock to serialize:

    1. final _inferenceLock = Lock();
    2. Future<String> infer(String prompt) async {
    3. // Queue wait with a timeout so one task cannot hold the lock forever and starve other Agents
    4. return await _inferenceLock
    5. .synchronize(() async {
    6. try {
    7. // Per-inference timeout; exceptions are released via finally / the lock mechanism
    8. return await _localClient.sendMessage(prompt)
    9. .timeout(const Duration(seconds: 30));
    10. } catch (e) {
    11. // Log and rethrow here; the lock is released automatically when the callback ends, preventing deadlock
    12. rethrow;
    13. }
    14. })
    15. .timeout(
    16. const Duration(seconds: 35),
    17. onTimeout: () => throw TimeoutException('Inference queue timeout, engine released'),
    18. );
    19. }

    To make a single lock operable in practice, you also need: lock timeout (prevents permanent occupancy), task cancellation (so users can interrupt when they navigate away), exception-safe release (finally / automatic release to prevent deadlock), and a queue limit (prevents requests from piling up indefinitely and exhausting memory).

    Serialization guarantees correctness, but at the cost of throughput. For latency-sensitive work such as streaming chat, you need a finer strategy: task tiering + priority queues + priority aging. Split interactive tasks and background batch work into separate pools, let interactive work preempt and background work yield, and “age” low-priority tasks that have waited too long so they are not starved indefinitely. In compute-constrained environments like the phone, the scheduling policy often affects the final experience more than the model itself does.

    Concurrency acceptance testing. Before launch, run concurrency load tests that specifically verify: whether results stay stable across multiple sessions, whether session context is properly isolated, whether peak memory / VRAM hits the ceiling, and whether any OOM or crash occurs — then use the results to set the per-device concurrency limit.

    Choosing an on-device LLM for a mobile Agent

    The decision comes down to three things: whether it runs, whether it runs reliably, and whether it runs fast enough.

    Dimension What it means Recommendation
    Parameter count 2–4B fits mobile best 4B on high-end phones; stay at ~2B on mid- and low-end devices
    Quantization format Determines memory footprint and speed Prefer 4-bit (e.g., Q4) as a balance between accuracy and size
    Context window Larger windows cost more memory Set according to available memory, e.g., 4k–10k tokens
    License Commercial compliance Confirm commercial use and redistribution are permitted
    Memory / storage footprint Weights stay resident Reserve peak headroom so other features do not contend
    Offline availability Must work with no network Define the conditions under which it falls back to the cloud

    Common on-device Agent pitfalls and a selection checklist

    A suggested order for troubleshooting:

    1. Slow model loading: check storage read speed, whether loading happens repeatedly, and whether mmap is in use.
    2. Out of memory / OOM: lower the context length, switch to a smaller quantization, release conversations on demand.
    3. GPU unavailable: add a CPU fallback, and check driver and device-model compatibility.
    4. Context-too-long errors: truncate or chunk the input; you are hitting maxNumTokens.
    5. Thermal throttling: limit concurrency, cap continuous inference duration, and fall back to the cloud when necessary.

    Reusable pre-launch checklist:

    • Model selection: parameter count, quantization, and license confirmed
    • Context length and peak memory measured, with headroom reserved
    • Time-to-first-token and generation speed measured against the fixed baseline methodology
    • Permissions, file validation, backend fallback, and initialization failure handling all in place
    • Engine / conversation release logic covers exception paths
    • Concurrency: lock timeout / cancellation / exception-safe release / queue limit / priority aging in place
    • Failure rollback and monitoring metrics (crash rate, OOM rate, thermal events, fallback trigger count) wired up
    • Gradual rollout, user disclosure, and the cloud fallback switch ready

    Engineering summary: three lessons from integrating an on-device LLM

    1. Stability beats convenience. Treat the official native API as your baseline and evaluate community wrapper layers cautiously. For any device-level failure, first narrow the dependency chain, run a controlled experiment, and collect log evidence instead of retrying try-catch in the application layer — and have gradual rollout, user disclosure, and a fallback in place.
    2. Use a unified interface to isolate model differences. Abstract both local and cloud models behind the same LLM interface, and switching models becomes a configuration problem rather than an architectural one. This is the foundation for making “bring your own model” sustainable.
    3. Concurrency must be governed explicitly. An on-device engine is a scarce, exclusive resource. In multi-agent scenarios, assume conflicts will happen by default, bring concurrency into the design with locks, queues, priorities, and aging, and validate it with load tests — instead of patching it after a production incident.

    For teams building local Agents on phones, the ceiling of what on-device LLMs can do matters, but what usually decides whether the product succeeds is these less visible engineering details. Get stability, interface abstraction, and concurrency governance right, and offline, privacy-friendly local intelligence can actually move from demo to usable.