On-device vs cloud AI: how to choose

Choose between on-device and cloud AI in Android: trade-offs for privacy, latency, offline use, app size, and battery, with a Kotlin backend interface. About 25 minutes.

Why it matters

  • The on-device vs cloud decision is the first architectural choice in any AI feature. Get it wrong and you ship an app that crashes on low-RAM devices, drains battery, or leaks user data to a third-party server.
  • Interviewers at senior levels ask you to justify the choice with concrete trade-offs (latency, privacy, model quality, cost per token, app size) rather than a one-line answer.
  • A clean AiBackend interface lets you swap runtimes without rewriting UI code, which is what reviewers look for in a PR that adds AI to an existing Android app.
  • Structured output from a cloud model can be malformed JSON; you must validate it in Kotlin before trusting it, or your app will crash on a bad response.

The simple explanation

  • On-device AI is like a calculator in your pocket: instant, private, works in a plane, but limited to what fits in the device.

The question every Android AI feature answers first is: where does inference run?

On-device means the model weights (a file of numbers, such as a LiteRT .tflite file or a LiteRT-LM .litertlm file) load into the phone's RAM and run on the CPU, GPU, or NPU. No network call. The user's prompt never leaves the device. Trade-offs: the model is smaller, so quality is lower; the file adds to your AAB size; loading and running it costs battery; and not every device has enough RAM or an NPU. On Android you can also use Gemini Nano through ML Kit GenAI APIs, where the system (AICore) owns the model, but only on supported devices. Check the current docs for supported models and devices.

Cloud means your app sends a request to your own server (or a managed client SDK such as Firebase AI Logic, protected with App Check), which calls a model provider. A provider API key never goes in BuildConfig or app code. Trade-offs: you get a larger, higher-quality model; the app stays small; but you pay per token, you add a network round-trip (latency), and the user's data leaves the device.

DimensionOn-deviceCloud
PrivacyData stays on deviceData leaves device
OfflineWorksNeeds network
LatencyNo round-tripNetwork + queue
Model qualitySmaller modelLarger model
App size+model fileNo change
BatteryNPU/GPU costNetwork cost
CostNo per-call feePer-token
Device coverageVariesUniversal

The right answer is rarely "always on-device" or "always cloud." Many apps use both: a small on-device model for instant, private tasks (text classification, image tagging) and a cloud call for complex generation. Wrap both behind one interface so the UI layer does not care which one runs.

In Prompts, context and structured output you will learn how to ask for JSON and validate it. Later lessons cover ML Kit, MediaPipe, LiteRT and Gemini Nano in detail.

Notes

  • On-device inference loads model weights into RAM and runs on CPU, GPU, or NPU. No network call is made. The model file adds to your app size (or must be downloaded), and a large model can get the app killed for memory on low-RAM devices.
  • Cloud inference sends the prompt to your own server. The API key must stay on that server. Never put it in BuildConfig, a string resource, or any file shipped in the APK.
  • Latency on-device is bounded by device compute; latency in the cloud is bounded by network round-trip plus server queue time. For a typing-assist feature, on-device wins. For a long-form essay, cloud wins.
  • Not every device has an NPU or enough free RAM for a large model. Check the current docs for supported models and devices before committing to on-device.
  • Structured output from a cloud model can be invalid JSON. Always parse and validate the response in Kotlin before using the result. Treat a parse failure as a normal error path, not a crash.
  • Hallucination is normal model behaviour, not a bug you can fully remove. Design your UI to show uncertainty and let the user verify, rather than trusting the output blindly.
  • A clean AiBackend interface (or equivalent in your DI graph) lets you swap on-device and cloud at runtime or per feature without touching Compose or ViewModel code.
  • Per-token cloud cost scales with context window size. A large context window costs more per call than a small one. Trim context aggressively.

Code example

This Kotlin snippet shows a sealed AiResult, an AiBackend interface with two implementations (on-device and cloud), and a pickBackend function that chooses at startup based on device capabilities and feature requirements.

// Swap on-device or cloud AI without changing UI code
sealed interface AiResult {
    data class Ok(val text: String) : AiResult
    data class Err(val msg: String) : AiResult
}
 
interface AiBackend {
    suspend fun complete(prompt: String): AiResult
}
 
// On-device: model weights load into RAM, run on CPU/GPU/NPU
class OnDeviceBackend(private val modelPath: String) : AiBackend {
    override suspend fun complete(prompt: String): AiResult =
        try {
            // wrap LiteRT / ML Kit / MediaPipe here
            AiResult.Ok("on-device result")
        } catch (e: OutOfMemoryError) {
            AiResult.Err("Model too large for this device")
        }
}
 
// Cloud: your server holds the API key; app never sees it
class CloudBackend(private val serverUrl: String) : AiBackend {
    override suspend fun complete(prompt: String): AiResult =
        try {
            // POST to your server via Retrofit / OkHttp
            AiResult.Ok("cloud result")
        } catch (e: Exception) {
            AiResult.Err("Network error: " + e.message)
        }
}
 
// Call once at startup; store the result in your DI graph
fun pickBackend(
    hasNpu: Boolean,
    freeRamMb: Int,
    modelSizeMb: Int,
    needsOffline: Boolean
): AiBackend {
    val fits = freeRamMb > modelSizeMb * 2
    return if (needsOffline || (fits && hasNpu))
        OnDeviceBackend("model.tflite")
    else
        CloudBackend("https://your-server.example.com/ai")
}
  • AiResult is a sealed interface so the UI can when-branch on success or error without null checks.
  • OnDeviceBackend catches OutOfMemoryError as a last guard. Most model memory is native, so the real defence is checking memory before you load; the caller can then fall back to cloud.
  • CloudBackend points at your own server, not a third-party SDK. The API key lives server-side only.
  • pickBackend uses a 2× RAM headroom rule as a simple guard. In production, read ActivityManager.getMemoryInfo() (total and available memory) and isLowRamDevice(), and check the current docs for device support.

Run the idea in plain Kotlin

data class Criteria(
  val privacyCritical: Boolean,
  val needsOffline: Boolean,
  val latencyMsBudget: Int,
  val modelSizeMb: Int,
  val deviceRamMb: Int,
  val hasNpu: Boolean
)

fun decide(c: Criteria): String {
  var onDevice = 0
  var cloud = 0

  if (c.privacyCritical) onDevice += 3
  if (c.needsOffline) onDevice += 3
  if (c.latencyMsBudget < 200) onDevice += 2
  if (c.deviceRamMb > c.modelSizeMb * 2) onDevice += 2
  if (c.hasNpu) onDevice += 1

  if (c.modelSizeMb > 500) cloud += 2
  if (c.latencyMsBudget > 2000) cloud += 1

  val choice = if (onDevice >= cloud) "on-device" else "cloud"
  return "on-device=" + onDevice + " cloud=" + cloud + " -> " + choice
}

fun main() {
  val c1 = Criteria(true, true, 150, 80, 4096, true)
  val c2 = Criteria(false, false, 3000, 800, 2048, false)
  val c3 = Criteria(false, true, 500, 200, 1024, false)

  println("Case 1 (privacy + offline, small model): " + decide(c1))
  println("Case 2 (large model, high latency budget): " + decide(c2))
  println("Case 3 (offline, medium model, low RAM): " + decide(c3))
}

In production

OOM crash on low-RAM devices after adding on-device model
  • The team shipped a large on-device model that loaded at app start. Crash reports spiked on devices with limited RAM.
  • Users saw the app freeze for several seconds, then the process was killed for using too much memory.
  • The model file was bundled in the base module, which made the download much bigger for every user, even those who never used the feature.
The fix
  • Made model loading lazy: only load when the user opens the AI feature screen, not at Application.onCreate.
  • Added a memory check via ActivityManager.getMemoryInfo() and isLowRamDevice() before loading; if the model does not fit, fall back to the cloud backend.
  • Shipped the model with Play Asset Delivery (or Play for On-device AI) so it downloads on demand instead of inflating the base module.
Blank screen when cloud AI call has no timeout
  • During a regional network outage, the cloud AI call hung indefinitely. The Compose screen showed a blank state because the LaunchedEffect never completed.
  • Users could not use the core feature and reported it as a crash in support tickets.
  • No offline fallback existed, so the feature was completely unavailable without a network.
The fix
  • Added a withTimeout around the network call and a retry with exponential backoff.
  • Cached the last successful response in DataStore so the UI could show a stale result with a "last updated" timestamp.
  • Added an error UI state with a retry button instead of leaving the screen blank.

Common mistakes

  • Hardcoding the backend choice in the ViewModel. You cannot test the cloud path in a unit test or switch to on-device for a privacy feature without rewriting the caller. Use an AiBackend interface injected via Hilt or a service locator.
  • Storing the cloud API key in BuildConfig or a string resource. Anyone who decompiles the APK can read it. The key must live only on your server. The app talks to your server; your server talks to the model provider.
  • Assuming every device can run the on-device model. RAM, NPU availability, and thermal limits vary. Check the current docs for supported models and devices, and always provide a cloud fallback for devices that cannot load the model.
  • Trusting structured output from a cloud model without validation. Models can return malformed JSON or fields with wrong types. Parse the response in Kotlin and handle parse failures as a normal error path, not a crash.
  • Sending the full conversation history every cloud call. Context window size drives per-token cost and latency. Trim to the most recent turns or summarise older context on your server before forwarding.
  • Treating hallucination as a bug to eliminate. Hallucination is inherent to how these models work. Design the UI to show confidence, let the user verify, and add a human-review step for high-stakes outputs.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“When would you choose on-device inference over a cloud call in an Android app?”

“How do you keep the cloud AI API key out of the Android app?”

“A user reports the AI feature is slow. How do you diagnose whether it is on-device or cloud latency?”

“How do you handle a cloud model returning invalid JSON as structured output?”

Quiz

Where must the cloud AI API key live in a production Android app?

What is the main risk of loading a large on-device model at Application.onCreate?

A cloud model returns a JSON string that fails parsing. What is the correct response?

Which factor most strongly pushes the decision toward cloud inference?

0 of 4 answered

Mini task

Exercise: Add a backend switch to an existing feature (15 min)

  1. Open your project. Create a new file AiBackend.kt in your data package. Define the AiResult sealed interface and the AiBackend interface exactly as in the example above.

  2. Implement CloudBackend that calls your server endpoint via Retrofit (or OkHttp). The endpoint accepts a prompt string and returns a JSON body. Parse the response in Kotlin into a data class. Catch parse exceptions and return AiResult.Err.

  3. Implement OnDeviceBackend as a stub that returns AiResult.Err("Not yet available"). Add a TODO comment noting where you would wrap the inference runtime.

  4. In your Hilt module (or equivalent DI), provide AiBackend by calling pickBackend with the model size and the available memory from ActivityManager.getMemoryInfo(). Do not put any API key in BuildConfig.

  5. Inject AiBackend into the ViewModel that currently calls the AI feature. Replace the direct call with backend.complete(prompt) and handle both Ok and Err in the Compose UI.

Done condition: The app compiles, the cloud path works when online, the on-device path returns a clear "not yet available" message, and no API key appears anywhere in the project or the built APK (search the source, then open the APK in Android Studio's APK Analyzer and check resources and BuildConfig).

Next: Prompts, context and structured output