Design Instagram (Mobile)
Concepts Utilized: MVVM Architecture, Image Caching (LRU), Pagination, Background Upload, Push Notifications, Camera Integration, Video Compression, Offline Queue, Content Prefetching
This document covers the mobile architecture for a photo-sharing application with an infinite scrolling feed, media upload functionality, and camera integration.
Features
| Feature | Description |
|---|---|
| Feed | Infinite scroll with paginated content loading |
| Photo/video capture | Native camera integration with filters |
| Stories | Ephemeral content with 24-hour expiration |
| Direct messaging | Private conversations between users |
| Push notifications | Alerts for likes, comments, and follows |
Architecture
Feed Implementation
Pagination
Cursor-based pagination prevents duplicate content when new posts are added during scrolling.
Implementation approach: The ViewModel maintains a cursor (from the last API response) and a loading flag. The loadMore method checks the loading flag to prevent duplicate requests, sets it to true, then fetches posts using the current cursor. On completion, append new posts to the existing list, update the cursor for the next page, and reset the loading flag.
Image Caching
A two-tier cache (memory and disk) reduces network requests and improves scroll performance.
Implementation approach: Check memory cache first (NSCache or similar). If not found, check disk cache and promote to memory cache if found. If not in disk cache, fetch from network and store in both caches. This hierarchy provides fast access for recently viewed images while persisting images across app sessions.
Photo Upload
Background Upload
Uploads persist across application state changes using background tasks.
Implementation approach:
- Save the image to local storage first
- Create a pending upload record in the database with pending status
- Request background execution time from the OS
- Start the upload; when complete, end the background task
This pattern ensures uploads continue even if the user navigates away from the app, and pending uploads survive app termination for retry when the app relaunches.
Technical Constraints
| Constraint | Impact | Mitigation |
|---|---|---|
| Memory limits | Loading high-resolution images can trigger OS termination | Downscale images to display size before rendering |
| Battery consumption | Background uploads consume significant power | Batch uploads and respect low-power mode |
| Network variability | Uploads fail on unstable connections | Implement retry logic with exponential backoff |
| Storage limits | Excessive caching causes user-initiated app deletion | Implement LRU eviction with configurable size limits |