Summary#
Mobile system design is about architecting native (or cross-platform) apps on iOS and Android, together with the backend contract that serves them. Mobile has constraints the web mostly doesn't:
- Battery and radio costs. Every network request wakes a power-hungry cellular radio.
- Flaky networks. Tunnels, lifts, handovers and captive portals.
- An operating system that kills your app and tightly limits background work.
- App-store releases that take a day or more to reach users and can never be rolled back.
- A long tail of old app versions that keep calling your APIs for years.
Good mobile designs answer these with a standard set of tools:
- Architecture: MVVM with unidirectional data flow.
- Offline-first storage in an on-device database that is the UI's single source of truth, kept current by a sync engine (delta pulls plus an outbox of pending writes).
- Push notifications through APNs and FCM.
- Memory- and bandwidth-aware image loading.
- Background work through OS schedulers (WorkManager, BGTaskScheduler).
- APIs shaped for mobile: cursor pagination, delta sync and a backend-for-frontend.
- Release safety: version policies, forced upgrades, feature flags and staged rollouts.
- Crash and performance monitoring that decides whether a rollout continues.
Why It Exists#
On a server you control the hardware, deploy many times a day, and can roll back in a minute. On mobile, none of that holds:
- Releases go through app-store review (usually hours to a day or two) and roll out over days. Users update when they choose, and some never do. A bug that reaches 100% of users can't be undone: you can only ship a fix and wait for adoption.
- The device is resource-constrained and shared. Battery, memory, storage, CPU and thermal budget are shared with every other app. The OS aggressively suspends and kills background apps to protect battery life, so your process may die at any moment and must restore state seamlessly.
- The network is hostile. Mobile round trips range from about 30–50 ms on good 4G or 5G to many hundreds of milliseconds on congested or 3G links, with frequent drops and changes between Wi-Fi and cellular. Many users pay per megabyte, and some are on 2G in parts of the world.
- The app is a long-lived replica of server data. Users expect it to open instantly, show their last data even offline, and never lose a message or a photo they posted on the underground.
- Billions of devices call your backend. Retry behaviour, polling intervals and push fan-out designed carelessly become self-inflicted DDoS attacks after an outage.
That's why mobile design is its own discipline, and why large companies (Uber, Meta, Airbnb, Lyft and others) run mobile-specific system design interviews. The goal is to design the app and its contract with the backend so it stays fast, frugal, correct offline, and safe to evolve.
How It Works#
A well-designed mobile app is layered:
- UI layer. Screens and views driven by state.
- Presentation layer. ViewModels that turn data into UI state and handle user intents.
- Domain and data layer. Repositories that hide where data comes from.
- Local database. The source of truth the UI observes.
- Sync engine. Keeps the local database consistent with the server.
- Platform integrations: push, background scheduling, the image pipeline, telemetry.
On the backend, a mobile-focused BFF, push providers, a CDN, remote config and crash reporting complete the system.
Inside the app, the screens observe a ViewModel that reads from repositories backed by the local database. The sync engine is the only component that talks to the server for data. Outside the app, a handful of server-side systems serve the client:
The sections below cover each concern in turn:
- the constraints;
- app architecture;
- offline-first storage and sync;
- push;
- images;
- background work;
- mobile API design;
- versioning;
- flags and rollouts;
- monitoring.
Mobile constraints: battery, flaky networks and app-store releases#
Battery and the radio. On a phone, the cellular radio is among the most power-hungry components, and its cost isn't proportional to bytes.
- The tail. After a transfer, the radio stays in a high-power connected state for several seconds (the "tail") before dropping back to idle. Measurements in "A Close Examination of Performance and Power Characteristics of 4G LTE Networks" (Huang et al., MobiSys 2012) found LTE tails on the order of 10 seconds.
- The consequence. A 1 KB analytics ping every 30 seconds can keep the radio awake a third of the time, costing far more energy than one 300 KB batch every 15 minutes.
- The design rules:
- Batch and coalesce. Send analytics, logs and non-urgent sync together, and piggyback them on requests the user already triggered.
- Prefer push to polling. One push "tickle" replaces thousands of empty polls.
- Defer non-urgent work to when the device is charging and on Wi-Fi, via OS schedulers.
- Minimise wakeups. Location, sensors and wake locks drain batteries fast. Use the coarsest location accuracy and the lowest update rate that works.
- Avoid busy work while backgrounded. The OS will kill offenders, and both stores flag apps with excessive battery use.
Flaky, slow and expensive networks. Design for all of these:
- Variable latency and bandwidth. RTT ranges from about 30 ms to over 500 ms, and bandwidth from under 100 kbps to hundreds of Mbps, sometimes within one commute.
- Disconnections and handovers. Requests fail mid-flight. Wi-Fi to cellular switches change your IP address and break long-lived connections.
- Captive portals and "connected but no internet". The OS reports connectivity, yet requests hang. Timeouts matter: a stuck request with no timeout is a frozen spinner.
- Metered data. Respect cellular data, and offer "download on Wi-Fi only" for large media.
- Shared IPs. Carrier-grade NAT puts thousands of users behind one IP address, so per-IP rate limits punish mobile users. Identify clients by user ID, device ID or API key instead (Rate Limiting and Throttling).
The universal answers:
- Offline-first data, so the UI never waits on the network to show something.
- Idempotent writes with retries, using exponential backoff with jitter.
- Resumable transfers.
- Small payloads, compressed and in compact formats.
- Explicit timeouts on every call (Resilience Patterns: Timeouts, Retries and Circuit Breakers).
Memory, CPU, storage and the OS lifecycle.
- The OS can kill your app at any time. iOS terminates suspended apps under memory pressure ("jetsam"), and Android's low-memory killer does the same. After the user leaves the app, its process can be gone within seconds or minutes. When the user returns, the app must restore its state: current screen, scroll position, half-typed draft. Persist navigation and input state, and use the platform's state-restoration APIs.
- The main thread must stay free.
- At 60 Hz each frame has 16.7 ms; at 120 Hz it has 8.3 ms.
- Blocking the main thread with disk I/O, JSON parsing or image decoding causes jank.
- On Android, blocking it for 5 seconds triggers an ANR ("Application Not Responding").
- On iOS, the system watchdog kills apps that take too long to launch or respond.
- Thermal throttling. Sustained CPU or GPU load (video processing, ML) slows the device and drains the battery.
- Storage is finite and user-visible. Users delete apps that grow to gigabytes. Bound caches, and let the OS purge cache directories.
- Device fragmentation. Thousands of Android models with different screen sizes, OS versions, RAM and vendor modifications. Test on low-end devices, not just flagships.
- App size. A large download reduces installs, especially in markets with expensive data. Use app thinning or Android App Bundles, on-demand resources, and dynamic feature modules.
App-store releases: the hardest constraint.
- Review delay. Each release passes store review, usually within a day but sometimes longer. Emergency fixes still take hours to reach users.
- Gradual adoption. Even with auto-update, a new version typically reaches a majority of active users over a period of days to weeks. Some users never update, because their devices can't run the new OS version or auto-updates are off.
- No rollback. You can halt a rollout, but users who installed the bad version keep it until a fixed version ships. You can't downgrade them.
- Release trains. Large apps ship on fixed schedules (weekly or bi-weekly). Features that miss the train wait for the next one. That's why features ship dark behind flags and are enabled remotely.
- Platform rules. Store guidelines restrict downloading and executing new code. Interpreted JavaScript or server-driven configuration is allowed within limits, but a native-code hot patch isn't. Remote behaviour change must work through data, configuration and flags.
Because of these constraints, mobile designs push as much variability as possible to the server side: API responses, remote config, feature flags, server-driven UI. The binary contains capabilities, and the server decides how they're used.
App architecture: MVVM and unidirectional data flow#
Mobile architectures evolved to tame one recurring problem: UI code that owns everything. In early iOS and Android apps, a view controller or activity fetched data, held state, handled taps, and updated views directly, the "Massive View Controller". It was impossible to test, and it broke on rotation and process death.
The patterns, in brief:
- MVC (Model–View–Controller). Apple's original guidance. In practice the controller absorbs everything.
- MVP (Model–View–Presenter). The presenter holds logic and talks to a passive view interface. It's testable, but involves lots of boilerplate.
- MVVM (Model–View–ViewModel).
- How it works. The ViewModel exposes observable UI state and accepts user actions. The view simply renders state and forwards events. The ViewModel knows nothing about views, which makes it unit-testable.
- Platform support. On Android, Jetpack's
ViewModelsurvives configuration changes such as rotation. On iOS, SwiftUI's observable objects play this role. - Status. It's the default recommendation on both platforms today.
- MVI and unidirectional data flow (UDF).
- How it works. State flows down (ViewModel to UI) as an immutable value, and events flow up (UI to ViewModel) as intents. A reducer computes
newState = reduce(oldState, event). Side effects (network, database) run outside the reducer and feed results back as events. - The inspiration was Redux and Elm on the web.
- Examples include The Composable Architecture (TCA) on iOS, and Android's official architecture guidance with Compose. Uber's RIBs framework (open-sourced 2017) organises the app as a tree of Router–Interactor–Builder units, keeping business logic separate from views for large teams.
- How it works. State flows down (ViewModel to UI) as an immutable value, and events flow up (UI to ViewModel) as intents. A reducer computes
Why UDF works well on mobile:
- One source of truth per screen. The state value can be saved and restored after process death, logged for debugging, and snapshot-tested.
- Declarative UI fits naturally. SwiftUI (2019) and Jetpack Compose (stable 2021) re-render from state, the same model as React. You describe the UI for a given state, rather than mutating views.
- No impossible states. A sealed type such as
Loading | Content(posts, isRefreshing) | Error(message, cachedPosts)makes the UI handle every case explicitly.
Layering and modularisation for large apps:
- Clean architecture layers. Presentation (UI, ViewModels), domain (use cases and business rules, platform-independent) and data (repositories, database, network).
- The repository pattern. Repositories expose observable streams from the local database (Kotlin
Flow, SwiftAsyncSequenceor Combine publishers) and trigger sync behind the scenes. ViewModels never call the network directly. - Dependency injection. Hilt or Dagger on Android, and protocols with initialiser injection or a container on iOS. It swaps fakes in tests and wires modules together.
- Feature modules. Large apps split into dozens to hundreds of modules (feed, profile, payments, a shared design system, networking) with explicit dependencies. Builds get faster through incremental compilation, ownership becomes clear, and features can be delivered dynamically on Android.
- Cross-platform options.
- React Native. Shopify publicly committed to it in 2020. Airbnb, by contrast, wrote in 2018 about moving away from it.
- Flutter.
- Kotlin Multiplatform, which shares business logic while keeping native UI.
- The choice turns on team skills, the need for native platform features, performance-sensitive UI, and how much logic can be shared. Shared code reduces duplication, but adds a bridge layer and its own failure modes.
Offline-first storage and sync#
Offline-first means the app reads from and writes to a local database first, and treats the network as a background synchronisation channel. The UI never waits on the network to show data. It shows what's local immediately, then updates when sync brings changes. Compare that with "online with a cache", where the app calls the API and caches responses opportunistically. Offline-first is more work, but it delivers instant launches, resilience to dead zones, and no lost writes.
On-device storage options:
| Store | Platform | Use for |
|---|---|---|
| SQLite (directly, or via Room, SQLDelight, GRDB) | Both | Structured data, queries, indexes, transactions: the default for offline-first |
| Core Data or SwiftData | iOS | Object graphs with change tracking and observation, built on SQLite |
| Realm, Couchbase Lite, ObjectBox | Both | Object databases; some include their own sync products |
| Key-value stores (UserDefaults, Jetpack DataStore, MMKV) | Both | Small settings and flags; not for large or relational data |
| Keychain (iOS) and Keystore with EncryptedSharedPreferences (Android) | Both | Secrets only: tokens, keys; hardware-backed where available |
| Files in app sandbox (cache and documents directories) | Both | Media, downloads, large blobs; the cache directory may be purged by the OS |
Rules for the local store:
- Run database work off the main thread, and use transactions for multi-row updates.
- Plan schema migrations from day one. Every app version must migrate from any older schema it might find, since users skip versions. Test migrations from several versions back.
- Encrypt sensitive data at rest (SQLCipher, or platform file protection classes), and clear user data on logout.
- Bound the size. Keep, say, the latest 500 feed items and 30 days of messages. Evict older data, and refetch it on demand.
The sync engine has two halves.
1. Pull: getting server changes efficiently (delta sync).
- Avoid full downloads. Don't refetch everything on every launch. Ask for changes since a cursor:
GET /sync?since=<token>. - Use an opaque server token. The server returns created and updated records plus tombstones (records deleted since the cursor) and a new cursor. The client applies them in a transaction, then stores the new cursor.
- Make the cursor a server-issued token, such as a per-user change-log sequence number or an encoded position, not the client's clock. Phone clocks are wrong surprisingly often.
- Handle expired cursors. If a cursor is too old (the server's change log is retained for, say, 30 days), the server replies "reset required". The client then does a full resync, or a scoped one for recent data.
- Paginate the deltas. A client returning after two weeks may have thousands of changes. Each page returns a
hasMoreflag, and the client applies pages in order, committing the cursor after each page so a crash resumes cleanly. - Trigger pulls on: app foreground, a push "tickle" ("something changed, sync"), periodic background refresh within OS limits, and pull-to-refresh.
2. Push: sending local changes reliably (the outbox).
- Write locally first. A user action writes to the local database and appends an outbox entry in the same transaction: an operation type, a payload, a client-generated ID (UUID) and an attempt count. The UI updates immediately from the local database, showing a pending indicator where appropriate.
- Drain in order. The sync engine sends outbox entries in order when the network is available. Each request carries an idempotency key (the client ID), so a request that timed out and is retried can't create duplicates (Idempotency and Safe Retries).
- On success, delete the entry and reconcile the server's version: server-assigned fields, canonical timestamps.
- On transient failure, retry with exponential backoff and jitter.
- On permanent failure, such as a validation error or a deleted parent, mark the item failed and show it to the user ("Message not sent. Tap to retry") rather than dropping it.
- Dependent operations stay ordered. "Create album" must be acknowledged before "add photo to album", or the server must accept client IDs as foreign keys.
Conflict resolution. The same record may have been edited on two devices, or on the server, while one device was offline. Pick a policy per data type:
- Last-writer-wins (LWW) using server-assigned versions or timestamps. It's simple and fine for profile fields or settings, but silently discards one edit.
- Version checks (optimistic concurrency). The client sends the version it edited, and the server rejects the write if the version changed (HTTP 409 or 412). The client then refetches, and re-applies or asks the user. This suits business data such as orders and documents.
- Field-level merging. Merge non-overlapping field changes, and only conflict on the same field.
- CRDTs for collaborative data: notes, lists, text. Concurrent edits merge automatically and deterministically (Conflict Resolution, OT and CRDTs).
- Append-only data (messages, workout records, log entries) mostly avoids conflicts, because each device only adds new records with unique IDs.
Managed sync products. Firebase Firestore (with offline persistence), Couchbase Lite with Sync Gateway, AWS Amplify DataStore and PowerSync implement much of this for you: local cache, delta sync, conflict handling. They save effort, at the cost of lock-in and less control over the data model and conflict semantics. Many large apps build their own, because sync behaviour is deeply product-specific.
Strava is a familiar example of the offline-first pattern. A run is recorded entirely on the device, often with no signal, and uploaded when connectivity returns. The workout must never be lost, which makes durable local storage plus an idempotent upload the core of the design (Design a Fitness Tracking App (Strava)).
Push notifications: APNs and FCM#
Apps can't hold their own persistent connections in the background, because the OS would kill them to save battery. So both platforms provide one shared, OS-managed push channel:
- APNs (Apple Push Notification service) for iOS, iPadOS, macOS and watchOS.
- FCM (Firebase Cloud Messaging) for Android. FCM can also deliver to iOS by relaying through APNs.
The device keeps a single efficient connection to the platform's push service, and your backend sends messages to that service, never directly to the phone.
The flow end to end:
- Permission. The app asks the user for notification permission. iOS always requires it. Android requires it from Android 13 (the
POST_NOTIFICATIONSruntime permission). Ask in context ("Get notified when your driver arrives?"), not on first launch, because a denied prompt is hard to undo. iOS also offers provisional authorisation, which delivers quietly to the notification centre without a prompt. - Registration. The OS gives the app a device token (APNs) or a registration token (FCM). The app sends it to your backend with the user ID, app version, platform, locale and notification preferences.
- Token lifecycle. Tokens change on reinstall, restore or periodically. Re-send the token on every launch when it differs. When APNs answers HTTP 410 (Unregistered), or FCM reports an unregistered token, delete it. Stale tokens waste send capacity and skew delivery metrics.
- Send. Your notification service builds the payload and calls the provider API:
- APNs: an HTTP/2 API, authenticated with a signed JWT from a
.p8key or a TLS certificate. - FCM: the HTTP v1 API, authenticated with OAuth service-account credentials.
- APNs: an HTTP/2 API, authenticated with a signed JWT from a
- Delivery. The provider delivers when the device is reachable. While a device is offline, APNs keeps only the most recent notification per app, and FCM keeps messages for a configurable TTL, up to 4 weeks by default.
Payload types and limits:
- Visible (alert) notifications: title, body, sound, badge, deep link. Both platforms cap payloads at about 4 KB, so send IDs and short text, not content.
- Background or data messages.
- On iOS:
content-availablesilent pushes wake the app briefly to fetch data, but iOS throttles them heavily. Apple advises no more than a few per hour, and delivery isn't guaranteed if the app was force-quit or the battery is low. - On Android: FCM data messages are handled by the app. High-priority messages can wake a device from Doze, but Android may deprioritise an app that sends high-priority messages without showing notifications.
- On iOS:
- Priority and collapsing.
- APNs priority 10 means immediate and priority 5 means power-considerate. FCM uses
highandnormal. - Collapse keys (
apns-collapse-id, FCMcollapse_key) replace older pending notifications of the same kind, so a score update doesn't stack 30 alerts.
- APNs priority 10 means immediate and priority 5 means power-considerate. FCM uses
- Rich and encrypted notifications. On iOS, a Notification Service Extension gets a short time window to modify an incoming notification: download an image attachment, or decrypt an end-to-end encrypted payload, as secure messengers do. Android apps do the equivalent in their messaging service.
- Android notification channels (from Android 8) let users control categories (messages, promotions, reminders) separately. Design the categories deliberately.
Design principles:
- Push is a hint, not a data channel. Delivery is best-effort, can be delayed or dropped, and APNs coalesces offline messages. The source of truth is your API. A push says "new message in conversation 812", and the app syncs to fetch it. The in-app notification inbox is likewise built from the server, not from received pushes.
- Respect users.
- Enforce per-user frequency caps, honour quiet hours and local time zones, and aggregate ("Ana and 4 others liked your photo").
- Make every push actionable with a deep link to the right screen.
- Over-notification is the fastest way to get notifications disabled, or the app deleted.
- Fan-out is a backend problem. A breaking-news alert to 50 million devices needs a queue, worker fleets and rate-limited calls to APNs and FCM, which accept large but finite throughput per connection. See Design a Notification System.
- Measure the funnel: sent, accepted by the provider, delivered (where reported), opened, and opt-out rate, broken down per notification type.
Image loading and caching#
Images usually dominate a mobile app's bandwidth, memory and scroll performance. A good image pipeline has six parts:
- Request the right size from the server.
- The problem. A 12-megapixel photo (4000 × 3000) is several MB as a JPEG. Shown as a 360-point-wide thumbnail on a 3× screen, it only needs about 1080 pixels wide.
- The fix. An image CDN resizes on request (
…/photo.jpg?w=1080&fmt=webp), and the app asks for the size matching the view's pixel dimensions, bucketed to a few sizes so CDN caches stay effective. - Formats. Use modern formats: WebP is widely supported, AVIF and HEIC are smaller where supported. Serve lower-quality variants on slow networks or in data-saver mode.
- Downsample on decode.
- Memory cost. In memory, an image takes width × height × 4 bytes (RGBA), regardless of file size. A 4000 × 3000 image decodes to 48 MB, enough to crash an app after a few of them. The same image downsampled to 1080 × 810 takes about 3.5 MB.
- The rule. Always decode to the target size, and decode off the main thread.
- Use a two-level cache.
- A memory cache (LRU, sized as a fraction of the app's memory budget) holds decoded bitmaps for instant display while scrolling back.
- A disk cache (LRU, a few hundred MB) holds encoded bytes, which survive restarts and save bandwidth.
- The cache key must include the requested size and transformation. The same URL at two sizes is two entries.
- Respect HTTP cache headers. Versioned image URLs can be cached indefinitely.
- Manage requests for lists.
- Deduplicate in-flight requests for the same image.
- Cancel requests for cells that scrolled off screen, since recycled cells must not show the wrong image.
- Prioritise visible images over prefetches.
- Prefetch the next few rows' images as the user scrolls.
- Use placeholders and progressive display. Send a tiny BlurHash or ThumbHash string, a few dozen bytes, in the API JSON. The app renders a blurred preview instantly, inside a box with the image's aspect ratio (also from the API) to avoid layout jumps, then fades in the real image.
- Choose a proven library rather than building your own: Glide, Coil or Fresco on Android, and SDWebImage, Kingfisher or Nuke on iOS. Facebook built Fresco (open-sourced in 2015) specifically to manage image memory on Android devices with tight memory limits.
Uploading images from the device:
- Compress and resize on the device first (for example, to 2048 pixels on the long edge), and strip location EXIF metadata unless the user opts in.
- Upload directly to object storage via a pre-signed URL, using resumable or multipart uploads, so the API servers don't proxy the bytes.
- Show the local image immediately while the upload continues in the background (Pattern: Handling Large Files and Blobs).
Background work limits#
Both platforms restrict background execution to protect battery life. Your design must treat background work as opportunistic, deferred and killable.
iOS:
- Suspension. Apps are suspended shortly after moving to the background, and
beginBackgroundTaskbuys only a short extension to finish a task. - BGTaskScheduler (iOS 13+) lets you request:
- a BGAppRefreshTask, a short run that the system schedules based on how often the user opens the app;
- a BGProcessingTask, a longer run that can require external power and network, typically overnight. The system decides when, or whether, these run.
- Background URLSession hands uploads and downloads to the OS, which completes them even if your app is suspended or terminated. It's the right tool for large media uploads and downloads.
- Background modes (audio playback, navigation and location updates, VoIP, Bluetooth accessories) are allowed only for apps that genuinely provide those features, and store review enforces this.
- Silent pushes can trigger a brief fetch, but they're throttled.
Android:
- Doze (Android 6) defers jobs, alarms and network access when the device is idle, with periodic maintenance windows.
- App Standby Buckets (Android 9) rate-limit jobs and alarms based on how recently and how often the user uses the app: active, working set, frequent, rare, restricted.
- Background execution limits (Android 8) stop apps from running background services freely.
- WorkManager is the recommended API for deferrable, guaranteed work. You declare constraints (unmetered network, charging, battery not low, storage not low), retry and backoff policies, and chains of work. It survives app restarts and reboots.
- Foreground services for user-visible ongoing work (navigation, a workout recording, music) must show a persistent notification. Since Android 14 they must also declare a service type.
- Exact alarms need special permission on recent versions.
Design rules:
- Do important work while the app is in the foreground. Sync on open, and flush the outbox when the user returns.
- Make background work idempotent, chunked and resumable. It may be stopped at any point. Checkpoint progress in the local database, and use resumable upload protocols such as tus or S3 multipart, so a 200 MB video upload resumes from the last finished chunk instead of restarting.
- Use push tickles plus foreground sync for freshness, rather than frequent periodic background polling, which the OS won't honour anyway.
- Respect constraints. Upload large media on Wi-Fi or while charging unless the user asks otherwise. Prefetch content (offline downloads, the next day's feed) overnight while charging, as video and music apps do for downloads.
- Tell the user when work is waiting on conditions ("Will upload when on Wi-Fi").
API design for mobile: pagination, delta sync and BFF#
Mobile clients turn API design choices into battery drain, perceived latency and data bills, so APIs serving apps are usually shaped differently from general-purpose ones (API Design Best Practices).
Fewer, coarser requests: the backend-for-frontend (BFF).
- Why it's needed. Each request costs at least one round trip (often 100–300 ms on cellular) and keeps the radio awake. A screen that needs a feed, 20 author profiles and 20 like states should not make 41 calls.
- How it works. A BFF, a thin server layer owned by the mobile team, aggregates backend services into one response per screen, already shaped for the UI: display strings, image URLs at the right size, precomputed counts (API Gateway and Backend-for-Frontend). Common setups:
- separate BFFs per platform (iOS, Android, web);
- one mobile BFF with version-aware responses;
- GraphQL, so clients compose the fields each screen needs.
- Persisted GraphQL queries. For mobile, send a query ID instead of the full query text. That saves bytes, and the server only accepts known queries, which helps security.
- Server-driven UI. Taken further, the BFF returns a description of the screen (sections, components, actions) that the app renders with native components. Layouts can then change without an app release. Airbnb has described its server-driven UI system, the Ghost Platform, used across its apps. The trade-offs are a more complex client renderer and contract versioning, plus a design system both sides share.
Pagination for lists and feeds.
- Use cursor pagination, not offsets. New items arriving at the top shift offsets, causing duplicates or gaps as the user scrolls. A cursor ("after item X", opaque to the client) is stable.
- Choose page sizes for the device. Use 10–30 items, so the first screen is fast and the next page is fetched as the user nears the end. Prefetch one page ahead.
- Make page responses self-contained. Embed the minimal related data (author name and avatar URL) so the app can render without follow-up calls. Include stable IDs, so the local database can upsert and deduplicate.
Delta sync endpoints. Return changes since a server-issued cursor, plus tombstones, as described in the sync section. Typical endpoints:
GET /sync?since=…&limit=500for the whole user dataset;- per-collection deltas such as
GET /conversations/812/messages?after=…; - ETags with
If-None-Match(HTTP 304, an empty body) for resources that rarely change, such as configuration and catalogues.
Payload efficiency.
- Compress responses with gzip or Brotli. JSON typically shrinks 70–90%.
- Omit unused fields. That's GraphQL field selection, sparse fieldsets, or BFF shaping.
- Consider Protocol Buffers. They're used with gRPC, or over plain HTTP. They give smaller, faster-to-parse payloads and schema-checked evolution, which suits high-volume or bandwidth-sensitive apps.
- Never inline large media. Return URLs for CDN-hosted images, with size variants and placeholders.
- Batch analytics and logs into periodic compressed uploads.
- Use HTTP/2 or HTTP/3. HTTP/3 (QUIC) helps mobile especially, because connection migration survives Wi-Fi to cellular changes, and it avoids TCP head-of-line blocking on lossy links (HTTP, HTTP/2, HTTP/3 and HTTPS).
Retries, rate limits and herd effects.
- Make every mutating endpoint idempotent. Use idempotency keys or naturally idempotent verbs such as PUT. Mobile clients will retry after timeouts, and a payment or message must never be applied twice.
- Rate limit by user, device or API key, not IP. Carrier-grade NAT shares IPs across thousands of users. Return 429 with
Retry-After, and make the app honour it (Rate Limiting and Throttling). - Beware the client fleet as a DDoS.
- Retry storms. If 10 million apps retry a failed call every 5 seconds without backoff during an outage, that's 2 million requests per second hitting a recovering backend.
- The fix for retries: exponential backoff with full jitter, capped (say at 5 minutes). Add a server-controlled kill switch in remote config that can slow polling or disable a feature fleet-wide.
- The same herd from pushes. A push sent to 10 million devices that each sync immediately creates the same spike. Add a random client-side delay (0–60 s), or include the needed data in the push.
Versioning old clients and forced upgrades#
On the web, everyone runs the latest frontend within minutes of a deploy. On mobile, dozens of app versions are in use at once, and some are years old. Every API change must be evaluated against that whole fleet.
Keep APIs backward compatible by default:
- Additive changes only. Add fields and endpoints; never rename or remove fields that old clients read. Clients must be tolerant readers that ignore unknown fields and unknown enum values, mapping unknown values to a safe "unknown" case rather than crashing.
- Send version information on every request: a header such as
X-App-Version: 8.42.0 (build 18231), plus platform and OS version. The backend can then vary behaviour for old versions, and dashboards can show traffic by version. - Version the API explicitly for breaking changes (
/v2/..., or versioned GraphQL fields), and keep old versions until their traffic falls below a threshold. - Define a support window, for example "we support app versions released in the last 12–18 months", and publish it internally, so backend teams know what they can remove and when.
- Use contract tests that run old clients' recorded requests against new backend builds, catching accidental breakage before deploy.
Forced and soft upgrades. A minimum-version policy, served by remote config or a startup endpoint, has three levels:
- Soft upgrade (nudge). A dismissible banner: "A new version is available."
- Hard upgrade (block). A full-screen "Please update to continue", used when an old version is broken or unsafe: a security vulnerability, a payment bug, or an API that can no longer be supported.
- Targeted kill switches. Disable just the broken feature in old versions instead of blocking the whole app.
Implementation details:
- Platform support. On Android, Google Play's In-App Updates API supports immediate (blocking) and flexible (background download) flows. On iOS there's no equivalent system API, so apps check their own minimum-version endpoint and deep-link to the App Store.
- The check must be robust. Fetch the minimum-version policy early, cache it, and fail open if the policy endpoint is unreachable. Don't lock users out because your config service is down. Version comparisons must handle build numbers correctly (8.10 is newer than 8.9).
- Use forced upgrades sparingly. They interrupt users, and some can't update: old OS versions, managed devices, no storage space. Before raising the minimum, check how many active users run versions below it, and check the minimum OS version the new app requires, or you'll lock out users with older phones entirely.
- Plan the server-side retirement:
- watch per-version traffic;
- announce deprecation through soft prompts;
- raise the minimum version;
- only then delete the old API path. Typical old-version long tails make this a months-long process, not a sprint.
Feature flags and staged rollouts#
Because binaries can't be rolled back, mobile teams separate shipping code from releasing features. That takes three tools: feature flags, staged store rollouts, and experiments.
Feature flags and remote config.
- Ship dark. New features ship in the binary disabled behind a flag. A remote config service enables them for internal users, then a percentage of users, then everyone. If a problem appears, turning the flag off fixes it within minutes, for every installed version that has the flag. That's the only true mobile "rollback" (CI/CD and Deployment Strategies).
- How the client evaluates flags:
- Fetch the config at launch and periodically, and cache it locally.
- Ship compiled-in defaults so the app works offline and on first launch.
- Usually apply new values at the next launch or a safe moment, so the UI doesn't change under the user mid-session.
- Targeting rules cover app version, OS version, country, language, device class, user segment and percentage. Percentages use a stable hash of the user ID, so a user doesn't flip in and out between sessions.
- Use flags for more than features:
- kill switches for risky integrations;
- tunable parameters, such as polling interval, page size, image quality and retry caps, which help during incidents;
- migrations, such as reading from a new API with a fallback to the old one.
- Tools. Firebase Remote Config, LaunchDarkly, Statsig, Optimizely and Unleash, or an in-house config service with a CDN-cached JSON document.
- Manage flag debt. Every flag is a branch in the code and in the test matrix. Track owners and expiry dates, and remove flags once a feature has fully launched. Stale flags in old binaries live forever, so keep them simple.
Staged rollouts in the stores.
- Apple's phased release spreads an update over 7 days to users with automatic updates on (1%, 2%, 5%, 10%, 20%, 50%, 100%). It can be paused if problems appear, and users can still update manually from the store.
- Google Play staged rollouts let you choose any percentage, increase it as health metrics hold, and halt the rollout. Halting stops further distribution, but doesn't remove the update from devices that already have it.
- Before the store: internal dogfood builds (TestFlight, Play internal testing), then a beta channel of opted-in users, then the staged production rollout.
A typical release pipeline:
- Cut the release branch from main on the weekly train.
- Run automated tests and checks: unit, UI and screenshot tests, app size and startup-time checks.
- Use internal builds with employees for 2–3 days.
- Submit for store review.
- Run the staged rollout at 1–10%, watching crash-free rate, ANRs, startup time and key business metrics against the previous version.
- Continue or halt. Expand to 100% if healthy. Halt and ship a hotfix if not, while flags disable the offending feature for those already updated.
Experiments. The same flag system assigns users to A/B variants. Exposure is logged when the user actually sees the feature, not when the config is fetched. Analysis runs on the experimentation platform with guardrail metrics such as crash rate, latency and battery (Design an A/B Testing and Experimentation Platform).
Mobile experiments must account for:
- version fragmentation. A variant can only reach users on versions that contain it.
- lagging adoption, which biases early samples toward heavy users who update quickly.
Crash and performance monitoring#
Because you can't see users' devices, telemetry from the field is how you know whether a release is healthy. It's the gate for every staged rollout.
Crash reporting.
- Capturing crashes. SDKs such as Firebase Crashlytics, Sentry, Bugsnag and Embrace capture:
- native crashes (signals and exceptions);
- Android ANRs;
- iOS watchdog terminations and out-of-memory kills (inferred, since the OS gives no callback);
- non-fatal errors you log.
- Making traces readable. Release builds are obfuscated and stripped, so stack traces must be symbolicated:
- upload iOS dSYM files;
- upload Android R8 or ProGuard mapping files and NDK symbols for every build in CI;
- a missing symbol upload makes a release's crashes unreadable.
- Context. Attach breadcrumbs: recent screens, network calls and state changes leading to the crash, plus the device model, OS version, app version, free memory and active feature flags. Never include PII or message content.
- Key metrics:
- crash-free users and crash-free sessions per version. Mature apps aim for 99.9% crash-free users or better;
- top crash clusters by affected users;
- new crashes introduced by this release.
- Store thresholds. Google Play's Android vitals defines "bad behaviour" thresholds, including a user-perceived crash rate of 1.09% and a user-perceived ANR rate of 0.47% across devices. Exceeding them can reduce the app's visibility in the Play Store. Apple surfaces crash, hang, launch-time and energy metrics in Xcode Organizer, and delivers on-device diagnostics through MetricKit.
Performance monitoring:
| Metric | What it means | Typical target or flag |
|---|---|---|
| Cold start time | Process launch to first useful frame | Apple's guidance is to show the first frame within about 400 ms; Android vitals flags cold starts of 5 s or more as excessive |
| Slow and frozen frames | Frames over 16 ms (60 Hz) and over 700 ms | Track the percentage per screen, especially in lists |
| ANR or hang rate | Main thread blocked (Android ANR at 5 s for input; iOS hangs) | Keep below store thresholds; investigate any regression |
| Network | Request latency, error rate, payload size, by endpoint, country and network type | p50 and p95 per endpoint, as seen by the client |
| Screen load time | Navigation to content rendered | A per-screen budget, for example 1 s from cache, 2 s from network |
| App size and memory | Download size, peak memory, OOM rate | Watch growth per release |
| Battery and data use | Background wakeups, location usage, bytes per session | Regressions often come from SDKs and polling |
How the telemetry is used:
- Compare each new version against the previous one at the same rollout stage. Early adopters differ from the average user, so a 2% cohort is compared with the same 2% stage of the previous release.
- Alert on regressions and wire them to rollout halts.
- Segment by device tier. Low-end Android devices often reveal problems flagships hide.
- Add distributed tracing with a trace ID header on API calls, which connects a slow screen to the slow backend span (Observability: Logs, Metrics and Traces).
- Batch telemetry and upload it on Wi-Fi or with other traffic, to respect battery and data. Sample high-volume performance events, but keep every crash.
When to Use It#
Apply the mobile system design lens when:
- The interview says "design the app," not "design the backend". Examples are "design the Instagram app," "design an offline-capable notes app," "design a chat client," or a mobile engineer loop at a company with large native apps. The interviewer expects device constraints, local storage, sync, push and release engineering, not database sharding.
- Users must work with bad or no connectivity. Field workers, travellers, emerging markets, fitness tracking in the wilderness, messaging on the subway. Offline-first architecture, an outbox and delta sync are central here.
- Battery, data cost or background execution shape the feature. Location tracking, media upload, background refresh, wearables. The OS rules decide what is possible.
- You own a backend that serves mobile clients. API design for mobile, such as BFFs, payload size, version support windows, retry discipline and push fan-out, is a backend concern caused by mobile realities.
- Release risk is high. Large installed bases, regulated industries, or features where a crash loop would be catastrophic. Flags, staged rollouts and release-health monitoring become mandatory.
When NOT to Use It#
Pick something else instead when:
- The product is content that a responsive website serves well. A marketing site, documentation or a simple form flow doesn't justify native apps, store review cycles and multi-version support. A fast web app or PWA is cheaper (Frontend System Design).
- The question is about backend scale. "Design WhatsApp's backend for 2B users" is about message routing, storage and fan-out. Spend a few minutes on client concerns (Client, Mobile and Frontend Considerations) and put the depth on the server.
- You don't need full offline-first. A banking app may only need a cached read-only view plus online-only writes. Building a general sync engine with conflict resolution for data that must be authoritative on the server adds complexity and risk without benefit.
- The team is small and must cover both platforms. A cross-platform framework (React Native, Flutter, Kotlin Multiplatform) often beats two native codebases, even though this page's native-first depth still applies under the hood.
- Server-driven UI everywhere. Driving every screen from the server makes the client a browser with worse tooling. Use it for frequently changing surfaces such as home feeds and promotions, not for core interaction screens.
How to Implement It#
A practical path for a new offline-capable mobile app, or for answering a mobile design question:
- Write down the constraints first.
- Which flows must work offline (read, write, or both)?
- Which data is sensitive?
- What background work is needed (upload, location, refresh)?
- What are the target devices and OS versions?
- How large is the installed base, which drives the version support window?
- Choose the architecture. Use MVVM or UDF with a repository layer. The UI observes local state; repositories coordinate the local database and network. Use DI and feature modules so teams and build times scale.
- Make the local database the source of truth for the UI.
- Storage: SQLite (Room, GRDB, SQLDelight) or Core Data/SwiftData.
- Rendering: screens render from the database and update reactively.
- Network: network responses write into the database, never straight into the UI.
- Design the sync protocol.
- Use pull with a server cursor and tombstones, plus a full-resync path.
- Use push through a persistent outbox with client-generated IDs and idempotency keys.
- Pick an explicit conflict policy per entity.
- Integrate push as a hint, not a data channel.
- Register tokens and refresh them on every launch, and clean up on 410 or "unregistered".
- Treat a push as a "sync now" trigger.
- Use a Notification Service Extension or a data message to fetch rich content.
- Use the OS schedulers for background work. Use WorkManager on Android, and BGTaskScheduler plus background URLSession on iOS. Add constraints (network, charging), exponential backoff and idempotent jobs. Use a foreground service or location mode only when the user can see the value.
- Shape the API for mobile.
- Add a BFF or GraphQL layer with persisted queries.
- Use cursor pagination and delta endpoints.
- Send compressed payloads and image URLs sized for the device.
- Send
Retry-Afteron 429 and 503; clients add jitter.
- Plan versioning.
- Make additive API changes only.
- Use tolerant readers.
- Send version headers.
- Keep a minimum-supported-version config with soft and hard upgrade prompts.
- Add contract tests against the last N app versions.
- Release safely. Ship every feature behind a flag with a safe compiled-in default. Then go through dogfood, beta and a staged store rollout, with automated health gates.
- Instrument from day one.
- Crash and ANR reporting with symbol uploads in CI.
- Cold start, frame and screen-load metrics.
- Client-side network metrics with trace IDs.
- Dashboards split by version and device tier.
The heart of an offline-first client is the outbox processor. It drains locally queued mutations in order, retries safely, and never loses a write:
type Mutation = { id: string; entity: string; op: "upsert" | "delete";
payload: unknown; attempts: number; createdAt: number };
async function drainOutbox(db: LocalDb, api: Api, net: Network): Promise<void> {
if (!net.isOnline()) return; // wait for connectivity callback
const pending = await db.outbox.oldestFirst(50); // FIFO keeps causal order
for (const m of pending) {
try {
// Idempotency key = mutation id, so a retry after a lost response is safe
const res = await api.send(m.entity, m.op, m.payload, { idempotencyKey: m.id });
await db.transaction(async (tx) => {
await tx.applyServerVersion(m.entity, res.record); // server is canonical
await tx.outbox.remove(m.id);
});
} catch (err) {
if (isPermanent(err)) { // 400/409/422: never succeeds
await db.outbox.moveToDeadLetter(m.id, err); // surface "couldn't save" in UI
continue;
}
await db.outbox.incrementAttempts(m.id);
const delayMs = Math.min(300_000, 1000 * 2 ** m.attempts) * Math.random(); // full jitter
scheduler.retryAfter(delayMs, "drainOutbox"); // WorkManager / BGTask under the hood
return; // stop: preserve ordering
}
}
if (pending.length === 50) scheduler.runSoon("drainOutbox");
}Key choices in the snippet:
- The mutation ID doubles as the idempotency key, so a write whose response was lost is applied only once.
- The server's version replaces the local optimistic row in the same transaction that removes the outbox entry, so a crash between the two steps can't leave the app in a mixed state.
- Permanent errors go to a dead-letter list the UI can show, instead of blocking the queue forever.
- Transient errors stop the drain to preserve ordering.
- Retries use capped exponential backoff with full jitter so a fleet coming back online doesn't stampede the server.
| Technology | Fits when |
|---|---|
| Kotlin + Jetpack Compose, ViewModel, Room, WorkManager | Native Android with modern declarative UI, a reactive local database and OS-compliant background work |
| Swift + SwiftUI/UIKit, SwiftData/Core Data or GRDB, BGTaskScheduler | Native iOS; GRDB when you want explicit SQLite control and observation |
| React Native | A JavaScript/TypeScript team, shared logic with web, and mostly standard UI; native modules for heavy features |
| Flutter | One codebase with pixel-consistent custom UI across platforms |
| Kotlin Multiplatform | Sharing business logic, networking and the database layer while keeping fully native UI |
| Realm, Couchbase Lite, Firebase/Firestore offline, AWS Amplify DataStore | Managed offline sync without building the protocol yourself, with less control over conflicts and schema |
| APNs + FCM (direct or via a provider like OneSignal, Braze, Airship) | Push delivery; providers add segmentation, scheduling and analytics |
| Glide, Coil, Fresco / Kingfisher, SDWebImage, Nuke | Image loading with memory and disk caching, downsampling and request lifecycle |
| Firebase Remote Config, LaunchDarkly, Statsig, Unleash | Feature flags, remote config, percentage rollouts and experiments |
| Crashlytics, Sentry, Bugsnag, Embrace, MetricKit, Android vitals | Crash, ANR, hang and performance monitoring across versions |
| Fastlane, Bitrise, GitHub Actions, Xcode Cloud | Mobile CI/CD: signing, builds, screenshot tests, store uploads |
Trade-offs#
| Decision | Option A | Option B | How to choose |
|---|---|---|---|
| Data ownership | Online-first: server is the truth, the client caches responses | Offline-first: local DB is the truth for the UI, sync in the background | Offline-first when users must read and write without network; online-first when data must be authoritative and fresh (balances, inventory) |
| Conflict policy | Last-writer-wins: simple, loses concurrent edits | Field-level merge, CRDTs or server-side rules: preserve intent, more complex | LWW for single-owner data; merges for shared or collaborative data (Conflict Resolution, OT and CRDTs) |
| Codebase | Two native apps: best performance and platform fit, double the work | Cross-platform: shared code and team, a bridge and abstraction layer | Native for platform-heavy apps (camera, maps, wearables); cross-platform for business apps and small teams |
| UI delivery | Client-defined screens: fast and type-safe, change needs a release | Server-driven UI: change without a release, harder to test and evolve | SDUI for fast-changing surfaces; client UI for core interactions |
| Real-time updates | Push hint + pull: battery-friendly, delay of seconds | Persistent socket in the foreground: instant, costs battery and server connections | Socket only while the screen is active (chat, live tracking); push when backgrounded |
| Image quality | Higher resolution: sharper, more data, memory and decode time | Server-sized variants per device: efficient, more CDN variants | Always request the size you display; adapt to network type and data-saver mode |
| Background work | Defer to the OS scheduler: battery-friendly, timing not guaranteed | Foreground service / continuous mode: reliable timing, a visible notification and user scrutiny | Scheduler for sync and uploads; foreground only for user-visible ongoing tasks (navigation, workout recording) |
| Release speed | Weekly train: predictable, small diffs, regular cadence | Release when ready: fewer releases, bigger and riskier diffs | Most large apps use weekly or biweekly trains plus flags; hotfixes skip the train |
| Upgrade policy | Long support window: happy users, more backend compatibility code | Aggressive hard upgrades: less legacy, user friction and churn | Support 12–18 months; hard-upgrade only for security or broken contracts |
Common Pitfalls#
- Rendering network responses directly. The screen goes blank offline, flickers between states, and loses data on process death. Write to the local store; render from it.
- Unbounded retry loops. Fixed-interval retries without jitter create synchronized storms when a backend recovers. Retry forever without a dead-letter path, and one poison mutation blocks every later write.
- No client-generated IDs. A create whose response was lost gets retried and creates a duplicate. Generate the UUID on the device and use it as the idempotency key.
- Treating push as reliable delivery. Pushes are dropped, collapsed, delayed by Doze, or disabled by the user. Always reconcile with a sync on app open.
- Decoding full-size images into lists. A 12 MP photo decoded at full size costs about 48 MB. A few of them cause OOM kills and jank. Downsample to the view size.
- Doing work on the main thread. Disk I/O, JSON parsing of large payloads, or database queries on the UI thread cause ANRs and hangs. Use background dispatchers and measure with StrictMode or Instruments.
- Fighting the OS on background work. Custom alarms, wake locks and hidden services get throttled, killed, or flagged by store review. Use the platform schedulers and design for deferral.
- Breaking old clients with API changes. Renaming a field or changing an enum crashes versions that will stay installed for years. Make changes additive, read tolerantly, and contract-test old versions.
- Shipping without a remote kill switch. A crash in a new feature then needs a store review cycle to fix while users crash-loop.
- Missing symbol uploads. Crashes arrive unreadable exactly when you need them most. Make dSYM and mapping uploads a mandatory CI step.
- Logging PII in breadcrumbs or analytics. Phone numbers, message text and precise location in telemetry create privacy and regulatory exposure. Scrub at the source.
- Storing secrets insecurely. Tokens belong in the Keychain or Android Keystore-backed storage, never in plain preferences or the app bundle. Assume the binary will be reverse-engineered (Security Fundamentals for System Design).
Real-World Examples#
- Uber. Uber rebuilt its rider app in 2016 around RIBs (Router, Interactor, Builder). The architecture is driven by business logic instead of views, so hundreds of engineers could work in parallel on one app. Uber open-sourced RIBs in 2017.
- Facebook / Meta.
- Fresco (2015) is an Android image pipeline that kept decoded bitmaps outside the Java heap on older Android versions, to avoid garbage-collection pauses and OOMs in image-heavy feeds.
- "2G Tuesdays" (2015) let employees opt into a simulated slow connection, to build empathy for users on poor networks.
- Facebook Lite was a very small app for low-end devices and expensive data.
- Airbnb.
- Sunsetting React Native (2018). In a public blog series, Airbnb described leaving React Native. They cited the cost of maintaining bridges, three platforms' worth of infrastructure and immature tooling, while keeping the lessons.
- Ghost Platform. Later, Airbnb described this server-driven UI system: sections and screens are described by the backend and rendered by native components on each platform.
- Shopify. In 2020 Shopify announced React Native as the default for its mobile apps, citing shared code and a larger engineering pool. The contrast with Airbnb shows that cross-platform fit depends on the team and product.
- Netflix. Offline downloads (2016):
- encoded content specifically for mobile download sizes;
- managed licences (DRM) with expiry and download limits;
- synced watch progress when the device came back online.
- Instagram. Early Instagram engineers described starting the photo upload in the background while the user was still writing the caption, so pressing "Share" felt instant. It's a classic example of hiding latency with optimistic, speculative work.
- Strava. Records workouts fully offline with GPS. The activity is stored locally and uploaded when connectivity returns, which is the canonical example of an outbox for a high-value user write.
- Apple and Google. Both stores have phased or staged releases. Apple's is a 7-day automatic schedule that can be paused. Google Play uses percentage rollouts that can be halted. This is why every serious mobile team pairs store rollouts with remote flags.
Case studies that use this pattern#
- Design a Notification System: APNs and FCM fan-out, token lifecycle, priorities, collapse keys, quiet hours and per-user rate limits.
- Design a Chat System (WhatsApp): a foreground socket with push fallback, a local message database, outbox and delivery receipts, and multi-device sync.
- Design a Photo Sharing App (Instagram): image sizing, background uploads, feed caching and prefetch.
- Design a Fitness Tracking App (Strava): offline GPS recording, battery-aware location, and upload on reconnect.
- Design File Storage and Sync (Dropbox / Google Drive): delta sync, chunked resumable uploads, conflicts and background transfer.
- Design a Ride-Hailing App (Uber): location updates, realtime driver tracking, flaky networks and idempotent ride requests.
In the Interview#
Radio, battery and batching arithmeticShow
Network behaviour on mobile is mostly a power problem, and the arithmetic shows why batching matters more than bytes.
The radio state machine. A cellular radio has a low-power idle state and a high-power connected state.
- Promotion. Sending even one small packet promotes the radio to the connected state. On LTE this takes on the order of a few hundred milliseconds, which adds latency to the first request.
- The tail. After the last packet, the radio stays in the high-power state for a tail period before demoting, in case more traffic follows.
- The measured cost. Huang et al.'s measurement study of LTE ("A Close Examination of Performance and Power Characteristics of 4G LTE Networks", MobiSys 2012) found that the tail lasts on the order of ten seconds. That tail energy dominates the cost of small, periodic transfers. 5G and carrier settings change the exact values, not the principle.
A worked example. The numbers are illustrative but realistic.
- Assumptions:
- The connected state draws about 1 W.
- Each wakeup costs about 12 s of high-power time, counting the promotion, the transfer and the tail.
- That comes to roughly 12 J per wakeup, whether you send 200 bytes or 200 KB.
- A typical phone battery holds about 4,000 mAh × 3.85 V ≈ 15.4 Wh ≈ 55,000 J.
- Polling every 60 s means 60 wakeups an hour, or 720 J an hour. That's about 1.3% of the battery per hour, around 30% a day, for one feature, if nothing else would have woken the radio.
- Polling every 15 minutes means 4 wakeups an hour, or 48 J. That's about 0.09% per hour.
- Riding on other traffic costs close to zero: piggyback on a push-triggered sync, or on an OS-scheduled window where other apps' work is also batched.
Design consequences:
- Coalesce requests. Five small requests in the same second share one promotion and one tail; five requests spread over a minute pay five tails. Combine analytics, prefetch and sync into one burst.
- Replace polling with push hints. One push wakes the device only when there's something to fetch.
- Defer non-urgent work to Wi-Fi, charging or OS maintenance windows. WorkManager and BGTaskScheduler exist mainly to batch work across apps.
- Prefer fewer, larger transfers. Downloading a 2 MB batch once costs less energy than downloading 200 KB ten times.
- Mind the uplink. Sending is often more expensive per byte than receiving, especially at weak signal where transmit power rises. Compress uploads and avoid chatty telemetry.
Data cost matters too. A feed screen that loads 30 images at 300 KB each costs 9 MB. Serving 100 KB variants sized to the device cuts that to 3 MB. On a prepaid plan in an emerging market, that difference decides whether people keep the app. Data-saver modes (Android's Data Saver, iOS Low Data Mode) are signals the app should respect: lower image quality, no autoplay, no background prefetch.
Sync protocol design: cursors, tombstones, clocks and conflictsShow
An offline-first app is only as good as its sync protocol. The details that bite in production:
1. Don't use timestamps as cursors. "Give me everything with updated_at > last_seen" looks simple, but it has three bugs:
- Clock skew across servers.
- Ties within the same millisecond.
- Out-of-order commits, the worst one. Transaction A takes timestamp 100 but commits after transaction B at timestamp 101. A client that synced in between saw 101, advanced its cursor past 100, and never receives A.
The fixes:
- A server-assigned sequence number allocated at commit time. For example, a per-user or per-partition change-log table appended in commit order, or a position in the database's replication log.
- A safety lag. Only serve changes older than a few seconds, and re-scan an overlap window, deduplicating by ID and version.
2. Use tombstones for deletes.
- Why tombstones. A pull-based client can't see a row that no longer exists, so deletes are recorded as tombstones: entries in the change log that say "ID X deleted at sequence S".
- Retention. Tombstones can't be kept forever, so they have a retention period, say 30 or 90 days.
- Expired cursors. If a client's cursor is older than the retention horizon, the server must reply "cursor expired, reset", and the client does a full resync. That means a fresh snapshot plus a new cursor, while keeping its unsent outbox.
- The cost of resets. Full resyncs are expensive. If a server bug invalidates every cursor for 10M users, each pulling a 5 MB snapshot, that's 50 TB of egress and a self-inflicted thundering herd. Protect cursors and stagger forced resets.
3. Use server versions for optimistic concurrency.
- Check the base version on writes. With a central server you rarely need vector clocks for app data. Each record carries a server version. The client's mutation includes the
base_versionit edited. The server accepts the write if the version matches. Otherwise it returns a conflict, which it can resolve automatically or report to the client. - Version vectors. These are needed when there's no single authority, such as peer-to-peer sync or multi-leader replicas.
- Hybrid logical clocks for client events. Ordering client-generated events, like messages and edits, across devices with skewed clocks is the job of hybrid logical clocks. They combine physical time with a logical counter so causality is preserved while values stay close to wall-clock time (Kulkarni et al., "Logical Physical Clocks and Consistent Snapshots in Globally Distributed Databases", 2014).
4. Pick a conflict policy per entity, not per app:
| Entity | Policy |
|---|---|
| User settings | Last-writer-wins per field, so changing the theme on one device and the language on another both survive |
| Counters, such as likes | Send operations ("+1") instead of values; the server sums them |
| Sets, such as tags and members | Add and remove operations with add-wins or remove-wins semantics, the idea behind OR-Set CRDTs |
| Free text | Conflict copies for whole documents, or OT/CRDT merges for real-time collaboration (Conflict Resolution, OT and CRDTs) |
| Money, inventory, bookings | No client-side merge. Online-only or server-validated, with a clear "failed, retry" state |
5. Define the sync scope and window. Clients rarely need all data.
- Sync per scope: the user's own data, a channel, a team.
- Limit history: the last 30 days of messages, the next 2 weeks of a calendar.
- Fetch older data on demand.
This bounds local storage and initial sync time. An initial sync of 50k records at 1 KB each is 50 MB; scoping it to 5k records makes onboarding fast.
6. Plan for local schema migrations. Users skip versions. Someone upgrading from v3 to v9 must run every migration in order, on a database that may hold years of data, without exceeding startup time limits. To handle this:
- Keep migrations small.
- Test upgrade paths from old versions with real-size databases.
- Move heavy backfills into background jobs.
- If migration is impossible, have a "drop cache and resync" escape hatch for derived data. Never use it for unsent user writes.
Release engineering statistics: adoption curves and staged-rollout detection powerShow
Staged rollouts only work if the early cohort is large enough to detect a regression before it reaches everyone. That's a statistics question.
Version adoption curves. With automatic updates, a new version's share rises quickly in the first days and then flattens into a long tail. Some devices update weeks or months later, and some never do: storage full, automatic updates off, OS too old for the new build.
- The backend sees many versions at once. Measure your own adoption curve by counting the app version header in traffic. It sets the support window and tells you how long a buggy version keeps generating traffic after a hotfix.
- Plan for both halves of the curve. A rule of thumb: assume a fix reaches most active users within one to two weeks, and that a small percentage stays on any version for many months.
Detection power. In this example:
- The app has 10M DAU.
- The baseline crash rate is 0.1% of users per day, which is 99.9% crash-free users.
- A rollout at 1% reaches 100k users a day.
- Expected crashing users in the cohort: 100k × 0.001 = 100.
- Crash counts are roughly Poisson, so the standard deviation is about √100 = 10.
A big regression is obvious. If the new version doubles the rate to 0.2%, you expect 200 crashing users instead of 100. That's about ten standard deviations, obvious within hours.
A small regression needs more exposure. Take a 20% relative increase, from 0.10% to 0.12%, across N user-days:
- Excess crashes: 0.0002 × N.
- Noise: √(0.001 × N).
- z ≈ 0.0002 × N ÷ √(0.001 × N) ≈ 0.0063 × √N.
For a confident z of 4, √N ≈ 630, so N ≈ 400k user-days. That's four days at 1%, or one day at about 4%. Hence the 1% → 2% → 5% → 10% ramps: each step buys the exposure needed to see smaller regressions before the blast radius grows.
Practical pitfalls in reading the numbers:
- Early-adopter bias. Users who update on day one skew toward heavy users on newer devices and good networks. Compare the new version against the previous version at the same stage of its rollout, not against the whole fleet.
- Rare, device-specific crashes. A bug that only hits one chipset on one OS version may affect 1 in 100k users. It won't be visible at 1%. Segment dashboards by device model, OS version and form factor, and keep watching after 100%.
- Peeking. Checking a dashboard every hour and halting at the first "significant" spike inflates false alarms. That's acceptable for crash gates, where halting is cheap, but it's a real problem for experiment metrics, which need sequential testing methods or a fixed analysis horizon (Design an A/B Testing and Experimentation Platform).
- Metrics beyond crashes. Many bad releases don't crash. They break login, slow startup by 30%, or drain the battery. Gate on business guardrails as well: sign-in success, checkout conversion, messages sent per user, cold-start p90, ANR rate.
What to automate. Mature teams wire these comparisons into the rollout tool:
- Advance the rollout automatically when the gates pass.
- Pause automatically and page the release owner when any gate fails.
- Combine this with remote flags, so the response to a bad feature is usually minutes (flag off), not days (hotfix through review).
Key Takeaways#
- Mobile design starts from constraints the server world doesn't have: flaky networks, battery-dominated radio costs, OS process kills and background limits, and binaries you can't roll back.
- Make the local database the UI's source of truth. Sync it with cursor-based delta pulls (with tombstones and a reset path) and an outbox of idempotent, client-ID'd mutations.
- Treat push as a hint, not a data channel. Use a high-priority push to wake the app, a delta sync to fetch the truth, and a foreground socket only while the user is looking.
- Images and background work cause most performance and battery problems. Downsample to the view size, cache in two levels, and hand background work to WorkManager or BGTaskScheduler.
- Shape the API for mobile: a BFF, cursor and delta endpoints, small payloads,
Retry-Afterwith client jitter, and additive-only changes that keep years-old versions working. - Release safety comes from layers: feature flags with compiled-in defaults, dogfood and beta builds, staged store rollouts, and automated health gates on crash-free rate, ANRs, startup time and business metrics.
- Detection power sets rollout speed. 1% of a large user base finds big regressions in hours, but small ones need days or larger cohorts. Compare against the previous version at the same rollout stage.