On-Device LLM Deployment: Architecture Design and Pitfalls from a Real Production Integration
This article walks through the architecture and engineering trade-offs of deploying large language models locally on mobile devices. Using a real product integration as the guiding example, it explains why on-device inference matters (data privacy, offline availability, and cost/latency), the stability pitfalls of multi-layer cross-platform wrapper libraries, and a layered design that connects platform channels directly to native inference engines. It then covers engine lifecycle management (a singleton engine plus on-demand conversations), a unified interface that abstracts local versus cloud inference, and a global-lock strategy for handling concurrent multi-agent requests. The goal is to help developers move on-device models from "it runs" to "it actually works well."
1. Why Run LLMs Locally on the Device
As small open-source models (such as 2B and 4B parameter variants) have matured, on-device inference has shifted from “it can run” toward “it is genuinely usable.” Running a model locally on the device delivers value in three main areas:
- Data privacy: All inference happens on the device, so user data never leaves the phone. This is especially important for sensitive scenarios like voice recordings, notes, and knowledge management.
- Offline availability: The device keeps full capability even with no network or a weak connection, removing the hard dependency on cloud services.
- Cost and latency: It eliminates round-trip network overhead, and long-term use does not incur per-token billing.
But on-device deployment is not simply “download a model file and you are done.” A phone’s memory, compute, thermals, and system resource scheduling are far more constrained than a server’s, and the real engineering pitfalls are rarely in the algorithm itself. They usually lie in inference framework selection, resource lifecycle management, and concurrency control. The sections below use a real product integration to break down each critical piece.
2. Pitfall One: The Wrapper Library That Reboots the Phone
At first, to save time, a cross-platform wrapper library from the community was adopted directly. Its API was clean and simple, hiding the details of the underlying inference engine behind a tidy abstraction, and it looked like a fast way to get started. But once it actually ran, a serious problem surfaced:
On some devices, inference caused the entire phone to black-screen and reboot — note that this is not an app crash, but a system-level reboot.
Here is how the issue was investigated:
- Control the variables: On the same device and with the same model file, the official sample app ran without any problem.
- Locate the difference layer: The official sample connected to the inference engine through native code directly, while the community wrapper added an extra cross-platform plugin layer on top of it.
- Draw a conclusion: The stability issue most likely came from this extra layer. Every additional bridge adds another layer of thread scheduling, memory bridging, and lifecycle management — and these are exactly the areas where system-level crashes tend to originate.
Lesson one: for capabilities that touch system-level resources (GPU, large memory, native threads), connect directly to the official native API whenever possible, and avoid multi-layer wrappers. The development time a wrapper library saves is often paid back with interest during stability debugging.
3. The Right Architecture: Layered Design + Direct Native Access via Platform Channels
After dropping the wrapper library, the approach changed to writing custom platform channels that call the mobile platform’s official native inference library directly. The overall layering looks like this:
Upper-layer business / UI (cross-platform layer)│ depends only on a unified inference interface▼Platform channel (cross-boundary communication layer)│ MethodChannel-style request / streaming-response bridge▼Native plugin layer (host platform)│ wraps the engine and scheduling logic▼On-device inference engine (native AI inference library)
The key points of this layering are:
- The cross-platform layer handles only interaction and display. It issues requests through a unified abstract interface and does not care whether the underlying execution is local inference or a cloud call.
- The native plugin layer is responsible for engine initialization, model loading, and inference scheduling. It calls the official inference library directly, avoiding the uncertainty introduced by intermediate wrappers.
- Cross-layer communication uses a platform-channel mechanism that supports streaming responses — the model calls back once per generated fragment, and the upper layer refreshes in real time, delivering an experience close to that of cloud LLMs.
A condensed example (pseudocode, meant only to convey the design idea):
// Initialize the engine only once — loads the multi-GB model into memory / GPUval engine = Engine(modelPath = modelPath,backend = Backend.GPU,maxNumTokens = 10000, // context limitcacheDir = context.cacheDir // KV cache directory)engine.initialize()// Create a lightweight conversation for each request and release it when doneengine.createConversation(config).use { conversation ->conversation.sendMessageAsync(userText).collect { fragment ->// streaming callback: return fragments to the upper layer as they arrive}}
After switching to the official native API, inference speed returned to normal and the device-reboot problem disappeared entirely.
4. Engine Lifecycle: Singleton Engine + On-Demand Conversations
The biggest cost on-device is model loading. A model with billions of parameters can easily span several GB, and reloading it for every request brings unbearable wait times and memory churn. The design principles for the engine lifecycle are therefore:
- Engine as a singleton: The engine is initialized only once over the entire app lifecycle, with the model kept resident in memory/GPU. Subsequent requests reuse it directly, avoiding repeated loading.
- On-demand conversations: Each interaction creates a lightweight conversation object that carries its own independent context and is released immediately after use. A conversation does not reload the model, so its cost is very low.
- Prompt release:
usesemantics (or the equivalent try-with-resources / auto-close pattern) ensure that resources are reclaimed as soon as a conversation ends, preventing context from accumulating without bound and exhausting memory.
This “make heavy resources singletons, create lightweight objects on demand” pattern matches the approach in the official sample app and is a general-purpose paradigm for on-device inference resource management.
5. Staying Transparent to the Upper Layer: A Unified Interface Over Local and Cloud
Products often support both a local offline mode and a cloud online mode. To handle this, a unified inference abstraction interface is designed so that both the local engine and the cloud service implement the same interface:
- The upper-layer Agent depends only on the unified interface and does not care whether the underlying model is local or a cloud API.
- Switching between local and cloud mode requires changing only a single configuration item, with zero intrusion into business code.
- The local implementation adapts the engine’s streaming output into standard callbacks, so its behavior aligns completely with the cloud implementation.
This interface-oriented design means that introducing a fully offline option barely changes the upper-layer logic, which is key to keeping the architecture extensible.
6. Multi-Agent Concurrency: Why a Global Lock Is Necessary
In real products, multiple Agents often run in parallel — for example, an Agent that processes cards, one that maintains the knowledge base, and one that analyzes images and audio. The problem is that on-device inference engines are generally not concurrency-safe. When multiple conversations contend for the GPU and memory at the same time, it leads to garbled results, out-of-memory errors, and even crashes.
The mitigation is to introduce a global lock:
- Guard all conversation access to the same inference engine with a global mutex, ensuring that only one inference task executes at any given moment.
- Requests from different Agents queue up and are scheduled serially, trading true parallelism for stability.
- The lock is released only after the streaming response completes, handing control to the next Agent.
In a resource-constrained environment like a device, “serial plus queued” is often more reliable than “concurrent” — stability takes priority over extreme parallelism.
7. Key Takeaways for On-Device Deployment
Across the whole process, a few general principles emerge:
- Choose by layer: For capabilities close to system resources, prefer connecting directly to the official native interface and use multi-layer wrapper libraries with caution.
- Establish heavy resources first, then build light ones on top: A singleton engine for reuse and on-demand conversations are the core of on-device performance and memory management.
- Isolate through interfaces: Use a unified abstraction to hide the difference between local and cloud so that switching costs nothing.
- Achieve concurrency through serialization: Given the engine’s lack of concurrency safety, a global lock plus a queue is the safe choice.
- Fall back to a hybrid architecture: When the on-device model cannot handle complex tasks, adopt a local-first, cloud-augmented strategy. The local side handles privacy-sensitive and offline scenarios, while the cloud (for example, general-purpose LLM inference offered by Baidu AI Cloud) takes on tasks with higher compute or quality demands. The two cooperate through a unified interface, balancing privacy, offline availability, and the ceiling of capability.
Ultimately, deploying an on-device LLM is an engineering practice of repeatedly trading off stability, performance, and experience under limited resources. Only when foundational issues like architecture layering, lifecycle management, and concurrency control are handled cleanly can a model truly move from “it runs” to “it works well.”
