Resilient Streaming Chat Client for Android with MVVM and UDF
System DesignModel answerLast updated
Design a layered Android client for an LLM chat app covering streaming, cancellation, retries, offline history, immutable UI state, and lifecycle and process-death handling.
Problem
You are designing the client side of a conversational AI app for Android. Users can browse earlier conversations, type a prompt, watch the model's answer appear incrementally as it streams in, and search through old sessions.
Propose an architecture that stays correct on flaky networks, survives screen rotation and backgrounding, and remains easy for a large team to extend and test.
Requirements
Functional
- Streaming chat and history: Prompts are sent to a backend that streams the reply (Server-Sent Events or WebSocket). Past conversations and messages are loaded through a paginated REST API.
- Cancel and retry: The user can stop a reply while it is being generated. Failed calls should be retried with exponential backoff, or manually by the user.
- Offline reading: Any conversation the user has already opened must remain readable without a connection.
Non-functional
- Unidirectional data flow: State flows down, events flow up, with clear ownership at each layer.
- Lifecycle safety: No leaks, and no duplicate network calls caused by rotation or backgrounding.
- Testability: Business logic must not depend on Android framework classes.
What your answer should address
- Layers: Responsibilities of the presentation layer (Compose and ViewModel), the domain layer (use cases), and the data layer (repository and data sources).
- UI state: An immutable model for loading, in-progress streamed text, errors, and completed output, designed so contradictory states cannot be expressed.
- Concurrency: How you use coroutines and Flow (
StateFlow,SharedFlow, dispatchers, structured cancellation) for background work. - Data management: How the repository coordinates the network (Retrofit/OkHttp) with local storage (Room).
- Edge cases: Configuration changes, process death (
SavedStateHandle), and connections that drop mid-stream.
State any assumptions about scale and scope up front, and call out the trade-offs behind your main decisions.
Hints
Hint 1
Make the local database the single source of truth: network results are written to it, and the UI only observes it. Consider which problems this removes (rotation, offline, pagination).
Hint 2
Split UI state into independent fields (input text, history load status) plus a sealed type for the mutually exclusive generation phase (idle, submitting, streaming, failed). Ask which combinations should be unrepresentable.
Hint 3
Think about what happens to a stream when the user cancels, when the connection drops, and when the process is killed. What identifiers or sequence numbers would let you resume or deduplicate safely?
Hint 4
Emitting UI state or writing to disk on every token is expensive. Consider batching or conflating updates and checkpointing periodically.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Assumptions and scale
- History: up to a few thousand conversations per user, a few hundred messages each, loaded in pages of 20 to 50.
- Streaming: roughly 20 to 100 tokens per second. Pushing one UI update per token is wasteful given a ~16 ms frame budget.
- Offline: read-only for previously opened conversations. Queuing prompts while offline is out of scope for v1.
- One active generation per conversation. Search runs locally over cached messages, with server search as an online fallback.
2. API contract
GET /conversations?cursor&limitandGET /conversations/{id}/messages?cursorreturn{items, nextCursor}.POST /conversations/{id}/messageswith{clientMessageId, prompt}returns an event stream:message_start,delta{seq, text},done,error.GET /messages/{id}returns the final message, used for recovery.
Two design details matter. clientMessageId acts as an idempotency key so a retried POST cannot create a duplicate turn. seq on each delta allows deduplication and resumption after a drop.
3. Local data model
Room is the source of truth. Messages carry a status (PENDING, STREAMING, COMPLETE, FAILED, CANCELLED) and the last received seq. A remote-keys table stores pagination cursors for Paging 3's RemoteMediator. An FTS table over message content gives offline search.
4. Layers
Presentation. Composables are stateless: they render a UiState and emit events (Send, Cancel, Retry, Search). The ViewModel reduces events into one StateFlow. One-off effects such as snackbars and navigation go through a buffered Channel exposed as a Flow.
Domain. Pure Kotlin with no Android imports. Use cases such as SendPrompt, ObserveConversation, CancelGeneration and SearchMessages hold rules like rejecting blank prompts and allowing only one active generation per conversation. They map data models to domain models.
Data. The repository coordinates Retrofit/OkHttp and Room and returns Flows backed by the database. Network responses are written to Room and never passed directly to the UI. Dependencies are injected via interfaces (for example with Hilt), so tests can use fakes.
5. UI state
data class ChatUiState(
val messages: List<Message> = emptyList(),
val input: String = "",
val generation: Generation = Generation.Idle,
val historyLoad: LoadState = LoadState.Loaded)
sealed interface Generation {
data object Idle : Generation
data class Submitting(val clientId: String) : Generation
data class Streaming(val clientId: String, val partial: String) : Generation
data class Failed(val clientId: String, val error: ErrorUi, val retryable: Boolean) : Generation
}
Orthogonal concerns live in the data class; the mutually exclusive phase is a sealed type, so "streaming and failed at once" cannot exist. The Send button is enabled only in Idle or Failed. Finalized text is not a separate UI state: it arrives in messages from Room and generation returns to Idle.
6. Concurrency
- The ViewModel keeps a
Jobfor the active generation, ignoringSendif it is active, andCancelsimply cancels it. - The stream is wrapped in
callbackFlowwithawaitClose { eventSource.cancel() }, so cancelling the coroutine closes the socket. Optionally call a server cancel endpoint so the backend stops generating. - On completion after cancellation, the repository marks the message
CANCELLEDand keeps the partial text. - Dispatchers are injected; the repository uses
flowOn(io). Retrofit and Room suspend functions are already main-safe. - Apply
conflate()or time-based batching so the UI renders at most once per frame. - State is exposed with
stateIn(viewModelScope, WhileSubscribed(5_000), initial). The 5-second grace period survives rotation without restarting upstream work and stops database observation when the app is backgrounded.
Retries. Use retryWhen for IOException with exponential backoff plus jitter, capped at about 3 attempts. Retry only idempotent calls or ones protected by clientMessageId. Non-retryable errors (4xx, policy rejections) go directly to Failed(retryable = false).
7. Repository flow
History: Paging 3 with a RemoteMediator. The UI reads from Room; the mediator fetches a page and upserts items and remote keys in one transaction.
Sending:
- Insert the user message as
PENDINGso it shows instantly. - Open the stream; on
message_startinsert the assistant row asSTREAMING. - Accumulate deltas in memory and emit partial text upward.
- Checkpoint to Room about once per second or every ~200 tokens, storing
lastSeq. Writing every token would cause write amplification and constant Flow invalidations. - On
done, write final content asCOMPLETE.
Offline: Room serves cached data; the UI shows a stale or offline indicator, and Send is disabled or fails fast with a clear message.
8. Lifecycle and failure cases
- Rotation: The ViewModel and its job survive, and
StateFlowreplays the latest state to the new composition. Collect withcollectAsStateWithLifecycle. - Backgrounding: Decide whether generation continues. For short replies keep it in
viewModelScope; for guaranteed completion hand off to a foreground service or WorkManager. Otherwise the grace period lapses, observation stops, and the stream is cancelled. - Process death: Persist in
SavedStateHandleonly small items: conversation id, draft input, and the in-flightclientMessageId. Everything else is rebuilt from Room. On restart, rows still markedSTREAMINGare stale. - Dropped stream: Retry with backoff. If the server supports resume, reconnect with the last
seqand drop duplicates. Otherwise fetch the final message by id; if it is unavailable, markFAILEDwith the partial text kept and offer Retry. - Duplicate sends: Prevented by the active-job check plus the idempotency key.
9. Testing
Use cases and ViewModels take interfaces and injected dispatchers, so tests use fakes with kotlinx-coroutines-test and Turbine to assert state sequences (Idle, Submitting, Streaming, Idle). Use an in-memory Room database for DAO and mediator tests, and MockWebServer for stream parsing and drop scenarios.
Common mistakes
- Letting the UI observe network responses directly, which breaks offline support and rotation.
- Modeling state with several booleans (
isLoading,isStreaming,hasError) that can contradict each other. - Using
SharedFlowfor state, orChannelwithout a buffer, and losing events. - Not tying the network call to coroutine cancellation, leaving a socket open after the user leaves.
- Writing to the database or emitting UI state for every token.
- Retrying non-idempotent POSTs without an idempotency key.