DEV Community

Cover image for Offline by Default: Shipping Gemini Nano Features Without a Server
Android Expert
Android Expert

Posted on Originally published at Medium

Offline by Default: Shipping Gemini Nano Features Without a Server

Summarize, classify, and rewrite on-device with ML Kit GenAI, and what actually breaks when you ship it.

A server-free summarizer sounds like a free lunch: no per-call cost, no network dependency, and user text that never leaves the phone. It is also a feature whose availability you do not control, whose model arrives as a separate download, and whose runtime budget is set by an OS service rather than your code. Most of the production pain comes from treating it like a library call instead of what it is: a capability negotiated with the platform at runtime.

This post walks through the shape I would use for a production feature built on Gemini Nano through ML Kit GenAI: how to decide whether the device can do it, which API to call for which job, how to model the download, when and how to fall back to a server, and how to measure the thing honestly. Code is Kotlin with coroutines and Flow. API names and artifact versions were checked against Google’s docs at the time of writing, and several of these APIs are beta, so confirm them against the current reference before you copy anything.

1. Device support and availability check

Start from an uncomfortable fact: there is no Build.VERSION.SDK_INT check that tells you whether Gemini Nano will run. The ML Kit GenAI APIs require Android API 26 or higher, they do not support devices with an unlocked bootloader, and they depend on the AICore system service and a Gemini Nano model that must be present on the device. Support also varies by chipset family and by which model generation a device ships. Google's docs say the Prompt API performs best on the Pixel 10 series, and that the list of devices behind the task-specific APIs (summarization, rewriting, and so on) differs from the Prompt API list.

So the only trustworthy signal is asking the feature itself. Every ML Kit GenAI client exposes a status check that returns one of four values: checkFeatureStatus() on the task clients (a ListenableFuture<Integer>), and a suspending checkStatus() on the Prompt API's GenerativeModel.

availability-check-flow

The diagram says checkFeatureStatus(). On the Prompt API, read that as checkStatus(); the four outcomes are identical.

Wrap the raw integer status and the exceptions into a type your UI can switch on exhaustively. I do this once, generically, and reuse it for every client:

sealed interface Availability {
    data object Ready : Availability
    data object NeedsDownload : Availability
    data object Downloading : Availability
    data class Unsupported(val cause: Throwable? = null) : Availability
}

suspend fun resolveAvailability(check: suspend () -> Int): Availability =
    try {
        when (check()) {
            FeatureStatus.AVAILABLE -> Availability.Ready
            FeatureStatus.DOWNLOADABLE -> Availability.NeedsDownload
            FeatureStatus.DOWNLOADING -> Availability.Downloading
            else -> Availability.Unsupported() // UNAVAILABLE and anything added later
        }
    } catch (e: CancellationException) {
        throw e // never swallow cancellation
    } catch (e: GenAiException) {
        Availability.Unsupported(e)
    }

// Task clients return a ListenableFuture. await() comes from kotlinx-coroutines-guava.
val availability = resolveAvailability { summarizer.checkFeatureStatus().await() }

// The Prompt API's GenerativeModel exposes a suspending checkStatus() instead.
val nanoAvailability = resolveAvailability { model.checkStatus() }
Enter fullscreen mode Exit fullscreen mode

Two details matter here. First, the else branch is deliberate: if a future library version adds a status, you degrade to "unsupported" rather than crash. Second, the status call itself can throw. Google documents setup failures such as a binding failure to AICore and a "feature not found" error when AICore has not yet fetched its configuration, which is common right after a device is set up or reset. Both surface as exceptions from the check, not as a clean UNAVAILABLE, so a bare checkFeatureStatus().await() on a fresh phone can crash your screen.

Failure modes at this layer

  • Caching AVAILABLE in SharedPreferences. Status can regress after a system update, an AICore change, or a storage cleanup. Re-derive it per session, and again at feature entry if the session is long.
  • Checking once at app start. On a just-unboxed phone the answer at minute one and minute thirty can differ. Check lazily, when the user reaches the feature.
  • Hiding the feature permanently on the first Unsupported. The "configuration not downloaded yet" case resolves itself, sometimes within hours. Treat it as "not yet" with a retry on next entry, not "never".
  • Gating on a device allow-list you maintain yourself. It rots within a release cycle. Use the runtime check, and use your own list only for analytics.

2. ML Kit GenAI APIs

ML Kit exposes Gemini Nano through task-specific clients, plus a free-form prompt client. Pick the narrowest tool that fits.

ml-kit-genai-api-surface

The task APIs are not just thin wrappers. Google describes each as the shared base model plus a task-specific LoRA adapter, tuned inference parameters, and an evaluation pipeline. That is why you should prefer them over a hand-rolled prompt when one exists. The Prompt API is the escape hatch for work that has no dedicated client, and for us that means classification.

Artifact coordinates at the time of writing, all marked beta (no SLA, breaking changes possible):

dependencies {
    implementation("com.google.mlkit:genai-summarization:1.0.0-beta1")
    implementation("com.google.mlkit:genai-rewriting:1.0.0-beta1")
    implementation("com.google.mlkit:genai-prompt:1.0.0-beta5")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-guava:1.11.0") // await() on ListenableFuture
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.11.0") // see the known issue below
}
Enter fullscreen mode Exit fullscreen mode

Check Google’s known-issues page before you pin these. genai-prompt 1.0.0-beta5 (released October 26, 2026) is newer than the beta4 this article was first written against, and the request DSL in the classifier below should be re-checked against it. The known-issues page lists two problems for earlier builds: in beta3 and beta4, download() throws NoSuchMethodError when the download completes or is cancelled if the app resolves kotlinx-coroutines to 1.10.x or earlier, and in beta3, checkStatus() threw an unhandled GenAiException on non-Pixel devices (fixed in beta4). Google's stated workaround for the first is to explicitly pin kotlinx-coroutines-android to 1.11.0 or newer, which is why it appears above. What matters is the version your app resolves, not the version of any single artifact, so confirm it with ./gradlew :app:dependencies. I did not find a statement that beta5 fixes the download() problem, so keep the pin until Google says otherwise.

Summarize

The summarizer takes an input type (article or conversation) and an output type of one, two, or three bullets. Documented limits are the part that bites: input must stay under roughly 4,000 tokens, article input must exceed 400 characters, and supported languages are English, Japanese, and Korean. A guard in front of the client keeps those limits out of your error handling:

class NanoSummarizer(context: Context) : AutoCloseable {

    private val client = Summarization.getClient(
        SummarizerOptions.builder(context)
            .setInputType(SummarizerOptions.InputType.ARTICLE)
            .setOutputType(SummarizerOptions.OutputType.THREE_BULLETS)
            .setLanguage(SummarizerOptions.Language.ENGLISH)
            .setLongInputAutoTruncationEnabled(true)
            .build()
    )

    suspend fun availability() = resolveAvailability { client.checkFeatureStatus().await() }

    /** Emits streamed text; completes when inference finishes. */
    fun summarize(text: String): Flow<String> = callbackFlow {
        val request = SummarizationRequest.builder(text).build()
        // trySend returns a ChannelResult we do not inspect. The UNLIMITED buffer
        // below means it can only fail once the channel is closed, so no chunk is
        // dropped while the collector is still attached.
        val future = client.runInference(request) { partial -> trySend(partial) }
        future.addListener(
            // The listener runs after completion, so get() returns immediately.
            { close(runCatching { future.get() }.exceptionOrNull()) },
            Runnable::run
        )
        awaitClose { future.cancel(true) }
    }.buffer(Channel.UNLIMITED)

    override fun close() = client.close()
}

object InputGuard {
    private const val MIN_ARTICLE_CHARS = 400
    private const val MAX_APPROX_TOKENS = 4_000
    fun approxTokens(s: String) = s.length / 4 // crude, English-biased

    fun verdict(text: String): Verdict = when {
        text.length <= MIN_ARTICLE_CHARS -> Verdict.TooShort   // show the text itself
        approxTokens(text) > MAX_APPROX_TOKENS -> Verdict.TooLong // truncate or chunk
        else -> Verdict.Ok
    }
    enum class Verdict { Ok, TooShort, TooLong }
}
Enter fullscreen mode Exit fullscreen mode

Verify one thing empirically in your version: whether the streaming callback delivers deltas or the cumulative text so far. The docs call the argument “new text,” which reads like a delta, but a UI that appends cumulative text produces a stuttering mess. Log the first three callbacks on a real device before wiring up the UI.

Rewrite

The rewriter takes an output type: elaborate, emojify, shorten, friendly, professional, or rephrase. It supports English, Japanese, French, German, Italian, Spanish, and Korean, and its input limit is tight: under 256 tokens. It may return several suggestions, sorted by descending confidence.

class NanoRewriter(context: Context, tone: RewriterOptions.OutputType) : AutoCloseable {

    private val client = Rewriting.getClient(
        RewriterOptions.builder(context)
            .setOutputType(tone)
            .setLanguage(RewriterOptions.Language.ENGLISH)
            .build()
    )

    suspend fun rewrite(text: String): List<String> {
        val result = client.runInference(RewritingRequest.builder(text).build()).await()
        return result.results.map { it.text } // best suggestion first
    }

    override fun close() = client.close()
}
Enter fullscreen mode Exit fullscreen mode

Note that a rewriter is bound to its tone at construction. A “pick a tone” chip row therefore means either one client per tone, created lazily and closed on screen exit, or rebuilding the client on selection. Do not hold six live clients because it was convenient in the ViewModel.

Classify

There is no dedicated classification API, so use the Prompt API with a hard constraint on the output. The goal is a closed label set, near-deterministic sampling, and a tiny output budget. As the benchmarks section shows, output length is what you pay for, so a three-token answer is also your cheapest feature.

class NanoClassifier(private val labels: List<String>) : AutoCloseable {

    private val model = Generation.getClient()

    suspend fun availability() = resolveAvailability { model.checkStatus() }

    suspend fun classify(text: String): String? {
        val prompt = """
            Classify the message into exactly one label from: ${labels.joinToString(", ")}.
            Reply with the label only. If none fit, reply: other.

            Message: ${text.take(1_500)}
        """.trimIndent()

        val raw = model.generateContent(
            generateContentRequest(TextPart(prompt)) {
                temperature = 0.0f
                topK = 1
                candidateCount = 1
                maxOutputTokens = 8
            }
        ).candidates.firstOrNull()?.text

        return parseLabel(raw)
    }

    // Never trust free text from a small model, even when you asked for one word.
    private fun parseLabel(raw: String?): String? {
        val cleaned = raw?.trim()?.lowercase()?.trim('.', '"', '\'', '`') ?: return null
        return labels.firstOrNull { it.equals(cleaned, ignoreCase = true) }
            ?: labels.firstOrNull { cleaned.startsWith(it.lowercase()) }
    }

    override fun close() = model.close() // releases the generation engine
}
Enter fullscreen mode Exit fullscreen mode

The request-building DSL above mirrors the sample in Google’s Prompt API announcement, which used a low temperature, a small topK, a single candidate, and a very small output cap. Check the exact property names against the version you depend on, since this client is the newest and the most likely to move.

Failure modes at this layer

  • Never closing clients. Each client holds a connection to an on-device service, and that includes the Prompt API’s GenerativeModel. Release it with close() in onCleared() or at the end of the feature scope. A leaked client is a slow leak, not a crash, which is the worst kind.
  • Rewriting past 256 tokens. Long messages need a policy: refuse, truncate, or chunk by sentence. Silent truncation changes meaning, so tell the user.
  • Language drift. Ask for English on a Spanish message and you will not get an error, you will get something plausible. Detect the language first and route unsupported ones to fallback.
  • Foreground-only inference and per-app quota. AICore enforces an inference quota per app. Google’s GenAiException.ErrorCode reference documents BUSY (9) as covering two cases: your app is out of quota (retry with exponential backoff), or the request comes from disallowed background use (call the API while your app is in the foreground). There are also BACKGROUND_USE_BLOCKED (30) and PER_APP_BATTERY_USE_QUOTA_EXCEEDED (27), the latter for long-duration quotas such as a daily one. Google does not publish the quota values. Community write-ups additionally report that a foreground service does not count as foreground; I did not find that in the official docs, so test it on a device. Design batch jobs (indexing a whole inbox, say) so they never depend on background Nano.
  • Output variance across devices. Google notes that output can differ across devices because they carry different Gemini Nano base versions, though the LoRA adapters reduce the gap. Never assert on exact strings in a test that runs on a device farm.
  • Trusting the model with structure. Classification output must be parsed against your label set. Anything that fails the parse is null, which routes to fallback, not to a guess.

3. Handling model download and states

If the status is DOWNLOADABLE, the model is not on the device yet. Google's docs describe two situations: if Gemini Nano is already present, only the feature's adapter downloads, which is quick; if not, the base model must come down first, which takes noticeably longer and is the case you must design for.

You can skip the explicit download. Per the docs, if you never call downloadFeature(), the first inference request triggers it. Do not rely on that for anything user-facing, because the user then stares at a spinner of unknown length with no progress and no way to say "not on mobile data".

model-lifecycle-states

Bridge the callback API into a Flow so the download becomes just another observable stream:

sealed interface DownloadEvent {
    data class Started(val totalBytes: Long) : DownloadEvent
    data class Progress(val bytesSoFar: Long) : DownloadEvent
    data object Completed : DownloadEvent
}

fun Summarizer.downloadEvents(): Flow<DownloadEvent> = callbackFlow {
    val future = downloadFeature(object : DownloadCallback {
        override fun onDownloadStarted(bytesToDownload: Long) {
            trySend(DownloadEvent.Started(bytesToDownload))
        }
        override fun onDownloadProgress(totalBytesDownloaded: Long) {
            trySend(DownloadEvent.Progress(totalBytesDownloaded))
        }
        override fun onDownloadCompleted() {
            trySend(DownloadEvent.Completed)
            close()
        }
        override fun onDownloadFailed(e: GenAiException) {
            close(e) // surfaces as an exception to the collector
        }
    })
    // Stop tracking when the collector goes away. Whether cancelling the future
    // also stops the platform's fetch is not documented, so re-check status on
    // the next entry rather than assuming either way.
    awaitClose { future.cancel(true) }
}
Enter fullscreen mode Exit fullscreen mode

The Prompt API takes a different shape for the same job: download() is collected as a flow of DownloadStatus events (started, progress, completed, failed), and it adds an optional warmup() that loads Gemini Nano into memory to cut first-call latency. The task APIs use the callback form shown above. Normalize both into your own DownloadEvent, so the UI layer does not care which client is behind it.

Then collapse everything into one UI state, owned by a ViewModel, and make the transitions explicit:

sealed interface NanoUiState {
    data object Checking : NanoUiState
    data object Unsupported : NanoUiState
    data class NeedsDownload(val sizeKnown: Long?) : NanoUiState
    data class Downloading(val fraction: Float?) : NanoUiState
    data object Ready : NanoUiState
    data class Failed(val retryable: Boolean) : NanoUiState
}

class NanoViewModel(private val summarizer: NanoSummarizer) : ViewModel() {

    private val _state = MutableStateFlow<NanoUiState>(NanoUiState.Checking)
    val state: StateFlow<NanoUiState> = _state.asStateFlow()

    fun refresh() = viewModelScope.launch {
        _state.value = when (val a = summarizer.availability()) {
            Availability.Ready -> NanoUiState.Ready
            Availability.NeedsDownload -> NanoUiState.NeedsDownload(sizeKnown = null)
            Availability.Downloading -> NanoUiState.Downloading(fraction = null)
            is Availability.Unsupported -> NanoUiState.Unsupported
        }
    }

    fun download() = viewModelScope.launch {
        var total = 0L
        summarizer.downloadEvents()
            .catch { _state.value = NanoUiState.Failed(retryable = true) }
            .collect { event ->
                _state.value = when (event) {
                    is DownloadEvent.Started -> { total = event.totalBytes; NanoUiState.Downloading(0f) }
                    is DownloadEvent.Progress ->
                        NanoUiState.Downloading(if (total > 0) event.bytesSoFar.toFloat() / total else null)
                    DownloadEvent.Completed -> NanoUiState.Ready
                }
            }
    }
}
Enter fullscreen mode Exit fullscreen mode

Note that fraction is nullable. When the download is already in flight from an earlier session, you may never see a Started event with a byte count, so the honest UI is an indeterminate bar rather than a fake zero.

Failure modes at this layer

  • Downloading on metered data without asking. The base model is not a small asset. Ask first, show the size if you have it, and offer “Wi-Fi only”.
  • Restarting a download that is already running. If the status is DOWNLOADING, attach to the in-flight work. The task-API samples note that an inference request issued in that state runs automatically once the download finishes; the Prompt API docs do not show the same note, so do not assume it there. Calling downloadFeature() again just confuses your state machine.
  • Treating download failure as terminal. The documented download error is a network failure (an unresolved host, for instance) with advice to keep the connection and retry. Retry with exponential backoff and a cap, and keep the fallback path live while you wait.
  • Assuming the download ends with the process. Your coroutine dies with your process, but the model fetch is not yours. After a cold start, always re-run the availability check rather than trusting in-memory state.
  • Progress that lies. If you map “no progress events yet” to 0 percent, users watch a frozen bar and kill the app. Prefer indeterminate until you have real numbers.
  • Surprise first-inference stalls. Skipping the explicit download means the first user action blocks on a multi-minute fetch. Make the download an explicit, consented step, or trigger it from a settings screen, and call warmup() where the Prompt API offers it.

4. Cloud fallback strategy

On-device is a preference, not a guarantee. A real fraction of your users are on devices without Nano, on devices where the config has not landed, on devices whose quota is spent, or on a path where the model returned junk. A fallback strategy is not a bonus. It is the feature’s SLA.

fallback-router

The router has four design rules.

1. Fall back for reasons, and record them. Every result carries where it came from and why it left the device. Without that, you cannot answer “what percentage of our users actually get the offline path?”, which is the number that decides whether the project paid off.

2. Cloud is gated by consent and policy, not just connectivity. The pitch of on-device processing is that text stays on the phone. Silently sending it to a server when Nano is unavailable breaks that promise. Make the cloud path an explicit setting, or a per-action prompt, and let sensitive content classes (anything you would not log) refuse the cloud path outright.

3. Validate output before trusting it. A small on-device model can return empty text, the wrong language, or a response that is longer than the input. A cheap validator is the difference between a fallback and a bug report.

4. Always have a last resort that is not a model. If the device cannot do it and cloud is not allowed, degrade: show the first sentences for a summary, hide the rewrite button, or show “uncategorized”. The user sees a slightly worse feature rather than an error.

enum class Source { Device, Cloud, Degraded }

sealed interface Outcome<out T> {
    data class Success<T>(
        val value: T,
        val source: Source,
        val latencyMs: Long,
        val deviceFailure: FallbackReason? = null, // why we left the device, if we did
    ) : Outcome<T>
    data class Failure(val reason: FallbackReason) : Outcome<Nothing>
}

enum class FallbackReason {
    DeviceUnsupported, ModelNotReady, DeviceTimeout, DeviceError,
    InvalidOutput, CloudNotAllowed, CloudError
}

interface CloudSummarizer { suspend fun summarize(text: String): String }

class SummaryRouter(
    private val nano: NanoSummarizer,
    private val cloud: CloudSummarizer,
    private val cloudAllowed: suspend () -> Boolean, // consent + policy + network
    private val deviceTimeout: Duration = 20.seconds,
    private val clock: TimeSource = TimeSource.Monotonic,
) {
    private sealed interface DeviceResult {
        data class Ok(val text: String) : DeviceResult
        data class Fail(val reason: FallbackReason) : DeviceResult
    }

    suspend fun summarize(text: String): Outcome<String> {
        val start = clock.markNow()
        fun ok(v: String, s: Source, why: FallbackReason? = null) =
            Outcome.Success(v, s, start.elapsedNow().inWholeMilliseconds, why)

        val deviceFailure: FallbackReason = when (nano.availability()) {
            Availability.Ready -> when (val r = runDevice(text)) {
                is DeviceResult.Ok -> return ok(r.text, Source.Device)
                is DeviceResult.Fail -> r.reason
            }
            Availability.NeedsDownload, Availability.Downloading -> FallbackReason.ModelNotReady
            is Availability.Unsupported -> FallbackReason.DeviceUnsupported
        }

        val allowCloud = cloudAllowed()
        if (allowCloud) {
            try {
                val summary = cloud.summarize(text)
                if (looksValid(summary, text)) return ok(summary, Source.Cloud, deviceFailure)
            } catch (e: CancellationException) {
                throw e // the caller left: propagate
            } catch (e: Exception) {
                // fall through to the degraded path
            }
        }
        // Last resort: extractive. No model, no network, always works.
        val lead = text.split(Regex("(?<=[.!?])\\s+")).take(2).joinToString(" ")
        return if (lead.isNotBlank()) ok(lead, Source.Degraded, deviceFailure)
        else Outcome.Failure(if (allowCloud) FallbackReason.CloudError else FallbackReason.CloudNotAllowed)
    }

    private suspend fun runDevice(text: String): DeviceResult =
        try {
            // One overall deadline for the whole stream. last() waits for completion.
            val result = withTimeout(deviceTimeout) { nano.summarize(text).last() }
            if (looksValid(result, text)) DeviceResult.Ok(result)
            else DeviceResult.Fail(FallbackReason.InvalidOutput)
        } catch (e: TimeoutCancellationException) {
            DeviceResult.Fail(FallbackReason.DeviceTimeout) // our own timeout, not the caller leaving
        } catch (e: CancellationException) {
            throw e // the caller left: propagate
        } catch (e: NoSuchElementException) {
            DeviceResult.Fail(FallbackReason.InvalidOutput) // last() on a flow that emitted nothing
        } catch (e: Exception) {
            DeviceResult.Fail(FallbackReason.DeviceError) // includes GenAiException
        }

    private fun looksValid(summary: String, source: String) =
        summary.isNotBlank() && summary.length < source.length
}
Enter fullscreen mode Exit fullscreen mode

Three things in that snippet are doing real work. The device path returns a typed result, so a timeout, a thrown GenAiException and an invalid summary land in the dashboard as DeviceTimeout, DeviceError and InvalidOutput instead of one anonymous null, and every success carries the reason it left the device. The catch (e: CancellationException) { throw e } ordering is there because TimeoutCancellationException is itself a CancellationException, so you catch the timeout first and rethrow genuine cancellation, otherwise a user leaving the screen gets recorded as a device failure. The cloud call follows the same rule, because runCatching would swallow cancellation. And looksValid is deliberately dumb: a summary longer than its source is a signal that something is wrong, and the cost of the check is a comparison.

Failure modes at this layer

  • Retry storms on quota errors. If the platform returns BUSY, retrying immediately makes it worse. Back off with jitter for short bursts. Treat PER_APP_BATTERY_USE_QUOTA_EXCEEDED as a longer-horizon quota and use the fallback for the rest of the session.
  • Cloud fallback as a privacy regression. Reviewing a privacy label that says “processed on device” and then discovering a silent server path is how this feature gets pulled. Gate it, log it, and document it.
  • Inconsistent outputs between paths. A device bullet list and a cloud paragraph feel like two different products. Normalize the format at the router boundary.
  • No timeout on the device path. A model that stalls leaves a spinner forever. A hard timeout, with cancellation, is not optional.
  • Counting fallback as success. If your dashboard counts any returned string as a hit, a 70 percent cloud rate hides behind green numbers. Break metrics out by Source.

5. Latency and quality benchmarks

Two questions, and they need different tools: how long does it take and is the answer any good.

Latency: decode is the bill

Google’s announcement reports a Pixel 9 Pro text-to-text rate of about 510 tokens per second for prefill (reading the prompt) and about 11 tokens per second for decode (writing the answer). Those two numbers explain nearly everything about how these features feel. Reading is fast, writing is slow, and the asymmetry is about 46 to 1.

As a first-order approximation, latency is roughly inputTokens / 510 + outputTokens / 11, plus cold-start overhead. It ignores tokenization, safety checks and thermal throttling, so use it for planning, not prediction. I applied it to four representative jobs. These are derived estimates from Google's published figures on one device, not measurements of mine, and they exclude the first-call cost of loading the model.

latency-anatomy

Look at what the chart implies for design:

  • A classifier that emits three tokens finishes in about half a second. It is the cheapest feature you can ship, so build one early.
  • A rewrite of two sentences is dominated by decode. Reading 80 tokens costs almost nothing, writing 60 costs over five seconds. Streaming the output into the UI is not polish, it is the difference between “feels instant” and “feels broken”.
  • Asking for one bullet instead of three cuts the summary from about seven seconds to under four, with the same prompt cost. Output length is the knob you can actually turn.
  • Making the input shorter barely moves the needle for long outputs. Trimming a prompt from 800 to 400 tokens saves under a second.

What the estimates leave out is exactly where the field data will differ: the first call after the process starts (model load), thermal throttling after sustained use, other apps competing for the NPU, and device generation. A mid-range phone with an older Nano version will not match a Pixel 9 Pro.

Measure it yourself

Do not ship a latency claim you did not measure on your own hardware. A small harness that records time-to-first-chunk and total time per run, labeled by device state, is enough. Run it on physical devices only, since emulators do not have the model.

data class RunSample(
    val task: String,
    val firstChunkMs: Long,
    val totalMs: Long,
    val outputChars: Int,
    val warm: Boolean,
    val thermalStatus: Int, // -1 when unavailable (below API 29, or no PowerManager)
)

class NanoBench(private val context: Context) {

    private val power: PowerManager? = context.getSystemService(PowerManager::class.java)

    // currentThermalStatus needs API 29; the GenAI APIs themselves start at 26.
    private fun thermalStatus(): Int =
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) power?.currentThermalStatus ?: -1 else -1

    suspend fun measure(task: String, warm: Boolean, output: Flow<String>): RunSample {
        val clock = TimeSource.Monotonic
        val start = clock.markNow()
        var first = -1L
        var chars = 0
        output.collect { chunk ->
            if (first < 0) first = start.elapsedNow().inWholeMilliseconds
            chars += chunk.length
        }
        return RunSample(
            task, first, start.elapsedNow().inWholeMilliseconds, chars, warm,
            thermalStatus(),
        )
    }
}

fun percentile(sortedMs: List<Long>, p: Double): Long? {
    require(p in 0.0..1.0) { "p must be in [0, 1]" }
    if (sortedMs.isEmpty()) return null
    return sortedMs[((sortedMs.size - 1) * p).roundToInt()]
}
Enter fullscreen mode Exit fullscreen mode

A protocol that has held up for me:

  1. Separate cold from warm. Force-stop the app, run once (cold), then run N more (warm). Report them as two distributions. Blending them gives you a number that describes neither.
  2. Report p50 and p95, not the mean. One thermally throttled run drags a mean around; p95 is what your unluckiest regular user sees.
  3. Record thermal status with every sample. PowerManager.currentThermalStatus (API 29+, so record -1 on older devices) lets you throw out, or at least flag, runs after the device got hot.
  4. Fix the input corpus. Use the same 50 messages, in the same order, on every device, and keep them in version control.
  5. Test with the screen on and the app in the foreground. That is the only condition the platform serves reliably.

Quality: trust the adapters, verify your domain

Google reports benchmark scores for each task comparing the bare base model against the ML Kit GenAI API, and the gap is the argument for using the task clients instead of prompting the base model yourself.

quality-scores

Treat these as a vendor-reported signal about adapter value, not as a measure of your feature. They tell you the adapters help, most for summarization and least for rewriting. They do not tell you whether summaries of your support tickets, in your users’ dialects, are acceptable.

For your own quality bar:

  • Classification is the easiest to grade. Build a labeled set of a few hundred real, anonymized examples, compute accuracy and per-class recall, and track the share of outputs that fail to parse. Separately measure agreement with your cloud path on the same inputs. If the device and the server disagree on 20 percent of cases, your fallback silently changes behavior.
  • Summarization and rewriting need a rubric, not a metric. Score a sample on faithfulness (nothing invented), coverage (nothing important dropped), and tone. A pairwise review of device output against cloud output on 100 items will tell you more than any automatic score.
  • Regression gate on model drift. Because the device-side model is updated outside your release cycle, rerun the labeled set on a device pool on a schedule, not just at release.

Failure modes at this layer

  • Benchmarking on the flagship only. Your median user is not on the phone your team carries.
  • Reporting the warm number. The first call is the one the user’s impression forms around.
  • Letting quality become an unmeasured vibe. Without a labeled set, “it seems fine” survives until a support ticket proves otherwise.
  • Comparing against a cloud model on different prompts. If the prompts differ, the comparison measures your prompts.

What I would ship

Start with the classifier, because three output tokens make it fast, cheap to fallback, and easy to grade. Add summarization next, with streaming and an explicit one-bullet mode for short surfaces. Add rewriting last, because its 256-token input ceiling and decode-heavy latency make it the hardest to make feel good.

Treat availability as a runtime negotiation, make download an explicit, consented, observable state, route through a fallback that records why it fell back, and measure your own devices before you promise anyone a number. The model being on the phone does not make the feature simple. It moves the operational complexity from your servers to your state machine, and your state machine is the part you can test.

Sources: Google’s announcement of the on-device GenAI APIs in ML Kit (tasks, adapters, benchmark scores, Pixel 9 Pro rates); the Prompt API alpha announcement; and the ML Kit developer docs for summarization, rewriting, and the Prompt API. Quota and foreground-restriction behavior comes from the ML Kit GenAI overview and the GenAiException.ErrorCode reference; the Prompt API surface (checkStatus(), download(), warmup(), close()) from the GenerativeModel reference; version caveats from the ML Kit known issues page. The claim that foreground services do not count as foreground is community-reported only. The latency chart is derived arithmetic from Google's published rates, not a measurement.

🧵 Stop Treating Coroutines Like Magic Keywords

If “just add launch and hope” describes how your team handles concurrency, I’d recommend “Kotlin Coroutines Under the Hood” — a 25-chapter deep dive that goes past the syntax and down to the bytecode: the Continuation-Passing Style transform, the compiler-generated state machine, and exactly why a suspended coroutine costs a few dozen bytes while a blocked thread costs a megabyte.

It walks through structured concurrency and Job hierarchies, dispatcher internals (Default vs IO vs Unconfined), cooperative cancellation and exception aggregation, Flow’s cold-stream semantics and the full operator vocabulary, StateFlow/SharedFlow’s hot-broadcast model, Channels and fan-in/fan-out patterns, Mutex/Semaphore/actors for shared state, and a complete Android case study retrofitting a legacy callback-driven app onto coroutines and Flow — including a 100,000-coroutines-vs-100,000-threads benchmark lab you can run yourself.

Top comments (0)