Running Open-Source LLMs on Mobile: Native Engine Integration and Concurrency Locking for Multi-Agent Apps

    This article shares practical experience from integrating an open-source LLM into a mobile knowledge management app. It covers why you should initialize the inference engine only once per app lifecycle, when to replace a third-party wrapper library with direct native API calls, and how to serialize inference requests from multiple agents using a global lock and task queue. Includes Kotlin code examples, a decision table for wrapper vs. native integration, and a checklist of metrics to track when validating stability on your own devices.

    1. Key Takeaways

    If your app runs an open-source LLM on a phone and multiple agents share that model, three lessons are worth remembering up front.

    First, the model engine should be initialized exactly once per app lifecycle. Reloading weights for every inference causes severe I/O blocking and easily pushes memory past its limits.

    Second, when a third-party wrapper library causes system-level crashes that logs cannot pinpoint, prioritize verifying a direct native API integration. This step must be based on reproduction and log evidence—not assumptions from experience alone.

    Third, when multiple agents send concurrent inference requests, serialize them with a global lock or task queue. This sacrifices some throughput but significantly reduces the risk of GPU/NPU memory overflow and deadlocks.

    The rest of this article is organized into background, problem, solution, and validation.

    2. Why Run an LLM on the Device

    In personal knowledge management and life-logging apps, users increasingly care about data privacy and offline availability. If every request goes to a cloud LLM, users’ notes, photos, and voice content all leave the device—and unstable connections interrupt functionality.

    For this reason, many teams introduce quantized open-source models in the 2B–4B parameter range. These models can run within the compute and memory constraints of modern phones, but with very little headroom. Integrating them into an existing cross-platform app and keeping multiple agents running reliably takes repeated architectural adjustments.

    This article documents the real iteration process of a knowledge management app. Test devices, OS versions, and engine versions are listed in Section 6. Your environment will differ, so treat the numbers and observations here as references rather than universal conclusions.

    3. Problems with Third-Party Wrapper Libraries—and How to Diagnose Them

    Early in a project, teams usually pick a third-party wrapper library from their cross-platform framework because it quickly verifies whether the model can run on-device. These wrappers typically add a layer on top of the underlying inference engine and expose a concise API to higher-level languages like Dart or JavaScript.

    In deep testing, we found the app would crash when agents performed complex reasoning or made frequent model calls—on some devices, the entire phone would even reboot. A full device reboot usually indicates a problem in memory management or hardware resource scheduling, not just an application-layer logic bug.

    To locate the issue, we ran the same model through both the wrapper library and the official native reference implementation, then compared results. The differences clustered around cross-language communication, thread scheduling, and memory pointer mapping. The wrapper layer may have added overhead or mishandled exceptions. This conclusion comes from comparative testing—we did not audit the wrapper’s source code line by line, so we cannot pinpoint the exact faulty line.

    Use the following table to decide whether to replace the wrapper:

    Dimension Third-Party Wrapper Direct Native API
    Stability Depends on the library’s implementation quality; needs extra validation Controlled directly by the official engine; issues are easier to reproduce
    Maintenance cost Low; concise API High; Android and iOS code must be maintained separately
    Cross-platform consistency Good; one codebase for both platforms Poor; separate channels required on each side
    Debugging difficulty High; must see through the wrapper layer Low; shorter call chain
    Best suited for Prototyping, features with low stability requirements Production, long-running sessions, multi-agent scenarios

    If your app only needs a short feature demo, a wrapper library is usually sufficient. If the app processes user data in the background for long periods, direct native integration is worth the investment.

    4. Native Integration Architecture: Layering and a Singleton Engine

    After replacing the wrapper, the call chain becomes: upper-layer business logic → platform channel (e.g., MethodChannel) → native plugin → underlying inference engine. Upper-layer code interacts only with the channel and never touches model objects directly.

    The core design on the native side is “singleton engine plus sessions created on demand.” Model weights typically exceed 2 GB, and loading them into GPU or NPU memory is time-consuming and resource-heavy. The engine should be initialized only once, while each user interaction creates a lightweight session that is released immediately after inference completes.

    Here is illustrative code. Class names follow the original implementation—before integrating, confirm actual names, dependencies, and initialization parameters against your chosen SDK’s documentation.

    1. object LocalLlmHolder {
    2. private val initMutex = Mutex()
    3. @Volatile
    4. private var engine: Engine? = null
    5. suspend fun getEngine(context: Context, modelPath: String): Engine {
    6. engine?.let { return it }
    7. return initMutex.withLock {
    8. engine ?: createEngine(context, modelPath).also { engine = it }
    9. }
    10. }
    11. private fun createEngine(context: Context, modelPath: String): Engine {
    12. require(File(modelPath).exists()) { "Model file not found: $modelPath" }
    13. val created = Engine(
    14. EngineConfig(
    15. modelPath = modelPath,
    16. backend = Backend.GPU(),
    17. maxNumTokens = 10000,
    18. cacheDir = context.cacheDir.absolutePath,
    19. )
    20. )
    21. created.initialize()
    22. return created
    23. }
    24. }

    The inference entry point also needs locking and timeout control:

    1. private val inferenceLock = Mutex()
    2. private const val INFERENCE_TIMEOUT_MS = 30_000L
    3. suspend fun runInference(
    4. context: Context,
    5. modelPath: String,
    6. userText: String,
    7. config: ConversationConfig,
    8. ): Result<String> {
    9. return try {
    10. inferenceLock.withLock {
    11. withTimeout(INFERENCE_TIMEOUT_MS) {
    12. val engine = LocalLlmHolder.getEngine(context, modelPath)
    13. engine.createConversation(config).use { conversation ->
    14. val builder = StringBuilder()
    15. conversation.sendMessageAsync(userText).collect { chunk ->
    16. builder.append(chunk)
    17. }
    18. builder.toString()
    19. }
    20. }
    21. }.let { Result.success(it) }
    22. } catch (e: TimeoutCancellationException) {
    23. Result.failure(e)
    24. } catch (e: Exception) {
    25. Result.failure(e)
    26. }
    27. }

    A few important notes:

    • If engine initialization fails, engine stays null and the next call retries initialization. If the failure is due to insufficient device memory, retries will likely keep failing—in that case, notify the user instead of retrying endlessly.
    • The use block guarantees the session is closed on normal completion, exceptions, and timeout cancellation alike. This is key to preventing session resource leaks.
    • OutOfMemoryError is an Error, not an Exception, so the catch blocks above won’t capture it. If your SDK throws this type of error when GPU/NPU memory runs out, catch it separately in the caller and log the device state.

    The cloud/local switching interface can remain identical so upper-layer agents only need to change a configuration value. But the switching strategy needs its own design. If local inference automatically falls back to the cloud on failure, user data leaves the device—contradicting the privacy goal of local inference. Cloud fallback should therefore require explicit user authorization and be clearly communicated in the UI.

    5. Multi-Agent Concurrency: Global Lock and Task Queue

    In a local knowledge management app, multiple agents typically run concurrently: a card-processing agent structures information, a knowledge base agent handles vectorization and retrieval, and a multimodal agent analyzes images and audio.

    The cloud can absorb concurrent requests through elastic scaling; a phone has no such headroom. When multiple agents hit the same engine simultaneously, GPU/NPU memory can overflow, or underlying compute threads can wait on each other, eventually deadlocking.

    The solution is to introduce a global inference lock in the native scheduling layer, or use a single-threaded task queue. All inference requests enter one queue and execute in order. A task acquires the lock only after the previous task finishes and releases its session.

    In practice, a global lock is only the starting point. Add the following safeguards:

    • Queue capacity: Set an upper limit. When the queue is full, new requests immediately return a “busy” error instead of queueing indefinitely and consuming memory. Determine the limit based on per-inference latency and the wait time users can tolerate.
    • Timeouts: Assign each task a timeout. On expiry, cancel the task and release the session so one stuck task doesn’t block all subsequent requests.
    • Cancellation: When a user leaves a page or the system kills a background task, cancel the corresponding inference request instead of letting it keep holding the lock.
    • Prioritization: Interactive tasks (e.g., a user waiting on an answer) should take priority over background tasks (e.g., batch indexing). Use separate queues per class or a priority queue.
    • Deadlock monitoring: Record lock wait time for every acquisition. Alert when wait time exceeds a threshold to surface abnormal task orchestration.

    This strategy reduces concurrent throughput. For latency-sensitive interactive scenarios, a priority queue mitigates the impact. For background batch processing, longer waits are usually acceptable.

    6. Testing and Monitoring: Metrics to Record

    The stability improvements described here need to be validated on your own devices and models. Start by recording your test environment: device model, OS version, SDK version, backend type (CPU, GPU, or NPU), model size, and quantization method. Results vary widely across environments.

    During testing, track these metrics:

    • Concurrency: number of agents issuing inference simultaneously.
    • Peak memory: app and system memory usage during inference.
    • GPU/NPU utilization: hardware usage during inference.
    • OOM rate: out-of-memory occurrences per 1,000 requests.
    • P95 latency: completion time for 95% of requests—reflects user experience better than the average.
    • Lock wait time: time from entering the queue to acquiring the lock.
    • Crash count: number of app crashes and system reboots.

    Run every metric under the same test script multiple times and record the number of runs. Numbers from a single run rarely reflect true stability.

    7. Where This Approach Fits—and Where It Doesn’t

    This approach suits apps that run in the background for long periods, handle sensitive user data, and share a single local model across multiple agents.

    Reconsider it in these cases:

    • Low-memory devices with little headroom after model loading. Consider a smaller model, or load it only on explicit user request.
    • Highly latency-sensitive use cases such as voice conversations, where a serial queue creates noticeable wait times. Consider splitting the workload across multiple smaller models, or relaxing real-time requirements.
    • One-off demos that don’t need long-term stability. A wrapper library is simpler and likely sufficient.

    8. Conclusion

    Running open-source LLMs on phones requires handling model loading, memory control, and concurrent scheduling at the same time. Calling native APIs directly, keeping the engine as a singleton, and serializing inference with a global lock reduced crashes in our testing—but they are not the only approach, and they won’t fit every device.

    When implementing, start with comparative testing to confirm the source of your problems, then introduce these measures one at a time and validate against the metrics in Section 6. Keep a rollback plan at every step, and clearly tell users which data stays on-device.