System Design


1. Approaching Design Questions

Q: How do you approach a mobile system design question?

Follow this structure:

  1. Clarify Requirements (2-3 min)

    • Functional: What features?
    • Non-functional: Offline? Scale? Battery?
    • Constraints: Platform? API limitations?
  2. High-Level Design (5-10 min)

    • Architecture diagram
    • Main components
    • Data flow
  3. Deep Dive (10-15 min)

    • Specific component design
    • Data models
    • Key algorithms
  4. Trade-offs & Extensions (5 min)

    • What you'd do differently
    • Scalability considerations
    • Edge cases

Q: What non-functional requirements matter for mobile?

Requirement Considerations
Offline Support Local caching, sync strategy, conflict resolution
Performance Startup time, scroll performance, memory usage
Battery Network batching, background work limits
Bandwidth Compression, pagination, delta updates
Security Data encryption, secure communication

2. News Feed / Social Feed

Q: Design a news feed like Twitter or Instagram.

Key Components:

  • Feed Repository: Single source of truth, coordinates remote/local
  • Paging: Infinite scroll with Paging 3
  • Caching: Room database as cache
  • Real-time: WebSocket or polling for new items

Architecture:

UI (LazyColumn) → ViewModel → Repository
                                 ├── RemoteMediator → API
                                 └── PagingSource → Room

Key Decisions:

  • Cursor vs Offset pagination: Cursor is stable (items don't shift)
  • Cache invalidation: Time-based or on pull-to-refresh
  • Optimistic updates: Show locally before server confirms
  • Image loading: Preload next page images

Trade-offs:

  • More caching = better UX, more storage/complexity
  • WebSocket = real-time, more battery/complexity

3. Messaging App

Q: Design a chat/messaging app like WhatsApp.

Key Components:

  • Message Repository: Handles send/receive/sync
  • WebSocket/XMPP: Real-time message delivery
  • Local Database: All messages stored locally
  • Background Service: Receive messages when app closed

Data Model:

Conversation: id, participants, lastMessage, unreadCount
Message: id, conversationId, sender, content, timestamp, status

Key Decisions:

  • Delivery guarantees: At-least-once with deduplication
  • Message status: Sent → Delivered → Read
  • Offline messages: Queue locally, sync when online
  • End-to-end encryption: Signal Protocol pattern

Sync Strategy:

  1. On app start, fetch missed messages since last sync
  2. WebSocket for real-time during session
  3. Push notification triggers sync when app closed

4. Image Loading Library

Q: Design an image loading library like Coil or Glide.

Key Components:

  • Request Queue: Prioritize visible images
  • Memory Cache: LruCache for decoded bitmaps
  • Disk Cache: DiskLruCache for downloaded files
  • Decoder: BitmapFactory with sampling
  • Transformations: Resize, crop, rounded corners

Flow:

Request → Memory Cache? → Disk Cache? → Network
    ↓           ↓              ↓            ↓
   Done     Decode         Decode       Download
                ↓              ↓            ↓
          Cache in         Cache in    Cache both
           Memory           Memory

Key Decisions:

  • Memory cache size: ~1/8 of available memory
  • Disk cache size: ~50-250MB configurable
  • Request cancellation: Cancel when view recycled
  • Placeholder/Error: Immediate feedback

Optimizations:

  • Downsampling: Load at target size, not full resolution
  • Request coalescing: Same URL = single request
  • Preloading: Load upcoming images in list

5. Offline-First App

Q: How do you design an offline-first application?

Principles:

  1. Local database is source of truth
  2. All operations work offline
  3. Sync when connectivity available
  4. Handle conflicts gracefully

Architecture:

UI → ViewModel → Repository (SSOT)
                      ↓
                 Local DB ←→ SyncManager → API

Sync Strategies:

Strategy Approach Use Case
Last-write-wins Latest timestamp wins Simple, some data loss ok
Server-wins Server always correct Authoritative server data
Client-wins Client always correct User edits are precious
Manual resolution User chooses Collaborative editing
CRDT Automatic merge Complex, no conflicts

Key Decisions:

  • Change tracking: Track local modifications since last sync
  • Conflict detection: Compare versions/timestamps
  • Partial sync: Only sync changed data
  • Background sync: WorkManager with network constraint

6. Video Streaming

Q: Design a video streaming app like YouTube/Netflix.

Key Components:

  • Player: ExoPlayer with adaptive streaming
  • Caching: Pre-cache upcoming segments
  • Download: Background download for offline
  • CDN: Multiple quality levels, nearby servers

Streaming Protocol:

  • HLS/DASH: Adaptive bitrate streaming
  • Segments downloaded progressively
  • Quality adjusts to network conditions

Key Decisions:

  • Buffer size: Balance memory vs smooth playback
  • Quality selection: Auto (ABR) or user choice
  • Preloading: Start loading next video early
  • Resume position: Save and restore playback position

Offline Viewing:

  • Download in background with WorkManager
  • Encrypt downloaded content (DRM)
  • Track download progress, allow pause/resume
  • Expire after license period

7. Location-Based App

Q: Design a ride-sharing or delivery app.

Key Components:

  • Location Service: Foreground service with updates
  • Map Integration: Google Maps or Mapbox
  • Real-time Updates: Driver location via WebSocket
  • Geofencing: Trigger events at locations

Battery Considerations:

  • Use significant location change (not continuous)
  • Batch location updates
  • Reduce frequency when stationary
  • Foreground service required for background location

Key Decisions:

  • Location accuracy: Fused Location Provider, balance power/accuracy
  • Update frequency: Every 5-10 seconds active, less in background
  • Predictive routing: Update ETA based on traffic
  • Offline maps: Cache tiles for core areas

8. E-Commerce App

Q: Design a shopping app like Amazon.

Key Components:

  • Product Catalog: Search, browse, filter
  • Cart: Local + synced
  • Checkout: Payment integration
  • Order Tracking: Status updates

Architecture Decisions:

  • Search: Debounce input, paginate results
  • Cart: Optimistic local updates, sync to server
  • Product Cache: Cache popular items, invalidate on changes
  • Deep Linking: Open product from notification/share

Key Features:

  • Recently Viewed: Local history
  • Recommendations: Personalized from server
  • Wishlist: Local with sync
  • Reviews: Lazy load, paginate

9. Design Patterns for Mobile

Q: What patterns come up repeatedly in mobile system design?

Pattern Problem Solution
Repository Coordinate data sources Single source of truth
Cache-aside Reduce network calls Check cache, fallback to network
Retry with backoff Handle transient failures Exponential backoff
Optimistic update Responsive UI Update local, sync later
Event sourcing Audit, undo, offline Store events, derive state
CQRS Different read/write needs Separate models

Quick Reference

Scenario Key Considerations
News Feed Paging, caching, cursor pagination, image preloading
Messaging WebSocket, local DB, delivery status, encryption
Image Loading Memory/disk cache, cancellation, downsampling
Offline-First Local SSOT, sync strategy, conflict resolution
Video Adaptive streaming, buffering, DRM, background download
Location Battery, foreground service, update frequency
E-Commerce Search, cart sync, deep linking, recommendations

results matching ""

    No results matching ""