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.
Telemetry ingestion at scale: propose service-layer patterns to ingest billions of mobile telemetry events per day without creating hot shards or backpressure. Discuss partitioning, batching, client-side burst handling, and how to route events to ingestion workers safely.
Sample Answer
Requirements & constraints:
- Ingest billions of mobile events/day with low latency, no hot shards, no hard backpressure to clients, exactly-once or at-least-once as required, scalable and operable.
High-level approach:
- Partitioning
- Use a composite partition key: tenant_id (or app_id) + event_type + time-bucket (e.g., YYYYMMDDHH) then apply consistent hashing with virtual nodes. This shards by tenant and time to spread load and enable time-based TTL/retention.
- Add a small random salt or sequence-bit for high-cardinality tenants to avoid hot keys when a single tenant bursts.
- Keep partition→broker map in a service discovery store (Consul/ZK) and use consistent hashing so rebalances move few partitions.
- Client-side burst handling & smoothing
- Provide an SDK that does client-side token-bucket rate limiting and local batching. Token bucket smooths bursts; tokens refilled at steady rate configured per-app quota.
- Local persistent queue (on-disk) with size limits and eviction policy (oldest-first or sample) to avoid hard failures.
- Exponential backoff and jitter for retries; circuit-breaker to stop sending when server signals overload.
- Batching & transport
- Batch by partition key and send when either size or time threshold reached (e.g., 100KB or 200ms).
- Use efficient binary proto (Protobuf/Avro) over gRPC or HTTP/2 with multiplexing to reduce connection pressure.
- Ingestion workers & routing
- Fronted by a scalable message layer (Kafka, Pulsar, or sharded ingestion API). Clients write to per-partition topics. Brokers consume and persist.
- Consumers (ingestion workers) process partitions in parallel. Use consumer groups with partition ownership; consumer rebalancing uses consistent hashing map to avoid hot reassignments.
- Ensure safe routing: include event_id and sequence_number; make uploads idempotent in downstream by deduplication (Bloom+DB or RocksDB keyed store) within retention window.
- Avoid backpressure & hot shards
- Autoscale broker and worker pools. Use rate-limited write paths per-partition; when overloaded, brokers return lightweight "try-later" with suggested backoff, SDK respects it.
- For high-volume tenants, dynamically split logical partitions (time-sliced or added salt) and update partition map; clients refresh map periodically or on 409/redirect.
- Use write amplification limits: max batch size, per-client concurrent streams limit.
- Observability & operational controls
- Per-partition metrics (ingest qps, lag, CPU). Automated alarms and autoscaling rules.
- Quota enforcement per-tenant with throttling policies and graceful degradation (sampling) for heavy tenants.
Trade-offs & notes:
- Consistent hashing + virtual nodes minimizes hot shard risk and rebalance costs, but requires map distribution and client refresh.
- Client-side buffering increases client resource use but prevents service-side overload and reduces perceived failures.
- Exactly-once end-to-end is expensive; prefer at-least-once + idempotent handlers unless strict ordering/uniqueness required.
Example flow:
Client SDK batches events by partitionKey -> apply token-bucket -> send batch to partitioned Kafka topic -> broker persists -> consumer worker processes batch (dedupe by event_id) -> write downstream (OLAP/real-time store). If partition overloaded, broker responds with redirect/split instruction; SDK updates mapping and rebalances.
This pattern scales to billions/day by horizontally partitioning across tenants/time, smoothing bursts at the edge, batching to reduce throughput cost, and using durable partitioned queues to decouple ingestion from processing.
What are the most important monitoring and observability metrics you would collect for a mobile real-time messaging service at scale? Include server-side metrics, client-side signals, and key alerts you would configure to detect user-impacting issues quickly.
Sample Answer
For a mobile real-time messaging service at scale, I’d collect metrics that map directly to user experience, capacity, and reliability — and configure alerts tied to SLIs/SLOs so we detect user impact quickly.
Server-side metrics:
- Throughput: messages/sec, API requests/sec (ingest, delivery, ack)
- Latency percentiles (p50/p95/p99) for publish, deliver, ack paths
- End-to-end delivery time (from sender client send to receiver client receive)
- Error rates: 4xx/5xx per endpoint, refused connections, dropped messages
- Connection health: active connections, new connections/sec, handshake failures
- Backpressure/backlog: queue lengths, unacked message count, retention buffer usage
- Resource utilization: CPU, memory, network, disk I/O per service & pod
- Persistence metrics: write latency, replication lag, tombstone growth
Client-side signals (mobile):
- Connect/disconnect rates, reconnect frequency, time-to-reconnect
- Local queue length (messages pending to send), send failures (network vs app)
- Receive/display latency from device timestamp vs server timestamp
- Battery/network type breakdown (cellular/Wi‑Fi) impacting performance
- SDK version and crash/error telemetry for messaging flows
Key alerts (user-impacting, with escalation tiers):
- High P99 end-to-end delivery latency > SLO threshold (urgent)
- Error rate spike: 5xx rate > X% over 5m (urgent)
- Active connections dropping > Y% vs baseline or handshake failure rate increase
- Queue backlog growth or unacked messages increasing steadily (warning → urgent)
- Resource exhaustion: CPU or memory > 85% for >5m (warning)
- Increased client reconnects or elevated client-side send failures correlated with specific region or SDK (investigate)
- Replication lag > threshold (data loss risk)
Operational notes:
- Instrument SLIs: successful delivery rate, p99 latency, connection uptime; set SLOs (e.g., 99.9% delivery within 2s).
- Use correlated dashboards combining server and client signals by region/tenant to reduce MTTR.
- Implement alerting with context (recent deploys, percentage of users affected) and automated playbooks.
As a Solutions Architect designing systems for mobile apps, how do you define "scalability" for a service that must support millions of concurrent mobile users? List concrete scalability metrics (examples: concurrent connections, requests/sec, p95/p99 latency, time-to-first-payload) and explain measurable thresholds or SLAs you would propose for a real-time messaging feature used by 10M daily active users.
Sample Answer
Scalability definition (role-appropriate): Scalability is the system’s ability to maintain functional correctness and defined performance SLAs as load (users, connections, messages) grows. For a mobile real-time messaging service serving 10M DAU, that means predictable latency, high delivery success, elastic capacity (connections/RPS), and graceful degradation under overload.
Concrete metrics and suggested thresholds / SLAs (real-time messaging, 10M DAU):
- Peak concurrent users (CCU): expected peak CCU = 10M * peak_ratio. Example assumption: 10% simultaneous => 1,000,000 concurrent connections. Design to 1.2M headroom.
- Connections/sec (new connects): support connection churn spikes e.g., 5k–50k connects/sec; scale to 100k/sec for events (app updates).
- Requests/sec / messages/sec: avg messages/sec = 10M DAU * msgs_per_user_peak; e.g., if peak = 0.1 msg/sec/user => 1,000,000 msg/sec. Design for 1.5–2× burst headroom.
- P95 / P99 end-to-end latency (send -> recipient receive): P95 ≤ 50 ms, P99 ≤ 250 ms for 90% of geographies; global worst-case SLA P99 ≤ 500 ms.
- Time-to-first-payload (connection handshake + first message): ≤ 150 ms p95, ≤ 400 ms p99.
- Delivery success rate: ≥ 99.99% (successful ack within SLA); expired/failed deliveries < 0.01%.
- Availability: 99.99% (four 9s) regional; 99.95% global multi-region.
- Error rate (5xx, timeouts): < 0.1% of requests.
- Fanout amplification / amplification factor: measure average recipients per message; provision throughput = messages/sec * amplification_factor.
- Backlog / queue depth: max tolerated queue depth per shard before shedding: set e.g., 1M messages; time-to-drain SLA after surge: < 10 minutes to return to baseline.
- Resource efficiency: connections per server (long-lived TCP/websocket): design for 50k–200k sockets per front-end depending on instance type; CPU/memory per 1k active connections baseline.
- Autoscale time: scale-up within 30–60s for sudden spikes; scale-down with hysteresis to avoid thrashing.
- Durability / persistence SLA (for stored messages): persisted and ACKed within 2s p95; retention SLA for offline delivery as agreed (e.g., 7 days).
Why these thresholds:
- Mobile users expect near-instant messaging; p95 targets ensure perceived real-time behavior, p99 accounts for tail latency.
- High CCU and message/sec targets prevent under-provisioning—10M DAU implies large concurrency and bursts.
- Availability and delivery rates reflect business impact (user retention, SLAs for enterprise customers).
How to measure and enforce:
- Synthetic traffic and chaos testing for target CCU and bursts.
- Real-time metrics: per-shard messages/sec, connection counts, CPU/memory, queue depth, p95/p99 latencies, error rates.
- Autoscaling policies tied to meaningful signals (queue depth, CPU, connection saturation, latency).
- Capacity planning: model fanout, compression, batching, and protobuf sizes to convert messages/sec to bandwidth and instance counts.
- Graceful degradation: prioritize control messages, rate-limit non-critical features, employ back-pressure and shedding.
Example capacity calc (simple):
- If peak CCU = 1,000,000 and avg messages/sec/user_peak = 0.1 → messages/sec = 100k. If average fanout = 10 → 1,000k deliveries/sec. With 100k deliveries/sec per region per 100 instances → need ~1,000 instances (adjust for message size, protocol overhead, geo distribution).
These metrics allow you to translate business requirements into concrete architecture choices (connection tier, pub/sub brokers, sharding, region placement, CDN edge relay, autoscaling rules) and measurable SLAs to discuss with stakeholders.
Discuss stateful vs stateless real-time servers. For a stateful architecture that stores per-connection session data (presence, subscriptions), describe how you'd design failover, session replication, and seamless reconnect behavior so users do not lose important session state during server crashes or rolling upgrades.
Sample Answer
Requirements:
- Preserve per-connection session state (presence, subscriptions, last-ack’d message, sequence numbers) across server crashes and rolling upgrades
- Low reconnect latency (<1s perceived outage), strong consistency for presence where required, eventual consistency acceptable for non-critical metadata
- Scale to many concurrent connections
High-level design:
- Keep real-time frontends (WebSocket/TCP) stateless regarding durable session state; persist session state in a highly-available session store with fast read/write. Use in-memory replica on the active host for performance.
- Components: Load balancer with consistent hashing / sticky affinity token, Real-time servers (connection handlers), Session store (Redis Cluster with AOF + clustering OR CockroachDB for strong consistency), Replication/coordination layer (Raft/etcd for leader election or Redis primary-replica with Sentinel), Message broker (Kafka) for durable event stream.
Session lifecycle & replication:
- On connect, client presents a resume token (session ID + last-seq). If new, create session record in session-store; assign a short-lived lease owned by the handling server.
- Active server keeps session hot-copy in local memory for latency. All state changes are persisted immediately (write-through) to session-store and appended to per-session event stream in the broker. Optionally use Redis streams or Kafka per-session partitioning.
- Replication: session-store runs in clustered mode (multi-AZ Redis Cluster or CockroachDB) so writes are durable and accessible to any server. For sub-100ms reads, local server uses a write-behind cache but guarantees persistence before acknowledging critical ops.
Failover & seamless reconnect:
- Lease/heartbeat: server renews a short lease in session-store every N seconds. If lease expires, other servers may claim session.
- Client reconnect flow: client reconnects to load balancer; LB routes by session ID via consistent-hash cookie to likely previous server or any server that can claim lease. New server reads persisted session and event-stream, replays missed events up to last-ack using sequence numbers, restores subscriptions and presence.
- Resume tokens and sequence numbers ensure idempotent replay; server sends only events with seq > client-last-seq.
- Presence: for strong presence, use ephemeral keys with TTL in session-store and a central presence topic; on handover, new server emits join/leave events only when lease transitions occur to avoid flapping.
- Rolling upgrades: perform graceful drain—stop accepting new connections, wait for in-flight ops, persist final state, transfer lease, then close connections. Use canarying and short TTL leases to limit risk.
Consistency and trade-offs:
- Trade-off: write-through persistence adds latency; mitigate with batching non-critical updates and local cache for reads. Use stronger consistency (CockroachDB / Redis with WATCH for CAS) for presence and order-sensitive state; use eventual-consistency CRDTs for multi-subscriber lists if conflict tolerance helps scale.
- For massive scale, shard sessions by consistent hash to reduce cross-node contention; use Kafka for durable replay and replay speed.
Operational notes:
- Monitor lease expirations, replication lag, and client resume failures.
- Test chaos scenarios (kill server, network partitions) and measure recovery time objective (RTO) and message duplication/ordering guarantees.
This design guarantees fast reconnects, durable session state, and controlled trade-offs between latency and consistency.
System design: Design a push notification platform to reliably deliver notifications to 10M devices with peak fan-out of 500k messages/sec. Requirements: high delivery rate, integration with APNs/FCM, per-user throttling, deduplication, analytics per message, and SLA of 99.95% delivery within 30s if device is online. Describe the architecture, components, failure modes, and scaling strategies.
Sample Answer
Requirements (clarify):
- Deliver to 10M devices, peak fan-out 500k msg/s
- Integrate with APNs/FCM
- Per-user throttling, deduplication, per-message analytics
- SLA: 99.95% delivery within 30s if device is online
High-level architecture:
- Ingress API / Message Broker: REST/gRPC endpoints accept notifications from apps/services -> validate and enqueue to a durable distributed queue (Kafka or Pulsar) partitioned by user-id.
- Fan-out workers: Consumer pool reads messages, resolves recipients, applies per-user throttling & dedup rules, enriches with metadata, writes analytics events, and batches per push provider.
- Provider adapters: Stateless, horizontally scalable adapters for APNs and FCM that handle provider-specific protocols, token management, backoff, and rate limits. Use HTTP/2 (APNs) and XMPP/HTTPv1 for FCM, with connection pools.
- Delivery cache & dedupe store: Redis (or RocksDB) per region storing recent message IDs/user-message fingerprints with TTL for deduplication.
- Throttling service: Central policy engine (Redis/Leaky-bucket) per user to enforce rates across workers.
- Analytics pipeline: Events emitted to Kafka -> real-time processors (Flink) -> OLAP store for dashboards.
- Observability & SLA monitor: Track delivery latency, retries, provider responses; alert when SLA risk.
- Multi-region deployment with geo-routing and cross-region replication.
Key behaviors and scaling:
- Partition by user-id to localize fan-out; scale consumers to match partitions.
- Batch multiple notifications to same provider/connection to reduce overhead.
- Horizontal scale provider adapters; use backpressure on queues when providers are throttled.
- Use async retries with exponential backoff and capped attempts; mark device-state (online/offline) via last-active; queue penalties for offline.
Failure modes and mitigations:
- Provider outages (APNs/FCM down): queue persists messages; adapter circuit-breaker; divert analytics to indicate provider issues; notify clients with degraded SLA.
- Broker overload: autoscale brokers/partitions; use retention and throttling on ingress; shed noncritical load.
- Worker crashes: consumer groups rebalance; idempotent processing and dedupe store prevent duplicates.
- Network partition: retry with backoff; cross-region failover using replicated queues.
- Token expirations/auth failures: rotate credentials automatically; alert on high auth-error rates.
Trade-offs:
- Strong consistency vs throughput: eventual delivery state with at-least-once semantics and dedupe chosen for throughput.
- Cost vs latency: aggressive batching reduces cost but increases latency; tune to meet 30s SLA.
SLA strategies:
- Prioritize online devices: route high confidence deliverables with higher worker priority.
- Fast-path for time-sensitive messages: dedicated low-latency pipeline with smaller batches.
- SLAs enforced by monitoring, autoscaling, and provider-adaptive backoff to keep 99.95% within 30s.
Security & compliance:
- Encrypt payloads at rest/in-transit, RBAC for APIs, audit logs, PII redaction in analytics.
This design provides scalable fan-out, per-user controls, deduplication, provider integration, and observability to meet the SLA with clear failure mitigation and scaling strategies.
Unlock Full Question Bank
Get access to all 43 Mobile System Architecture and Offline-First Design interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.