Mobile System Architecture and Offline-First Design Questions
Architecting the mobile side of a distributed system: client-server sync, offline-first storage and conflict resolution, background processing, push notifications, and modular mobile architecture at scale. Covers syncing state across intermittent connectivity and designing backends for millions of mobile clients. The mobile-specific slice of distributed design.
Implement a small algorithm in Kotlin or Swift that schedules background syncs for a mobile app: batch-send queued analytics when the device is charging and on Wi-Fi, but ensure events older than 24 hours are sent regardless of state. Provide code, explain complexity, and discuss battery/network trade-offs.
Sample Answer
Brief approach
Schedule periodic background work that checks queued events and batches them when device is charging and on Wi‑Fi; however, always force-send events older than 24 hours. On Android use WorkManager; below is a Kotlin example using WorkManager + constraints + timestamp check.
// Kotlin (Android) — WorkManager Worker to batch-send analytics
class AnalyticsWorker(
ctx: Context,
params: WorkerParameters
): CoroutineWorker(ctx, params) {
private val repo = AnalyticsRepository(ctx) // handles queue, storage, network
override suspend fun doWork(): Result {
val now = System.currentTimeMillis()
val cutoff = now - TimeUnit.HOURS.toMillis(24)
// 1) If there are events older than 24h, send them regardless of connectivity
val stale = repo.peekOlderThan(cutoff)
if (stale.isNotEmpty()) {
repo.sendBatch(stale) // blocking suspend; handles retries/backoff
repo.remove(stale)
return Result.success()
}
// 2) Otherwise, if constraints satisfied (WorkManager ensures this task only runs when constraints met),
// send a bounded-size batch to avoid large network ops.
val batch = repo.peekRecentBatch(limit = 100)
if (batch.isEmpty()) return Result.success()
return try {
repo.sendBatch(batch)
repo.remove(batch)
Result.success()
} catch (e: Exception) {
Result.retry()
}
}
companion object {
fun schedule(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED) // Wi‑Fi
.setRequiresCharging(true)
.build()
val req = PeriodicWorkRequestBuilder<AnalyticsWorker>(15, TimeUnit.MINUTES)
.setConstraints(constraints)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
"analytics-sync",
ExistingPeriodicWorkPolicy.KEEP,
req
)
}
}
}
Key concepts
- WorkManager enforces constraints on Android; we still check for stale events inside worker.
- Repository handles persistence, batching, exponential retry and idempotency.
Complexity
- Time: O(n) per run where n = events examined; typically bounded by batch limit.
- Space: O(b) where b = batch size in memory.
Battery/network trade-offs
- Favor Wi‑Fi + charging to minimize battery and cellular cost; use small bounded batches to avoid long radio awake times.
- For stale events, force send may wake radio and cost battery — mitigate by sending minimal payload, coalescing events, and limiting forced-sends frequency (e.g., check ages only when WorkManager triggers or on significant device state changes).
- Use exponential backoff and idempotent endpoints to avoid wasteful retries.
Explain why stateless service design helps scale mobile backends. Describe the role of load balancers, autoscaling groups, health checks, and one example of a stateful component (e.g., WebSocket server) you would isolate and how you'd manage it.
Sample Answer
Why stateless helps scale mobile backends
Stateless services don’t store client session/data on the app server, so any instance can handle any request. For mobile apps with many short-lived API calls (auth, sync, analytics), stateless design enables horizontal scaling, simpler deployments, faster recovery, and easier A/B rollouts.
Role of components
- Load balancers: distribute incoming mobile requests across healthy instances; perform SSL termination and path/rate routing so clients don’t need to know instance topology.
- Autoscaling groups: add/remove stateless instances based on CPU, request rate or custom metrics (e.g., requests/sec from mobile users) to match demand and control cost.
- Health checks: LB + ASG probes (HTTP/ICMP) ensure traffic goes only to healthy nodes; unhealthy instances are replaced automatically, keeping user experience stable.
Example stateful component and isolation
- WebSocket server for real-time chat/notifications is stateful (maintains connections). I’d isolate it into its own service/cluster with:
- A dedicated autoscaling group tuned to connection count (scale by active sockets).
- A sticky-aware load balancer or a routing layer (e.g., a message router like HAProxy or NGINX with consistent-hash) so reconnects hit the same process when needed.
- Shared state in Redis (presence, user->server mapping) and a pub/sub (Redis Pub/Sub or Kafka) to fan out messages across instances.
- Health checks that verify socket accept loop and Redis connectivity; on failure, reassign users via Redis mapping and rely on clients to reconnect with exponential backoff.
This pattern keeps core APIs elastic and simple for mobile clients while handling connection state in a specialized, scalable service.
List and compare common client-side storage options available to mobile developers on iOS and Android (e.g., SQLite, Core Data, Room, Realm, LevelDB, Keychain/Keystore, SharedPreferences/DataStore). For each option, state typical use cases, strengths/weaknesses for offline-first apps, and platform-specific caveats (migrations, background access, encryption).
Sample Answer
Overview — how to choose
Pick storage by data shape, sync needs, encryption, and concurrency: key-value for small prefs/secrets, relational for structured queries and joins, object DBs for complex models/fast dev, keystore/keychain for secrets.
SQLite (iOS/Android)
- Use cases: relational data, complex queries, joins, large datasets.
- Strengths: Mature, small footprint, predictable performance, ACID.
- Weaknesses: Manual schema/migrations, boilerplate.
- Caveats: iOS uses SQLite under Core Data; Android Room abstracts migrations and threading.
Core Data (iOS)
- Use cases: object graph, undo/relationships, iOS-native model layer.
- Strengths: Integrated with Cocoa, change tracking, NSPersistentCloudKit.
- Weaknesses: Learning curve, migration complexity, less portable.
- Caveats: Background contexts required for threading; lightweight migrations possible but heavy versioning needs care.
Room (Android)
- Use cases: SQLite ORM for Android apps with compile-time queries.
- Strengths: Type-safe DAOs, integrated migrations, LiveData/Flow support.
- Weaknesses: Still SQL-based for complex queries, needs migration scripts.
- Caveats: Requires careful coroutine/dispatcher handling for background I/O.
Realm
- Use cases: Offline-first apps, reactive sync, simple object mapping.
- Strengths: Easy model mapping, fast reads/writes, built-in change notifications, optional Realm Sync.
- Weaknesses: Binary file format, vendor lock-in, larger binary size.
- Caveats: Migration API available; check background thread rules and encryption support via keys (manage securely).
LevelDB / RocksDB
- Use cases: High-write key-value, embedded storage for custom engines.
- Strengths: Fast write throughput, simple key-value semantics.
- Weaknesses: No relational queries, manual indexing, platform bindings required.
- Caveats: Rare in pure mobile apps; manage compaction and file size.
SharedPreferences (Android) / UserDefaults (iOS)
- Use cases: Small key-value config, UI state, flags.
- Strengths: Simple API, low overhead.
- Weaknesses: Not for large data or complex objects, potential blocking on main thread if misused.
- Caveats: Use DataStore (Android) or secure variants for async and consistency.
DataStore (Android)
- Use cases: Replaces SharedPreferences for async, coroutine-friendly key-value or proto.
- Strengths: Asynchronous, transactional, type-safe (Proto).
- Weaknesses: Newer; migration path from SharedPreferences needed.
- Caveats: Use protobuf for schema and migrations.
Keychain (iOS) / Keystore (Android)
- Use cases: Storing secrets, tokens, encryption keys.
- Strengths: OS-managed, hardware-backed, secure.
- Weaknesses: Limited size, access control nuances.
- Caveats: iOS Keychain persists across app reinstall with keychain-access-groups if configured; Android Keystore keys tied to device/lock-screen; handle backups and migration carefully.
Offline-first considerations
- Prefer local DB (Room/SQLite/Core Data/Realm) for full offline model and sync queue.
- Encrypt sensitive local data (use SQLCipher or platform crypto; keys in Keystore/Keychain).
- Design sync/conflict resolution (CRDTs, last-write vs merge) and background sync constraints (iOS background fetch, Android WorkManager).
- Test migrations, multi-thread access, and restore-from-backup scenarios.
Use concrete combo: Room + WorkManager + Keystore for Android; Core Data + BackgroundTasks + Keychain for iOS.
Design an eventual-consistency and conflict-resolution strategy for hierarchical data (folders and notes) on mobile where users can concurrently move, rename, and edit items offline. Requirements: preserve structural invariants (no cycles), allow concurrent operations, provide intuitive conflict UX, and describe server reconciliation and tombstone/GC policies.
Sample Answer
Approach summary
- Use an operation-based hybrid CRDT + server reconciliation. Model each item (folder/note) as an object with immutable id (UUID), mutable attributes: name, content, parent_id. Operations are: EditContent(op), Rename(op), Move(op), Create(op), Delete(op). Each op carries (actor_id, lamport_ts, op_id, causal_deps). Edits use CRDT text (RGA/Automerge-style) for intra-item concurrent edits; Rename/Move use operation arbitration with deterministic tie-breakers and structural validation.
Preserve structural invariants
- Always validate parent links to prevent cycles:
- When applying Move(item, new_parent), check ancestry: traverse parent_id chain (using local/known snapshot) to ensure new_parent is not a descendant of item. If it would create a cycle, reject/transform op.
- If ancestry is ambiguous due to concurrent moves, server computes canonical DAG using op causal order + deterministic tie-breaker (actor_id, op_id). If conflict creates cycle, server reparent the later op to a safe fallback (root or last-known-valid parent) and emit reconciliation ops to clients.
- Maintain a monotonic "ancestry-version" per item (vector clock or lamport) to assist checks.
Conflict resolution rules
- Content edits: CRDT merge (preserve all concurrent characters/edits).
- Rename: last-writer-wins by (lamport_ts, actor_id); show both names in UI as “Local: X — Other: Y” when concurrent and allow user choose.
- Move vs Move: deterministic winner by (lamport_ts, actor_id). Loser becomes a no-op but client shows inline notification and “Undo/resolve” affordance.
- Move vs Rename/Edit: both can apply; move doesn't lose edits.
- Delete vs other ops: delete wins if causally after ops; if concurrent, keep tombstone + show possible “undelete” if user explicitly restores (server records delete_ts).
Server reconciliation
- Server stores op-log per item and replays respecting causal_deps. Conflicts resolved by rules above. Server emits compacted state + reconciliation ops to clients.
- On detecting cycle after replay, server reparent offending items to computed safe-parent and append reconciliation ops; notify owners with conflict list.
Tombstones and GC
- Use tombstones for deleted items for safe causal reconciliation and to prevent "resurrected" children. Tombstone metadata: deleted_by, delete_ts, keep_children_flag (on delete-with-children semantics).
- GC policy: keep tombstones for retention_window (e.g., 30 days) + until all active clients have acked tombstone via per-client vector clock. Periodic server GC removes tombstones and hard-deletes subtree; emit finalization event.
- For mobile: compact local DB by pruning tombstones older than retention_window or after server ACK to reduce storage.
UX patterns (mobile-focused)
- Immediate local apply + optimistic UI. Show subtle banners when a reconciliation changed local state (e.g., “Moved to X on another device — undo”).
- When lossy automatic resolution occurs (rename or move overwritten), surface a non-blocking conflict card with recommended actions: keep local, keep remote, merge (for names), or manual reposition.
- For concurrent edits conflict (CRDT-synced), show merged document and highlight concurrent regions with “Show other edits” toggle.
Example
- Alice offline renames Folder A -> “Work” (ts=10). Bob offline moves Folder A under Folder B (ts=11). On sync, server orders Bob’s move later; it would not create a cycle → both ops applied. Name chosen by higher ts (Bob’s if he also renamed). If move created a cycle, server reparent Alice’s folder to root and notify.
This strategy balances availability for offline mobile users, deterministic server reconciliation, preserves invariants via ancestry checks, and provides clear, actionable UX for conflicts.
Design synchronization for a mobile chat app to minimize data transfer and support offline message composition. Cover initial bootstrap (history download), delta updates, message acknowledgements and receipts, attachment upload strategy, ordering guarantees, tombstones for deletions, and trade-offs between polling and WebSockets (including fallback).
Sample Answer
Approach overview
I’d design a lightweight sync protocol: initial history download with pagination + sync tokens for deltas, optimistic local writes for offline compose, resumable attachment uploads, and robust ack/receipt semantics to minimize data transfer and preserve ordering.
Initial bootstrap (history)
- On first login fetch last N messages per conversation with pagination (cursor/page token).
- Server returns a sync_token representing server state (e.g., monotonic revision or vector-clock summary).
- Store messages locally in encrypted DB and mark synced range.
Delta updates
- Client sends sync_token to request deltas (new messages, edits, tombstones) since token. Server returns compact patches and a new token.
- Use sequence numbers per-conversation to make patches small and idempotent.
Message acknowledgements & receipts
- Client assigns a UUID and a local timestamp when composing (optimistic UI). Send to server; server returns server_id + commit_seq.
- Delivery/read receipts are lightweight events: client posts receipt {message_server_id, status, seq}. Server stores and publishes aggregated receipts to minimize fanout.
Attachment upload
- Upload attachments to dedicated storage via chunked resumable uploads (e.g., TUS or signed URLs). Client gets attachment_id and final URL; include attachment_id in message payload.
- Allow background upload and retry tied to connectivity APIs.
Ordering guarantees
- Server assigns per-conversation monotonic sequence numbers (commit_seq) used for definite ordering; client uses local clock for rough order until server confirmation. Resolve conflicts by commit_seq; for concurrent edits use last-writer-wins or CRDT for richer merging.
Tombstones (deletions/edits)
- Represent deletions/edits as tombstone records with seq and optional redact flag. Tombstones are part of deltas so clients can apply and compact local DB later.
Polling vs WebSockets trade-offs
- WebSockets: low-latency, real-time pushes, efficient for active users; needs reconnect/backoff, mobile battery care (heartbeat tuning).
- Polling/Long-polling: simpler, reliable across proxies, predictable battery use if rate-limited.
- Fallback: prefer WebSocket; fall back to long-polling or periodic polling when connectivity or proxies block WS. Always support delta pulls via sync_token so either path is identical.
Mobile considerations
- Minimize wakeups: batch sync on network/foreground changes and use push notifications to wake only when needed.
- Persist unsent messages and attachment state; resume uploads on network restoration.
- Security: authenticate signed upload URLs, encrypt local DB, validate server tokens.
This design balances minimal data transfer, offline composition, robust ordering, and pragmatic mobile constraints.
Unlock Full Question Bank
Get access to all Mobile System Architecture and Offline-First Design interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.