Latency, cost and fallbacks
Why it matters
- A long blank screen on a phone feels like a crash; users close the app and leave bad reviews. Streaming and timeouts are the difference between a usable feature and a support ticket.
- Every token you send costs money. Without input caps and per-user rate limits, one power user can spike your monthly bill significantly.
- Interviewers at senior level ask how you degrade gracefully when the model service is down, the device is unsupported, or the network drops. A one-line 'show an error' answer is not enough.
- Latency, cost, and fallback decisions interact with the other lessons in this module: you cache to save cost, you filter output for safety, and you version prompts so a bad rollout can be rolled back without an app release.
The simple explanation
- Ordering food at a restaurant: dishes come out as they are ready (streaming), the kitchen has a maximum wait (timeout), and if the dish is not ready you get a free appetiser (fallback).
- The kitchen (server) tracks how many orders each table has placed per hour (rate limit) so one table cannot starve the others.
- You cap the menu description length (token cap) so the chef is not reading a novel.
- If the kitchen is closed, the host offers a pre-made sandwich (cached answer) instead of sending you home (blank screen).
Every AI call in an Android app has three failure modes: it is slow, it is expensive, or it fails outright. You must handle all three or users will close the app.
Latency. A single LLM call can take several seconds. On a phone, that is a long time. Stream the response with Flow so the user sees text appear token by token. Set a hard timeout with withTimeout so the UI never hangs. Note it limits the whole call, so for long streams also consider a time-to-first-chunk limit. Show a skeleton or typing indicator while waiting.
Cost. Each call costs money per token. Cap the input length (roughly 4 characters per token) so a user cannot paste a huge document. Cache repeated prompts in Room or an in-memory Map. On the server, rate-limit per user and set a daily budget alert. Pick the smallest model that passes your eval set; check the current docs for supported models and devices.
Fallbacks. The service will go down. The device may not support on-device inference. The network may drop. Always have a fallback path: a cached answer, a static message, or a degraded feature. Never show a blank screen or a raw stack trace.
| Concern | Client side | Server side |
|---|---|---|
| Latency | withTimeout, streaming Flow | queue, autoscale |
| Cost | cap tokens, cache | per-user rate limit, budget alert |
| Failure | fallback UI, retry with backoff | circuit breaker, health check |
The API key must live on the server. Never put it in BuildConfig or in the APK. The server proxy adds auth, rate limiting, and logging before forwarding to the model provider.
Notes
- Stream responses with
Flowso users see text appear immediately; a long blank screen feels like a crash. - Set a hard timeout with
withTimeoutso the coroutine is cancelled and the UI recovers. - Cap input tokens on the client (roughly 4 characters per token) to prevent runaway cost from long pasted text.
- Cache repeated prompts in Room or an in-memory
Mapkeyed by user id and a hash of the prompt. - Rate-limit per user on the server; a single user should not be able to exhaust your monthly budget.
- Always provide a fallback: a cached answer, a static message, or a 'try again' button. Never show a blank screen.
- The API key stays on the server. Never put it in
BuildConfig,local.properties, or the APK. - Pick the smallest model that passes your eval set; check the current docs for supported models and devices.
- On-device models are downloaded and versioned separately from the APK; handle download failures and storage limits.
- Log latency, token count, and fallback rate as online metrics so you can spot regressions before users complain.
Code example
This repository shows the four guardrails in one Flow: cache lookup, per-user rate limit, input token cap, and a timed-out stream with a fallback message on failure.
// Repository: AI call with cache, timeout, token cap, and fallback
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.withTimeout
class AiRepository(
private val api: AiApi, // server proxy; holds the API key
private val cache: AiCache, // Room or in-memory
private val rateLimiter: RateLimiter,
) {
fun ask(userId: String, prompt: String): Flow<String> = flow {
// 1. Serve from cache if available
cache.get(userId, prompt)?.let { emit(it); return@flow }
// 2. Enforce per-user rate limit
if (!rateLimiter.allow(userId)) {
emit("Slow down, please try again shortly.")
return@flow
}
// 3. Cap input tokens (rough: 4 chars per token)
val capped = prompt.take(MAX_INPUT_CHARS)
// 4. Stream with a hard timeout; fall back on any failure
try {
withTimeout(REQUEST_TIMEOUT_MS) {
api.stream(capped, userId).collect { chunk ->
emit(chunk)
}
}
} catch (e: TimeoutCancellationException) {
emit("The request took too long. Please try again.")
} catch (e: CancellationException) {
throw e // the collector was cancelled: do not emit anything
} catch (e: Exception) {
emit("AI is unavailable right now. Try again later.")
}
}
}
private const val MAX_INPUT_CHARS = 2048
private const val REQUEST_TIMEOUT_MS = 15_000LwithTimeoutcancels the block and throwsTimeoutCancellationException; thecatchblock emits a user-facing fallback string instead of crashing. It must come before theCancellationExceptioncatch, because it is a subclass.- Any other
CancellationExceptionis re-thrown so leaving the screen stops the flow cleanly. - Saving the full answer into the cache after a successful stream is left out for brevity.
- The cache check runs before the rate limiter so a cached hit costs zero server requests and does not count against the limit.
MAX_INPUT_CHARSis a rough token cap; in production you would call a tokenizer or let the server reject over-length prompts with a 413.
Run the idea in plain Kotlin
data class AiRequest(val prompt: String, val userId: String)
data class AiResponse(val text: String, val cached: Boolean, val fallback: Boolean)
class AiService {
private val cache = mutableMapOf<String, String>()
private val requestCount = mutableMapOf<String, Int>()
private val maxPerMinute = 3
private val maxInputChars = 128
fun handle(req: AiRequest): AiResponse {
val key = req.userId + ":" + req.prompt
cache[key]?.let { return AiResponse(it, cached = true, fallback = false) }
val count = requestCount[req.userId] ?: 0
if (count >= maxPerMinute) {
return AiResponse("Rate limited. Try again later.", cached = false, fallback = true)
}
requestCount[req.userId] = count + 1
val capped = req.prompt.take(maxInputChars)
return try {
val result = simulateCall(capped)
cache[key] = result
AiResponse(result, cached = false, fallback = false)
} catch (e: Exception) {
AiResponse("AI unavailable. Showing default text.", cached = false, fallback = true)
}
}
private fun simulateCall(prompt: String): String {
if (prompt.contains("fail")) throw RuntimeException("simulated failure")
return "Answer for: " + prompt.take(30)
}
}
fun main() {
val svc = AiService()
val u = "user-1"
val r1 = svc.handle(AiRequest("Summarize the news", u))
println("Call 1: cached=" + r1.cached + " fallback=" + r1.fallback + " -> " + r1.text)
val r2 = svc.handle(AiRequest("Summarize the news", u))
println("Call 2: cached=" + r2.cached + " fallback=" + r2.fallback + " -> " + r2.text)
val r3 = svc.handle(AiRequest("fail this one", u))
println("Call 3: cached=" + r3.cached + " fallback=" + r3.fallback + " -> " + r3.text)
for (i in 4..6) {
val r = svc.handle(AiRequest("query " + i, u))
println("Call " + i + ": " + r.text)
}
}In production
- Users on 3G saw a blank chat screen for a long time after tapping send.
- Ratings dropped; support tickets mentioned 'app frozen'.
- The client waited as long as the server kept the connection open, with no app-level timeout, so users waited until the server responded or they force-closed.
- Added
withTimeout(15_000)around the streaming call in the repository. - Showed a skeleton UI and a 'Still thinking…' label while waiting.
- On timeout, emitted a cached answer or a 'Try again' button instead of leaving the screen blank.
- Added a p95 latency dashboard alert so the team was notified before users complained.
- A user pasted a very long document into the prompt field and sent it repeatedly.
- The server charged per token; the monthly bill spiked significantly.
- No input cap existed on the client, and the server had no per-user rate limit.
- Capped input at 2 048 characters on the client with a 'text too long' message.
- Added a per-user rate limit on the server proxy.
- Set a daily spend alert in the cloud billing dashboard.
- Logged token count per request so the team could spot outlier users.
Common mistakes
- No timeout on AI network calls. A slow server can keep the coroutine waiting far longer than a user will. The user sees a frozen UI. Always wrap the call in
withTimeoutand emit a fallback string onTimeoutCancellationException. - No fallback when the service is down. The model service will have outages. If the only path is a raw error toast, the feature is unusable during the outage. Provide a cached answer, a static message, or a degraded mode.
- Caching sensitive user data carelessly. A prompt that contains a medical question or a work email should not sit in a long-lived cache or get copied into backups. Prefer on-device processing for sensitive data and clear the cache on sign-out. See the Privacy lesson in this module.
- No per-user rate limiting. One user can exhaust your monthly budget or trigger a provider quota error that blocks all users. Rate-limit on the server, not just the client, because the client can be bypassed.
- Not streaming, showing a blank UI for a long time. Users perceive a long wait as a crash. Stream tokens with
Flowand update the UI incrementally so the first character appears quickly. - Hardcoding model names or API keys in the APK. A model name baked into the APK cannot change without a Play Store release. Keep model names and prompts in server config or Firebase Remote Config. The API key must never appear in
BuildConfigor in the APK; it stays on the server.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How do you handle AI latency in a mobile app?”
“How do you control the cost of an AI feature?”
“What do you do when the AI service is unavailable?”
“How do you decide which model to use for a feature?”
Quiz
What is the primary reason to stream an AI response instead of waiting for the full text?
Where should the API key for a model provider live in an Android app?
A user pastes a very long document into an AI prompt field. What is the correct client-side response?
What should happen when withTimeout fires during a streaming AI call?
0 of 4 answered
Mini task
Add a timeout and fallback to an existing AI call (15 min)
- Open the repository or use-case that calls your AI server. Find the function that returns a
Flow<String>or asuspendresult. - Wrap the existing call in
withTimeout(15_000). CatchTimeoutCancellationExceptionand emit a fallback string such as "The request took too long. Try again." - Add a second
catch (e: Exception)block that emits a generic "AI is unavailable" message. Make sure the UI collects theFlowand renders whatever string is emitted, including fallbacks. - Add a simple in-memory
Map<String, String>cache keyed by a hash of the prompt. Check the cache before calling the server. Skip the cache for prompts that contain personal data (check with your privacy owner). - Add a
maxInputCharsconstant (for example 2 048). Truncate the prompt with.take(maxInputChars)before sending. Show a snackbar if the original prompt was longer. - Done condition: the UI shows a fallback message within 15 seconds when the server is unreachable (simulate by pointing the base URL to
http://10.255.255.1), the cache serves a repeated prompt without a network call, and a long input is truncated with a visible snackbar.