On-Device LLM Deployment in Practice: A Complete Journey from Solution Selection to Architecture Rebuild
This article documents a team's hands-on experience integrating an offline large language model into a mobile Agent application. It covers the initial attempt with a Flutter plugin wrapper that caused system-level reboots, the rebuild around a native Kotlin integration layer with proper engine and session lifecycle management, the abstraction of a unified LLMClient interface for seamless on-device/cloud switching, and key lessons learned about cross-language wrappers, native lifecycle management, interface-first design, and hardware compatibility testing.
On-Device LLM Deployment in Practice: A Complete Journey from Solution Selection to Architecture Rebuild
Integrating offline large language model (LLM) capabilities into mobile products is becoming an important direction for improving user privacy and overall product experience. For an Agent-style application that emphasizes local data processing, whether it can offer an inference option that does not depend on network connectivity or cloud services at all often determines the breadth and depth of its scenario coverage. Recently, our team carried out a complete technical practice in this direction—from solution selection to a full architecture rebuild. The journey had its setbacks, but we ultimately settled on a stable and reusable integration pattern.
Solution Selection: A Fast Start and an Early Setback
At the start of the project, to validate quickly, we prioritized a relatively mature Flutter wrapper library from the community to integrate the on-device inference engine. At its core, the library provides Dart bindings over an underlying C++ inference framework, exposing concise high-level APIs such as loadModel and generateResponse. During the technical research phase, this approach would clearly reduce the development effort of cross-language bridging.
However, on-device testing sounded the alarm. After several consecutive long-text inference runs, the test device exhibited extremely severe stability problems—not a simple application crash (Force Close), but a reboot of the entire operating system. This kind of “full device reboot” indicated that the problem had spread from the application sandbox into the system kernel or low-level drivers.
We conducted rigorous cross-validation: on the same device, with the same model file, we ran the official native demo app (built with Kotlin calling the underlying inference framework directly). The entire process was stable and smooth. This comparison clearly pointed the root cause at the Flutter plugin wrapper layer.
After repeated testing and code review, we hypothesized three potential causes of the reboots:
- Failure of memory boundary management: When the Flutter plugin passes large binary blocks of tensor data between Dart and native C++ code, deep copies or improper memory-sharing strategies may have caused out-of-bounds access to the native heap.
- Thread scheduling conflicts: The inference engine’s internal GPU compute threads may have competed for resources with Flutter’s UI rendering thread under specific Android device drivers, triggering the watchdog mechanism and ultimately causing a system-level reboot.
- Broken exception propagation: Exceptions thrown at the underlying C++ layer were not properly caught across JNI (Java Native Interface) and the Flutter plugin registry, leaving the process in an undefined state.
Given the extremely high stability requirements of a mobile Agent product, we decided to abandon the Flutter wrapper approach entirely and call the system’s native interfaces directly, ensuring full control over low-level resource usage.
The Way Forward: Building a Robust Architecture on Native Interfaces
After dropping the Flutter plugin, we set out to design a more reliable native integration layer. The overall architecture is still based on bidirectional communication between Dart and native code (MethodChannel), but unlike the original approach, we pushed all core logic down to the Kotlin side.
New architecture layers: UI layer (Dart) → communication bridge (MethodChannel) → native logic layer (Kotlin plugin) → inference engine
In this design, we strictly followed the officially recommended paradigms for memory and lifecycle management:
1. Singleton for the Heavyweight Engine
Model loading is an extremely I/O- and memory-intensive operation. Loading a model file of nearly 3GB into GPU memory takes several seconds and consumes a large amount of contiguous memory. Triggering a reload on every inference request would cause catastrophic latency and memory churn. Therefore, the engine instance must be a global singleton.
// Initialization configurationval config = EngineConfig(modelPath = localModelPath,backend = Backend.GPU(), // Specify the GPU backendmaxNumTokens = 10000,cacheDir = context.cacheDir.absolutePath)// Globally unique instance: load once, keep resident in memoryval engine = Engine.getInstance()engine.initialize(config)
2. On-Demand Creation of Lightweight Conversation Handles
Unlike the heavyweight engine, creating and destroying each logical conversation (session) is very cheap. To keep contexts isolated and prevent memory leaks, we adopted a “use and discard” strategy.
fun generateResponse(inputText: String): String {val conversation = engine.createConversation()try {conversation.sendMessage(inputText).collect { response ->// Handle streaming output}} finally {conversation.close() // Explicitly release resources}}
With these two adjustments, inference speed returned to normal and the long-standing system stability problem was completely resolved. Practice proved that bypassing the Flutter plugin’s intermediate translation layer and working directly against the native API is an effective way to avoid performance loss and potential crash risks.
The Abstraction Layer: Seamless, Transparent Switching Between On-Device and Cloud
With the underlying inference stability solved, our other core challenge was architectural uniformity. Before offline mode was supported, the Agent product already depended on cloud LLM APIs. To keep upper-layer business logic (such as tool calling and prompt orchestration) agnostic to whether the user is offline or online, we abstracted a unified LLMClient interface.
The core value of this pattern:
- Dependency injection: Based on configuration or runtime environment detection, the local client implementation or the cloud client implementation is injected dynamically.
- Unified protocol: Whether it is streaming output, aborting generation, or timeout handling, the upper layer only programs against the interface, which greatly reduces the complexity of business code.
This design allows the product to switch flexibly between a “fully offline privacy mode” and a “high-intelligence online mode,” with the change being completely transparent to the upper-layer Agent core logic. In the end, the product gained fully offline local inference capability, and its performance and stability on common devices reached a usable level.
Summary and Lessons Learned
For developers planning to integrate on-device LLMs into mobile applications, we distilled the following core recommendations:
- Be cautious with cross-language wrappers: Unless officially supported and rigorously stress-tested, avoid heavy cross-language bridging layers in deep learning inference pipelines. Flutter plugins offer high development efficiency, but under extreme computational load they can introduce uncontrollable stability risks.
- Native-level lifecycle management: Distinguish heavy resources from light resources. The engine must stay resident; sessions must be short-lived. Following this principle effectively avoids most memory-related issues.
- Interface first: Define a unified communication protocol interface for cloud and local clients early in development. Don’t wait until the local model works before abstracting—doing so leads to extensive refactoring.
- Hardware adaptation is a long battle: On-device model performance is strongly tied to device hardware. GPU drivers from different vendors differ in operator support, so cover mid-range and low-end devices in real-device compatibility testing. Do not stop at validation on emulators or flagship phones.
