On-Device LLM Inference in Production: A Complete Guide from Pitfalls to a Stable Deployment
For a fully offline mobile app, running LLM inference directly on the device solves privacy concerns and unlocks functionality in airplane mode or weak-network environments. This article documents our journey integrating an on-device LLM engine into a Flutter app: why a community wrapper package caused system-level crashes, how we rebuilt the integration with a Platform Channel calling the official native engine, the "heavy engine + lightweight conversation" resource management pattern, and why a global mutex is essential for multi-Agent concurrency. It ends with five practical lessons for teams building local AI features.
1. Background: Why Local Inference Is Worth It
For a personal life-logging and knowledge management mobile app, “data never leaves the device” is a core selling point. The product previously used a “bring your own LLM” cloud approach, which was flexible but suffered from two unavoidable problems: privacy-sensitive users were reluctant to send data to the cloud, and the app was unusable in fully offline scenarios (airplane mode, weak connectivity).
The maturing of open-source on-device small models made a “fully offline option” feasible for the first time. Model files in the gigabyte range and inference engines that run directly on mobile GPUs mean local Agent inference can reach usable quality and response speeds. But the actual integration was far more曲折 than expected—this article records the pitfalls we hit and the final solution we landed on.
2. First Attempt: The Stability Trap of High-Level Wrapper Packages
To save time, we initially chose a community-maintained Flutter wrapper package that added a second layer of abstraction over the underlying inference engine, with a clean-looking API. Real-world testing exposed a serious problem: during model inference, the phone would occasionally black-screen and reboot—not an app crash, but a system-level restart.
This is worth taking seriously. An application-level crash can be mitigated with exception handling and process isolation, but a system-level restart means the underlying calls hit driver- or system-resource-level boundaries that the app layer can barely defend against.
Our troubleshooting process:
- On the same device with the same model file, running inference via the official sample app was completely stable;
- The official sample calls the engine directly through native APIs, while the wrapper added an extra cross-platform Plugin forwarding layer;
- The problem most likely lay in the wrapper’s memory management, thread scheduling, or lifecycle handling, and was not fixable in the short term.
Conclusion: On-device inference touches sensitive resources like GPU memory and low-level engine state machines. In production, prefer the official native APIs and treat community wrapper packages with caution. “Clean API design” is a secondary consideration compared to stability.
3. The Final Solution: A Self-Built Platform Channel Directly to the Native Engine
3.1 Architecture
After dropping the wrapper, we wrote our own Platform Channel to call the official on-device inference engine. The call chain is:
Dart business layer → MethodChannel → Kotlin Plugin → Inference engine
3.2 Two Core Design Decisions
First, the Engine is a global singleton. Model files are gigabytes in size, and loading one into GPU memory is an extremely expensive operation that must happen exactly once:
val engine = Engine(EngineConfig(modelPath = modelPath,backend = Backend.GPU(),maxNumTokens = 10000,cacheDir = context.cacheDir.absolutePath,))engine.initialize()
Second, Conversations are created on demand and destroyed after use. Conversation objects are lightweight. We create a new one per inference request and guarantee resource release with the use construct:
engine.createConversation(config).use { conversation ->conversation.sendMessageAsync(userText).collect { ... }}
This “heavy engine + lightweight conversation” layering is the key pattern for on-device inference: heavy resources are shared globally, while lightweight resources are isolated per request. It avoids repeated loading costs and prevents conversation state from leaking across requests.
3.3 Transparency to the Upper Layer
On the Dart side, we implemented a local inference client that implements the same LLMClient abstraction as our cloud providers. This was the highest-value design decision of the whole effort: to the upper-layer Agents, local and cloud models are completely interchangeable—switching requires changing a single config entry. It also validates a general principle: abstract a unified inference interface early in any LLM application, and the cost of adding new models and backends later drops to a minimum.
4. Multi-Agent Concurrency: Why a Global Lock Is Necessary
Several Agents run in parallel in the product: one generates cards, another maintains the knowledge base, another analyzes images and audio. Switching to local inference introduced a new problem—cloud APIs handle concurrent requests natively, but an on-device engine’s GPU memory and compute are exclusive resources. Multiple conversations inferring simultaneously leads directly to OOM crashes or inference speed collapse.
The solution is a global mutex that serializes inference requests from all Agents:
- Requests enter a queue and execute in priority or first-come-first-served order;
- While holding the lock, a request has exclusive access to the engine and releases it immediately after completion;
- The async interface exposed to upper-layer Agents stays unchanged; the queueing logic is absorbed inside the client.
Serialization looks like a throughput sacrifice, but the real-world impact is limited: a single inference with an on-device small model typically takes on the order of seconds, so queueing delay is noticeable but not fatal—far better than crashes caused by concurrency. Later iterations can add request coalescing and short-task-first scheduling optimizations.
5. Key Takeaways
- Be cautious with wrapper packages for on-device inference. Prefer official native APIs, and verify stability risks with real testing;
- Engine singleton + conversations created on demand is the standard resource management pattern for gigabyte-scale models on mobile;
- Abstract a unified
LLMClientinterface early so local and cloud models are transparent to the business layer; - On-device concurrency must be managed yourself. Global-lock serialization is the simplest reliable first solution;
- A hybrid offline-plus-cloud architecture is the pragmatic way to balance privacy, availability, and inference quality.
On-device LLMs are moving from “runs in a demo” to “runs in production,” but the engineering details are far more complex than any demo suggests. We hope this record of hard-won lessons helps teams building local AI applications avoid the same detours.
