/Learn
Deep dives · Client · front-end design

Front-end architecture for offline, real-time and AI apps

LearnDeep diveTier 2 · MechanismsAnalyze20 minMobile systems

You will be able to: explain front-end architecture for offline, real-time and AI apps and answer its interview questions.

Prove it: Offline-first inspection app with huge uploads

Mobile engineeringReact Native in one place4 of 22Next: Modular React Native for Many Apps: The Modularity Ladder →

What Priya actually saw. The clock, the tick and the amber badge all come from one database query, which is why screens stay simple. Start from the basics in Day 9 →

Study with AI

Part 1 of 5

Basics

What this part of the system is, what it is responsible for, and the vocabulary you need before the mechanics.

1.1Definition

The one-paragraph summary, then where its responsibility starts and stops.

Front ends in data-heavy apps own far more than pixels: what the user sees, each screen's state machine, perceived speed, offline behaviour, real-time updates, streaming AI and accessibility. Strong answers describe these layers as precisely as the backend.

What the front end owns
  • Render immutable UI state derived from a local source of truth
  • Model each screen as a small state machine with explicit loading, empty, error, offline and pending states
  • Own perceived performance: startup, scrolling, image and video memory
  • Handle offline, retries and conflicts visibly and honestly
  • Integrate real-time sockets and streaming AI responses smoothly
  • Meet accessibility and localisation requirements by default
What it must not do
  • Call the network from views or composables
  • Keep business rules in UI code
  • Block the main thread with parsing, hashing or database work
  • Hide failures behind infinite spinners
  • Encode meaning with colour alone

1.2Patterns and terms

The words used in the rest of this page.

TermMeaning
Loading / empty / content / errorThe four base states every list screen must design.
Pending / synced / conflict / failedPer-row sync states for offline-first data.
Optimistic updateShow the change immediately and reconcile when the server answers.
SkeletonPlaceholder shapes that match final layout, used only on first load.
Stale-while-revalidateShow cached data, refresh in the background, update in place.
Idempotent intentsA double tap produces the same result as a single tap.

1.3Key concepts

Ideas this deep dive relies on, in one sentence each.

01Outbox

Table of pending local writes, committed in the same transaction as the data, drained by the sync engine.

02WorkManager

Android library for deferrable, guaranteed background work.

1.4One screen, end to end

A concrete example first, so the mechanics have something to attach to.

Take the job detail screen in the inspection app. When it opens, the ViewModel subscribes to a database query for the job, its answers and its media. The first frame renders from SQLite in about 50 ms, before any network activity.

The technician changes an answer. The ViewModel sends an intent to the repository, which writes the answer and an outbox row in one transaction. The query emits again, the reducer produces a new immutable state with that field marked pending, and Compose recomposes only that row.

In the background, the sync engine pushes the change and the server returns the supervisor’s edit to the instructions. The same query emits again; the instructions update in place and a small ‘Updated by Priya’ label fades in. No screen code knows the network exists.

If the push returns a conflict, the row’s state becomes conflict, the reducer maps it to an amber badge, and tapping it navigates to the resolver. The team designed, named and screenshot-tested every one of these states before the feature shipped.

Part 2 of 5

Question

Know what you are reading for. These are the questions this deep dive prepares you to answer, and the rounds where they come up.

2.1Target questions

Keep them in mind while you read the detail.

  1. How do you structure a screen in an offline-first app?
  2. How do you make a list of 10,000 items smooth on a cheap phone?
  3. How do you design for failure in the UI?
  4. What changes in the front end when you add AI?

Model answers are in part 4, after the detail that supports them.

2.2Interview rounds

System design rounds where this component is part of a strong answer.

Part 3 of 5

Detailed answer

How it actually works: the components, the states it moves through, a full run, and the code.

3.1Client architecture

The parts and how they connect.

UIPRESENTATIONDATAScreensCompose · SwiftUI ·ReactDesign systemtokens · componentsNavigationtyped routes · deeplinksViewModel / storeintents → reducerUI stateimmutable · perscreenEffectsnavigation · toastsRepositoriesread · write +outboxLocal DBRoom · GRDB ·SQLiteReal-timeWebSocket · SSESync enginebackgroundTransfer managermediaAI clientstream · toolsintentsreduce1 txnobserveapply
ClientServiceData storeAI component
Boxes are components; arrows show calls and data flow.
Unidirectional data flow
Views send intents; a ViewModel or store reduces intents and data changes into one immutable state object; views render it. This is MVI on Android, the same shape with @Observable models or TCA on iOS, and a Zustand or Redux store in React.
Observe, don’t fetch
Screens subscribe to database queries. Network results go into the database, which updates the screen. That gives offline support, instant reopening and one source of truth.
Effects
One-off events such as navigation, toasts and haptics are separate from state, so rotating the device or recomposing does not repeat them.
Real-time and streaming
Sockets and server-sent events are data sources like any other: they write to the database (chat) or to a stream buffer (AI tokens) that the reducer consumes.
Design system
Tokens and components with accessibility built in. Screens compose components; they don’t restyle them.

3.2A user action through the layers

One run, step by step.

UserViewViewModelRepositoryLocal DBtap ‘Valve 3: leaking’Intent.SetAnswersetAnswer()row + outbox (1 txn)query emitsreduce → new UiStatestate (field pending)updated in < 16 msLater: sync writes server changes to the DBquery emits againstate (synced)
Solid arrows are calls; dashed arrows are responses.
  1. The view never waits for the network; the user sees their change in the same frame.
  2. The same observation path delivers local edits, sync results and real-time updates, so you test one code path.

3.3Code

Working code for the core of it.

MVI ViewModel with a reducer (Kotlin, Compose)

mvi-viewmodel-reducer.ktKotlin
1data class JobUi(val title: String = "", val fields: List<FieldUi> = emptyList(),2                 val banner: Banner? = null, val loading: Boolean = true)3 4sealed interface JobIntent { data class SetAnswer(val fieldId: String, val value: String) : JobIntent; data object Retry : JobIntent }5 6class JobViewModel(private val jobId: String, private val repo: JobRepo, net: NetworkMonitor) : ViewModel() {7  val ui: StateFlow<JobUi> = combine(repo.observeJob(jobId), repo.observeFields(jobId), net.online, repo.pendingCount()) { job, fields, online, pending ->8    JobUi(9      title = job.title,10      fields = fields.map { it.toUi() },                                  // each carries its sync badge11      banner = when { !online && pending > 0 -> Banner.Offline(pending); fields.any { it.conflict } -> Banner.NeedsReview; else -> null },12      loading = false,13    )14  }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), JobUi())15 16  fun onIntent(i: JobIntent) = viewModelScope.launch {17    when (i) {18      is JobIntent.SetAnswer -> repo.setAnswer(jobId, i.fieldId, i.value)   // row + outbox, returns fast19      JobIntent.Retry -> repo.retryFailed(jobId)20    }21  }22}
22 linesUTF-8Kotlin

The same state in a Compose screen (Kotlin)

same-state-compose.ktKotlin
1@Composable2fun JobScreen(vm: JobViewModel) {3  val ui by vm.ui.collectAsStateWithLifecycle()                      // stops collecting in the background4  Scaffold(topBar = { TopAppBar(title = { Text(ui.title) }) }) { pad ->5    LazyColumn(contentPadding = pad) {6      ui.banner?.let { b ->7        item(key = "banner") { BannerRow(b, onRetry = { vm.onIntent(JobIntent.Retry) }) }8      }9      items(ui.fields, key = { it.id }) { field ->                      // stable keys: rows keep their state10        FieldRow(field, onChange = { v -> vm.onIntent(JobIntent.SetAnswer(field.id, v)) })11      }12    }13    if (ui.loading) LinearProgressIndicator(Modifier.fillMaxWidth().padding(pad))14  }15}
15 linesUTF-8Kotlin

React web dashboard: cached queries plus live invalidation

react-web-dashboard.tsxTypeScript JSX
1function useJobs(region: string) {2  const qc = useQueryClient();3  const jobs = useQuery({ queryKey: ['jobs', region], queryFn: () => api.jobs(region), staleTime: 30_000 });4  useEffect(() => {5    const ws = new WebSocket(WS_URL + '?region=' + region);6    ws.onmessage = e => {7      const change = JSON.parse(e.data);8      qc.setQueryData(['jobs', region], (old: Job[] | undefined) => upsert(old ?? [], change.job));   // patch in place9    };10    return () => ws.close();11  }, [region, qc]);12  return jobs;13}
13 linesUTF-8TypeScript JSX

3.4Tested code, explained

A working implementation, then what each part does and why.

Every state a row can show

Name the states before you build the screen. The compiler then makes sure no screen forgets one.

RowUi.ktKotlin
1/** Everything one row can show. The compiler makes every screen handle all of them. */2sealed interface RowUi {3  data object Synced : RowUi4  data object Pending : RowUi5  data class Conflict(val mine: String, val theirs: Theirs) : RowUi6  data class Failed(val reason: String) : RowUi7}8 9/** A pure function: the same row always draws the same way, so it needs no network to test. */10fun rowUi(job: Job): RowUi = when (job.syncState) {11  SyncState.SYNCED -> RowUi.Synced12  SyncState.PENDING -> RowUi.Pending13  SyncState.CONFLICT -> {14    val theirs = checkNotNull(job.theirs)15    RowUi.Conflict(job.answers[theirs.field].orEmpty(), theirs)16  }17  SyncState.FAILED -> RowUi.Failed(job.error ?: "Could not save")18}
18 linesUTF-8Kotlin
sealed interface RowUi
A closed list. Adding a state breaks the build wherever it isn't handled.
fun rowUi(job: Job)
A pure function, with no network or clock involved, so a test needs only a row.
RowUi.Conflict(job.answers...
Carries both values, so the resolver screen has what it needs.

Compiled and tested by npm run test:mobile.

A screen as one mapping

The whole list is a transformation of one database query. That's why the screen needs no sync logic.

RowUi.ktKotlin
1data class JobRow(val id: String, val ui: RowUi)2data class ListSummary(val rows: List<JobRow>, val ticks: Int, val needsReview: Int)3 4/** The whole screen is one mapping over the database query. It never mentions the network. */5fun jobList(db: LocalDb): Flow<ListSummary> = db.jobs6  .map { jobs ->7    val rows = jobs.values.sortedBy { it.id }.map { JobRow(it.id, rowUi(it)) }8    ListSummary(rows, rows.count { it.ui is RowUi.Synced }, rows.count { it.ui is RowUi.Conflict })9  }10  .distinctUntilChanged()
10 linesUTF-8Kotlin
db.jobs.map { ... }
Each commit produces one new screen state, whoever made the change.
distinctUntilChanged()
If a sync changed nothing visible, nothing redraws.
val ticks: Int
The eleven green ticks and one amber badge are simply counts of this list.

Compiled and tested by npm run test:mobile.

Redrawing only what changed

140 pulled changes may touch three rows on screen. Compose and RecyclerView do this for you, and this is the idea underneath.

RowUi.ktKotlin
1/** Which rows must redraw. 140 pulled changes may touch only a few rows on screen. */2fun changedRows(old: List<JobRow>, new: List<JobRow>): Set<String> {3  val before = old.associateBy { it.id }4  return new.filter { before[it.id] != it }.map { it.id }.toSet()5}
5 linesUTF-8Kotlin
old.associateBy { it.id }
Looks up each row's previous state in constant time.
before[it.id] != it
Data classes compare by value, so an unchanged row doesn't redraw.

Compiled and tested by npm run test:mobile.

3.5Per-platform toolkit

Android

  • Jetpack Compose, ViewModel + StateFlow, Hilt, Room with Flow, Paging 3.
  • Coil for images, Media3 for video, WorkManager for background work.
  • Baseline Profiles and Macrobenchmark for startup and scroll; JankStats in production.
  • Paparazzi or Roborazzi screenshot tests; Maestro for end-to-end flows.

iOS

  • SwiftUI with @Observable models or TCA; UIKit collection views for very heavy lists.
  • GRDB ValueObservation or SwiftData @Query for reactive data.
  • Nuke or Kingfisher for images; AVFoundation for media.
  • Instruments and MetricKit for performance; swift-snapshot-testing and XCUITest.

React Native

  • New Architecture (Fabric, Turbo Modules, JSI) with Hermes.
  • FlashList for lists, expo-image or FastImage, Reanimated for animations on the UI thread.
  • WatermelonDB or op-sqlite for reactive local data; Zustand or Redux Toolkit for UI state.
  • Flashlight and the Hermes profiler; Detox or Maestro for flows.

Web dashboards

  • React with TypeScript, TanStack Query for server state, WebSockets or SSE for live updates.
  • Virtualised tables for large lists; charts with accessible data tables.
  • Playwright for end-to-end tests; Storybook with visual regression for components.
Part 4 of 5

Q&A

The questions from part 2, now with model answers. Try each one out loud before opening it.

4.1Front-end interview questions

How do you structure a screen in an offline-first app?
Unidirectional data flow: the view sends intents; the ViewModel writes through a repository and observes database queries; a reducer produces immutable state with explicit loading, empty, error, offline and per-row sync states; effects are separate.
How do you make a list of 10,000 items smooth on a cheap phone?
Paged reads from the local database, virtualisation with stable keys and content types, flat item layouts, images decoded to display size off the main thread, and production frame metrics.
How do you design for failure in the UI?
Every async state is named and designed: pending, failed with a reason and retry, conflict with a resolver, offline with a count. No infinite spinners, and nothing claims success before the source of truth confirms it.
What changes in the front end when you add AI?
Streaming rendering with buffering, visible tool progress, structured action cards for confirmations, cancel and retry, feedback capture tied to prompt versions, and a non-AI fallback path.
Part 5 of 5

Extra depth

Practical context for real projects: which technology to pick, what successful teams do, what to measure and the edge cases to plan for.

5.1Choices and when to pick them

Show detailsHide details
NeedOptionsWhen to pick
State managementMVI/UDF · TCA · Zustand · Redux Toolkit · TanStack QueryUDF everywhere; TanStack Query for server state on the web; a store for cross-screen UI state.
Local reactive dataRoom · GRDB · SwiftData · WatermelonDB · op-sqliteWhatever gives observable queries on SQLite on your platform.
ListsLazyColumn · UICollectionView · FlashList · virtualised tablesStable keys, content types, fixed or estimated sizes.
Images and mediaCoil · Nuke · Kingfisher · expo-image · Media3 · AVPlayerRequest sized images; one active video player.
TestingScreenshot tests · Maestro · Detox · XCUITest · PlaywrightScreenshots for every state; a few end-to-end flows for critical paths.
Feature deliveryFeature flags · server-driven UI · OTA for JS (EAS Update)Flags for every risky change; SDUI only for content screens.

5.2Front-end metrics

Show detailsHide details
MetricWhy it matters
Cold start to first meaningful content (p50, p90 by device class)The first impression; set a budget per tier.
Dropped or slow frames during scrollSmoothness on real devices, not flagships.
Time from tap to visible changeShould be one frame for local writes.
Crash-free and ANR-free sessionsRelease gates.
Share of screens shown from cacheShows offline-first actually working.
Accessibility issues found in CIKeeps the bar from slipping.

5.3Hard cases

Show detailsHide details
CaseHow it is handled
Process death mid-flowPersist screen state with SavedStateHandle or SceneStorage; reload from the database on return.
Configuration change repeats a toast or navigationModel one-off effects separately from state.
List jumps when data updatesStable keys, reserved image sizes, and insert-above only on user request.
Thousands of rows update at once during syncBatch database writes per page so observers emit once.
Streaming text causes jankBuffer tokens and render in 50 ms batches; re-parse only the last paragraph.
Right-to-left and large fonts break layoutsScreenshot tests in those variants; avoid fixed heights for text.
AI Engineer · Front-end architecture for offline, real-time and AI apps