Mobile App Architecture: Layers, Patterns & Offline-First
Every mobile app has an architecture, whether anyone chose it or not. Here is how we structure Presentation, Domain, and Data layers, choose between MVVM, MVI, and VIPER/TCA, and engineer offline-first outbox queues that survive flaky cellular networks.

On this page

A mobile app architecture has to survive conditions that backend and web code rarely meet. Your code runs on battery-restricted hardware you don't own. The operating system kills it without warning when memory gets tight, and cellular connections drop packets mid-transaction in elevators and subways. Every app ends up with some architecture whether or not anyone chose it. What you control is whether the layers isolate change, or whether UI views, network calls, and caching flags get so tangled that fixing a button on the checkout screen breaks user onboarding.
As CTO at Idealogic, I've architected greenfield iOS, Android, React Native, and Flutter systems and audited legacy mobile apps that stalled twelve months after launch. This guide lays out the blueprint we use for modern app architecture across client builds: the three-layer Clean Architecture model, MVVM vs MVI vs VIPER vs TCA, offline-first apps built on transactional outbox queues, feature modularization for fast incremental builds, and hardware-backed security boundaries.
The short version
- Three layers make up modern app architecture on mobile: the Presentation layer (declarative UI + unidirectional state holders), the Domain layer (pure business rules and use cases), and the Data layer (repositories over local SQLite/Room storage and remote APIs). Dependencies point inward.
- Unidirectional Data Flow (UDF) keeps screen state from drifting out of sync. UI views never mutate state directly; they dispatch immutable user intents to a ViewModel or Store, which updates a single source of truth that the screen observes.
- Match the presentation pattern to screen complexity: MVVM + StateFlow/
@Observableis our default for most SwiftUI and Jetpack Compose apps, while MVI / Redux / TCA pays for its extra ceremony on multi-step state machines like trading tickets and checkouts. - Offline-first architecture needs a local Single Source of Truth (SSOT) and an outbox queue: the UI reads from on-device SQLite, Room, SwiftData, or WatermelonDB, writes optimistic mutations locally first, and relies on a background worker with idempotency keys to reconcile with the server.
- Modularize by feature once the team grows. Splitting
:feature:*and:core:*modules keeps incremental Gradle and Xcode builds short and stops cross-feature coupling. - Put OWASP MASVS security in the Data layer: hardware-backed token storage (iOS Keychain / Android Keystore), SQLCipher database encryption, and TLS certificate pinning belong inside repositories and network interceptors, never inside UI components.
What is mobile app architecture (and why web patterns fail on phones)?
Mobile app architecture is the set of layers, boundaries, and data-flow rules that decide where UI, business logic, storage, and networking code live in a phone app. A mobile application architecture also has to handle failures that a web front end mostly ignores.
On the web, a browser tab is largely stateless: the server holds the canonical database over a stable connection, and if a user hits refresh, the page re-fetches clean state in milliseconds. When teams bring that thin-client mindset into how to build a mobile app, they wire fetch() calls directly inside useEffect hooks, SwiftUI .onAppear blocks, or Android Fragments.
That approach works in an office Wi-Fi demo and collapses in production under four mobile-specific pressures:
- OS process death and lifecycle eviction: When a user backgrounds your app to take a phone call or snap a high-resolution photo, iOS and Android routinely kill your app's process in RAM while keeping its screenshot in the recent-apps switcher. When the user taps back into your app ten minutes later, an architecture that stored transient state only in memory crashes or dumps the user back to the home screen, losing their half-completed form.
- Intermittent connectivity and cellular handoffs: Switching from home Wi-Fi to 5G in an elevator can create a "lie-fi" window of several seconds where the OS reports an active radio link but packets don't get through.
- Strict 8ms to 16ms main-thread frame budgets: On 120Hz ProMotion iPhones and flagship Android displays, the UI thread has a nominal 8.3 milliseconds per frame to compute layout and render pixels. Parsing a 2 MB JSON payload or querying SQLite synchronously on the main thread drops frames immediately and, if the thread stays blocked, ends in an Android Application Not Responding (ANR) error.
- Long-tail binary versions in the wild: Unlike web deploys, a meaningful share of mobile users stay on binaries shipped weeks or months ago. Your client Data layer must tolerate new unknown enum values and optional API fields without throwing deserialization exceptions.
NIST's analysis of software testing infrastructure (Planning Report 02-3) found that the later a defect is caught, the more it costs to fix. Structural mistakes tend to surface late. That's why we separate the client into explicit layers in Week 1.
The 3-layer Clean Architecture model for modern mobile apps
The mobile app architecture diagram below shows the three layers and the cross-cutting concerns that support each of them.
Both the official Android Developers Guide to App Architecture and current iOS and cross-platform practice converge on a three-layer model, on Android and iOS alike. Google's guide treats the Domain layer as optional. The model is governed by the Dependency Rule: outer layers may depend on inner layers, but inner layers know nothing about outer layers.
Layer 1: Presentation layer in mobile app architecture and Unidirectional Data Flow (UDF)
In declarative UI frameworks (SwiftUI, Jetpack Compose, React Native, and Flutter), UI is a pure function of state: UI = f(State). To prevent race conditions where a screen displays stale data while a network call is in flight, the Presentation layer enforces Unidirectional Data Flow (UDF):
- The State Holder (ViewModel, Bloc, or Store) exposes a single immutable
UiStatestream (for example, a KotlinStateFlow<CheckoutUiState>or Swift@Observablestruct) containing the exact fields needed to render the screen, plus one-off side effects (navigation triggers or snackbar alerts). - The View observes that state stream, renders loading skeletons, populated lists, or inline errors, and dispatches immutable User Intents / Actions (
OnConfirmOrderClicked,OnPromoCodeChanged) upward to the State Holder. - The View never mutates local state variables that represent business data.
Android app architecture gets this from a ViewModel that exposes StateFlow, the setup Google's guide recommends. iOS app architecture gets it from the Observation framework and @Observable, which need iOS 17 or later.
Layer 2: Domain Layer (Use Cases and pure business rules)
A common mistake in naive Clean Architecture implementations is creating hundreds of pass-through use cases that do nothing except call repository.getUser(). At Idealogic, we keep the Domain layer lean. A Use Case earns its place when it either:
- Combines data from multiple repositories: for example,
GetEnrichedPortfolioUseCasemerging real-time price ticks from a market-data repository with cached holdings from a wallet repository and user currency preferences. - Encapsulates complex, testable domain math or validation: for example, calculating tiered transaction fees, offline loan amortization schedules, or medical dosage thresholds that must be verified across 50 edge-case unit tests without spinning up a simulator.
Because the Domain layer imports zero platform frameworks (import UIKit or import android.content.Context is strictly forbidden via lint rules), its tests run in milliseconds on every Git commit.
Layer 3: Data Layer (Repositories, DTO mappers, and Single Source of Truth)
The Data layer hides where data physically lives from the rest of the application. Every Repository coordinates at least two data sources:
- Local Data Source: An on-device relational or document store (Room/SQLite on Android, SwiftData/Core Data/GRDB on iOS, WatermelonDB or Expo SQLite on React Native, Drift/SQLite on Flutter) plus encrypted key-value storage for session tokens.
- Remote Data Source: REST (
URLSession,Retrofit/OkHttp,ky/fetch,Dio), GraphQL (Apollo), or gRPC network clients that deserialize wire JSON into Data Transfer Objects (DTOs).
Wire DTOs never leak above the Data layer. If a backend developer renames a JSON field from user_balance_cents to available_amount_minor or returns a nullable string where the UI expects a non-null Decimal, the Data layer's mapper absorbs that change in one file and maps it into a clean Domain model.
Mobile app architecture best practices: when to skip a layer
Three layers are a default, and small apps can run on fewer. In a simple CRUD app the Presentation layer can depend on Data repositories directly, which is also what Google's guide allows. Don't write a use case that only forwards a repository call. A v1 with two engineers can live in one module with folders per layer, and you add feature modules when the team and screen count grow.
Presentation patterns compared: MVVM vs MVI vs VIPER vs TCA
MVVM with one immutable UiState is the default presentation pattern, and MVI or TCA is the step up for complex state machines. Teams argue about this choice inside Layer 1 more than almost anything else in mobile engineering. You don't need to pick a side. Match the ceremony of the pattern to the state complexity of your product.
The four presentation patterns compare like this across native and cross-platform stacks:
Why MVVM with a single immutable UiState became the default
Classic 2018-era MVVM earned a bad reputation because developers created ViewModels with twelve independent observable streams (isLoading, isRefreshing, hasError, items, selectedFilter, isBannerVisible). When three asynchronous callbacks resolved out of order, the screen entered impossible states, such as displaying both an empty-state illustration and a loading spinner over a populated list.
The fix keeps the simplicity of MVVM and borrows the best idea from MVI: each ViewModel exposes exactly one immutable UiState data class or sealed interface. Every state transition produces a new copy of that single state object (_uiState.update { it.copy(isLoading = false, items = result) }), so UI updates are atomic and you skip the boilerplate of VIPER.
Offline-first architecture for mobile apps: the outbox pattern
Offline-first architecture means the local database is the source of truth and the network is a background sync channel, not a prerequisite for rendering the screen. An app that shows a full-screen error modal whenever the user walks into a basement or boards a train feels broken.
The 4-step offline-first read and write loop
To make the local database the Single Source of Truth (SSOT) without corrupting server state, our engineers implement a four-stage loop across iOS, Android, React Native, and Flutter builds:
- Reactive local reads (Zero network wait on launch): When a user opens a screen, the Repository never blocks on an HTTP
GET. It immediately returns a reactive stream (Flow<List<Order>>in Room,@Queryin SwiftData, or an observable query in WatermelonDB) backed by on-device SQLite running in Write-Ahead Logging (WAL) mode so background writes do not block main-thread reads. The screen renders cached data in under 16 milliseconds. - Atomic local mutation + Transactional Outbox write: When the user creates a record or edits a field, the Domain use case validates the input and executes a single atomic SQLite transaction that does two things:
- Updates the local domain table with
sync_status = 'PENDING_SYNC'so the reactive UI query immediately reflects the optimistic change on screen. - Inserts a serialized mutation payload into a local
outbox_mutationstable containing a client-generatedidempotency_key(a UUID v4 that every retry reuses),entity_id,operation_type,payload_json,created_at_ms, andretry_count.
- Updates the local domain table with
- Background Outbox Worker with exponential backoff: A platform-native background scheduler (
WorkManageron Android,BGTaskScheduleron iOS, coupled with an active foreground network-reachability listener) drains theoutbox_mutationsqueue in strict FIFO order per entity. It runs opportunistically, because iOS givesBGTaskSchedulerno timing guarantee. Each request sends anIdempotency-Keyheader, specified in the IETF HTTPAPI idempotency key draft and built on the idempotent-method semantics of RFC 9110. If the connection drops after the server commits the row, the retry doesn't create a duplicate transaction. - Deterministic conflict resolution and rollback: When the server responds with
200 OKand the canonical server timestamp/version, the Repository marks the local recordSYNCEDand deletes the outbox entry. If the server returns409 Conflict(because another device modified the same record while this phone was offline) or422 Unprocessable Entity, the Repository applies a domain-specific resolution rule.
Choosing the right conflict resolution strategy by data type
Don't use a single conflict resolution rule across your entire database. Match the conflict resolution strategy to the business risk of the entity:
Optimistic UI without a persistent transactional outbox and idempotent server keys is just a bug generator waiting for an elevator ride. If the user sees a green checkmark on screen, that mutation must survive app termination, phone reboots, and three-day offline gaps.
Mobile app architecture modularization: structuring a codebase for multi-squad velocity
Modularize by feature once the codebase passes about 25 screens or more than one squad works in it. In a six-week MVP with two engineers, a single monolithic app module divided into presentation/, domain/, and data/ folders works fine. By month twelve, when eight engineers work across 60 screens, a monolithic module turns every pull request into a merge-conflict bottleneck and stretches clean Xcode and Gradle builds past ten minutes.
Our target is incremental builds under 15 seconds. To get there, we partition production codebases into a two-tier module graph:
- Core Horizontal Modules (
:core:*): Shared technical infrastructure containing zero product business rules::core:designsystem: Tokenized typography, colors, icons, and stateless UI primitives aligned with our mobile app design system.:core:network: Authenticated HTTP/GraphQL client, token refresh mutex interceptor, TLS pinning, and error envelopes.:core:database: Encrypted SQLite/Room schema migrations and outbox queue tables.:core:analytics&:core:model: Crash reporting wrappers and shared pure domain identifiers.
- Feature Vertical Modules (
:feature:*): Self-contained product capabilities (:feature:onboarding,:feature:wallet,:feature:transactions,:feature:settings).- Strict horizontal isolation rule:
:feature:walletmay never depend directly on:feature:transactions. If Wallet needs to navigate to a Transaction Detail screen, it emits a navigation route contract defined in a lightweight:core:navigationmodule that the top-level:appshell wires together via Dependency Injection (Hilt or Koin on Android, or an equivalent DI container on iOS and cross-platform stacks).
- Strict horizontal isolation rule:
Because feature modules cannot import each other's implementation classes, changing a ViewModel inside :feature:wallet only recompiles :feature:wallet. Incremental CI and local builds get shorter as a result. Google's build optimization guide describes the same effect for Gradle, and the size of the gain depends on your project, so measure it.
Security boundaries inside mobile app architecture (OWASP MASVS)
Security in a mobile app is a property of the Data and infrastructure layers, so you design it in from the first sprint. An audit the week before launch can't add it. When architecting clients against the OWASP Mobile Application Security Verification Standard (MASVS v2.1), we enforce four boundaries (covered in full in our mobile app security engineering guide):
- Hardware-backed credential isolation (MASVS-STORAGE): Session tokens, OAuth tokens obtained through the authorization-code flow with PKCE (RFC 7636), and symmetric database encryption keys are stored in the iOS Keychain (
kSecAttrAccessibleWhenUnlockedThisDeviceOnly, optionally gated by Secure Enclave-backed access control) or protected by the Android Keystore (with Tink for envelope encryption). PlaintextSharedPreferences,UserDefaults, and unencryptedAsyncStorageare blocked via static analysis lint rules. - The local database is encrypted at rest. When an offline-first architecture caches financial transactions, patient health records, or private messages in SQLite, the local database file is encrypted using 256-bit AES via SQLCipher, with the key unlocked only after biometric verification (
LocalAuthenticationon iOS /BiometricPrompton Android). - Single-flight token refresh mutex (MASVS-AUTH): When a user opens an app after their 15-minute access token expires, four screen widgets may fire concurrent API requests. Without a mutex lock in your network interceptor, all four calls receive
401 Unauthorizedand fire four competing/oauth/tokenrefresh requests, triggering reuse detection on the auth server and logging the user out. A single-flight coroutineMutexor Swiftactorqueues concurrent 401s, refreshes the token exactly once, and replays the suspended requests transparently. - Transport pinning and privacy compliance (MASVS-NETWORK & Store Policies): For regulated apps, the network client pins the SPKI SHA-256 hash of the backend's leaf or intermediate TLS certificate (with a backup pin and a remote config rotation switch, because a stale pin takes the app offline). The app also follows the Apple App Store Review Guidelines, Apple Human Interface Guidelines, and Google Play Developer Policy.
How architecture impacts mobile development cost and long-term velocity
Founders sometimes worry that Clean Architecture layers and offline sync queues will bloat their v1 budget. In our projects it has gone the other way. A McKinsey and University of Oxford study of more than 5,400 large IT projects found they run 45% over budget on average, which is why early structural decisions matter. CB Insights' startup post-mortem analysis lists no market need (42%) as the top reason startups fail. That's an argument for a codebase you can change quickly once real users respond.
Whether you choose native or cross-platform (see our breakdown of native vs cross-platform app development, cross-platform app development, React Native vs Flutter, and the cross-platform vs native knowledge base), setting clean Presentation, Domain, and Data boundaries in Sprint 1 adds less than three days of setup in our projects and saves regression debugging later. Team location changes the bill too. Labor cost levels in Central and Eastern Europe, per Eurostat (lc_lci_lev), are well below the US wage baselines tracked by the U.S. Bureau of Labor Statistics and BLS ECEC compensation data, so a senior Eastern European squad typically delivers the same architecture at a lower mobile app development cost than a US agency.
To see how mobile app architecture fits into the broader product journey, read our pillar guide on how to build a mobile app, our roundup of mobile app development trends, our UX troubleshooting guide on the top 5 user experience issues in mobile apps, and our mobile app development knowledge base. If you need a senior mobile app development or idea-to-product team to architect your greenfield build or rescue an existing codebase, let's talk.

CTO and Co-founder at Idealogic. Directing engineering, systems architecture, security, and full-stack delivery across web, mobile, and blockchain.
Frequently asked questions
Mobile app architecture (also called mobile application architecture) is the way client code splits into Presentation, Domain, and Data layers, how state flows one way between screens and storage, and how dependencies point inward toward business rules. With those boundaries in place you can unit test business logic without booting a simulator, and the app keeps working when the cellular connection drops.
Google's Android architecture guide and current iOS practice describe the same split. The Presentation (UI) layer holds declarative views and state holders like ViewModels or Stores. The Domain layer holds framework-free business logic and reusable use cases. The Data layer holds repositories that coordinate local SQLite or Room storage with remote REST or GraphQL APIs. Google's guide treats the Domain layer as optional, and a small CRUD app can skip it.
MVVM with reactive state streams (StateFlow on Android, @Observable on iOS) is our default for most SwiftUI and Jetpack Compose apps. Move to MVI or The Composable Architecture (TCA) when a screen needs strict unidirectional state replay, multi-step forms, or deterministic debugging. Keep VIPER for legacy UIKit codebases that still rely on imperative view controllers.
In an offline-first architecture the on-device database (SQLite, Room, SwiftData, or WatermelonDB) is the single source of truth. The UI reads only from reactive local queries. Each write saves the mutation and a queued sync job in one atomic local transaction, and a background outbox worker pushes pending mutations to the remote API with idempotency keys once connectivity returns.
Pair a persistent transactional outbox queue on the client with idempotent API endpoints on the backend. Before it sends a state-changing POST or PATCH request, the client generates a UUID v4 Idempotency-Key and stores it in the outbox row. If the HTTP response gets lost during a Wi-Fi to 5G handoff, the worker retries with the same key.
A small v1 app can start with top-level package folders by layer. Once several engineers share a codebase of more than about 25 screens, modularize by feature (:feature:checkout, :feature:profile) on top of shared core modules (:core:network, :core:database, :core:designsystem). Feature modules keep Gradle and Xcode incremental compilation small and enforce visibility boundaries, so squads ship in parallel with fewer merge conflicts.
Not in the ways that matter. The boundaries and dependency rules are the same across native Swift/Kotlin, React Native, and Flutter. The practical difference is that a cross-platform build writes the Domain and Data layers once in TypeScript or Dart for both stores instead of twice in two languages.
Security belongs in the Data and infrastructure code, never scattered across UI views. In an architecture built against OWASP MASVS, an auth interceptor attaches short-lived tokens read from the iOS Keychain or Android Keystore. The networking client requires TLS 1.2 or higher (1.3 preferred) and pins the server's public key. SQLCipher encrypts cached PII in the local database.
More from the journal

Knock vs Novu vs Courier in 2026: Notification Infrastructure & TCO
Engineering and 36-month TCO teardown of Knock vs Novu vs Courier in 2026: event vs per-message billing traps, MongoDB self-hosting overhead, PostgreSQL 17 FORCE RLS digest batching, and multi-channel fan-out math.

Sendbird vs Stream in 2026: Chat SDKs, PCC & 36-Month TCO
Engineering and 36-month TCO teardown of Sendbird vs Stream in 2026 alongside CometChat, PubNub, and Ably: Peak Concurrent Connection cliffs, Go/RocksDB edge latency, Redis Streams plus PostgreSQL 17 chat ledgers, and owned messaging math.

Jobber vs Housecall Pro in 2026: FSM APIs, Fees & TCO
Engineering and 36-month TCO benchmark of Jobber vs Housecall Pro vs ServiceTitan in 2026: GraphQL and MAX-gated REST APIs, multi-branch QuickBooks sync, card/ACH spreads, and custom offline-first FSM builds.