On-Device LLM Inference in Production: Lessons from Building a Stable Local Inference Pipeline for Mobile Apps

    Running large language models fully offline on mobile devices offers privacy, availability, and cost advantages—but getting there involves real engineering pitfalls. This article walks through a practical integration of an open-source on-device LLM, covering why cross-platform wrappers can destabilize inference, how to build a reliable Platform Channel bridge to the native engine, how to abstract inference behind a unified LLMClient interface, and how to manage multi-Agent concurrency with a global inference lock.

    On-Device LLM Inference in Production: Lessons from Building a Stable Local Inference Pipeline for Mobile Apps

    Background: Why Fully Offline, On-Device Inference

    As open-source on-device LLMs grow more capable, more applications are exploring AI solutions where “data never leaves the device.” For use cases involving sensitive personal data—such as personal knowledge management and life journaling—fully offline local inference offers three irreplaceable advantages:

    1. Privacy and security: All user data, conversation context, and analysis results stay on the device. Nothing is transmitted to the cloud, which eliminates data leakage risks at the architectural level.
    2. Availability: No network dependency. AI features keep working in the subway, in airplane mode, or anywhere connectivity is unreliable.
    3. Predictable costs: Inference runs on the user’s device. There are no per-call API fees and no rate limits to worry about.

    The trade-offs are equally obvious: limited compute, tight memory budgets, and strict thermal and battery constraints. This article documents a typical on-device LLM integration—including technology choices, debugging war stories, and architecture design—so teams facing similar scenarios can avoid repeating our mistakes.

    Step 1: Cross-Platform Wrappers—Convenient on the Surface, Risky Underneath

    Our app is built on a cross-platform framework, so the team’s first instinct was to use an existing cross-platform wrapper package. These packages simplify the underlying inference engine’s API and looked cheap to integrate.

    In practice, the problems were far worse than expected. We didn’t hit the usual OOM errors or inference crashes—we hit full phone black screens and device reboots. What makes this failure mode so dangerous:

    • It bypasses application-level exception handling; no try-catch can save you.
    • Reproduction is somewhat random, making logs hard to collect.
    • It directly erodes user trust in the product.

    Debugging Approach: Controlled Variables

    Faced with this kind of “black box at the bottom of the stack,” we used a controlled-variable debugging method:

    Variable Official Demo App Cross-Platform Wrapper
    Device Same phone Same phone
    Model files Identical Identical
    Inference engine Same underlying engine Same underlying engine
    Call chain Direct native API calls Extra cross-platform bridge layer

    The only significant difference was the number of layers in the call chain. The native app calls the mobile inference engine’s official API directly, while the wrapper adds an extra hop—“cross-platform framework → plugin bridge layer → native engine”—introducing an additional memory copy and thread scheduling. Although we couldn’t confirm the root cause with 100% certainty, the underlying engine was stable under native calls, which strongly suggested the problem lived in the wrapper layer.

    Conclusion: For scenarios involving low-level sensitive operations like GPU memory management and large file loading, excessive abstraction introduces uncertainty. Stability comes first, so we abandoned the cross-platform wrapper and went straight to the official native APIs.

    Step 2: Building Our Own Platform Channel to Talk Directly to the Native Engine

    Architecture

    The bridging layer we built looks like this:

    1. Dart business layer
    2. ↓ MethodChannel
    3. Native plugin layer
    4. ↓
    5. On-device inference engine (GPU backend)

    The native side follows two core principles:

    Principle 1: The Engine is a singleton

    Model files are measured in gigabytes, and loading one into GPU memory is a heavyweight operation that must happen exactly once globally:

    1. // Engine is initialized only once — loads the large model into GPU memory
    2. val engine = Engine(EngineConfig(
    3. modelPath = modelPath,
    4. backend = Backend.GPU(),
    5. maxNumTokens = 10000,
    6. cacheDir = context.cacheDir.absolutePath,
    7. ))
    8. engine.initialize()

    A few hard-won details worth expanding on:

    • Be conservative with maxNumTokens. The larger the context window, the more GPU memory the KV cache consumes. On low-end devices this can trigger system-level memory reclamation or even process kills. Set it based on the context length your business actually needs—don’t max it out blindly.
    • Point cacheDir at the cache directory. Temporary files generated during inference should never pollute the app’s persistent storage.
    • Run initialize() asynchronously after app startup to avoid blocking the main thread, and expose initialization status events to the frontend so the UI can show loading progress.

    Principle 2: Create Conversations on demand, destroy them after use

    A Conversation is a lightweight object; maintaining conversation state costs far less than the Engine. Create a new one per inference request and release it automatically via a use block to prevent stale state from polluting subsequent context:

    1. engine.createConversation(config).use { conversation ->
    2. conversation.sendMessageAsync(userText).collect { token ->
    3. // Streaming output — tokens are sent back to the Dart side one by one
    4. }
    5. }

    Streaming output is delivered token by token through a MethodChannel event channel, keeping first-token latency low for the user.

    Transparent Abstraction: A Unified LLMClient Interface

    One key architectural decision: define a unified LLMClient interface on the Dart side, implemented by both cloud API providers and the local inference engine.

    1. abstract class LLMClient {
    2. Stream<String> sendMessage(List<Message> messages);
    3. }

    The payoff: the upper-layer Agent logic is completely unaware of whether inference happens in the cloud or on-device, and switching to a local model requires changing a single configuration option. This also means future on-device model integrations require zero changes to business code.

    Step 3: A Global Lock for Multi-Agent Concurrency

    In real products, multiple AI tasks often run at once: a card-organizing Agent, a knowledge-base summarization Agent, and an image/audio analysis Agent may all trigger simultaneously. But an on-device inference engine can typically serve only one request efficiently at a time—GPU compute and memory simply don’t allow true parallel inference.

    Our solution is a global mutex at the inference layer:

    1. All Agent inference requests enter a queue, sorted by priority (user-initiated interactions > background automated tasks);
    2. Only one request at a time is allowed to hold the Engine and run inference;
    3. Queued tasks are cancellable—if the user issues a higher-priority request, lower-priority tasks can be interrupted and re-queued.

    This mechanism sacrifices superficial “concurrency,” but in exchange delivers deterministic resource control and stable inference latency—a pragmatic choice for on-device scenarios.

    Summary and Recommendations

    Looking back at this whole effort, a few conclusions are broadly applicable to other teams:

    • For stability-sensitive low-level integrations, prefer official native APIs. Cross-platform wrappers are fine for rapid prototyping, but every extra layer of abstraction adds risk—especially where GPU memory management is involved.
    • Manage resource lifecycles in layers: heavyweight resources as global singletons, lightweight resources created on demand and released promptly. No leaks.
    • Interface abstraction determines extensibility: a unified LLMClient interface enables seamless switching between cloud and on-device inference, and drives the cost of future model upgrades close to zero.
    • On-device concurrency should use queues, not true parallelism: respect hardware constraints and use priority-based scheduling to protect the user experience.

    On-device LLMs are maturing from “can run” to “actually usable,” but the engineering pitfalls go far beyond what any demo shows. We hope this record of lessons learned helps teams currently building—or planning to build—local AI integrations avoid some of the same dead ends.