Design an Activity Recording and Social Feed Service
System DesignModel answerLast updated
Build a mobile service that captures GPS workouts offline, uploads them reliably, and powers a social feed of followers' activities.
You're designing a mobile application for endurance athletes. The app records workouts—running, cycling, and similar activities—using the device's GPS sensor. During a workout, the athlete sees real-time metrics: elapsed time, distance covered, and current pace. When they finish, they save the workout with a name and activity type, and it becomes part of their profile, complete with a map trace and summary stats.
Athletes can follow each other. Each athlete has a personal feed showing recent workouts from the people they follow, where they can react with kudos or post comments.
Your task is to design the end-to-end system: how GPS data flows from the phone to permanent storage, how workouts are stored and displayed, and how the social feed is built and served.
What's In Scope
- Recording workflow: start, pause, resume, stop
- Live statistics displayed on the device during the workout
- Saving and uploading a completed workout
- An activity detail page showing the route map and summary metrics
- A profile page listing an athlete's workout history
- Following other athletes
- A home feed displaying recent workouts from followed athletes
- Kudos (reactions) and comments on workouts
What's Out of Scope
- Performance leaderboards for route segments
- Route planning or navigation
- Group features like clubs
- Direct messaging between athletes
- Integration with wearable devices
- Premium subscriptions
Key Constraints
-
Offline-first recording: Network connectivity during a workout is unpredictable. The recording must work entirely offline, and the app must reliably upload completed workouts even if it crashes, is closed, or the device restarts.
-
Idempotent uploads: Uploads may be retried multiple times due to network failures. The system must guarantee that retries never create duplicate workouts.
-
Privacy enforcement: Each workout has a visibility setting (e.g., public, followers-only, private). No read operation may expose a workout to someone the setting excludes.
-
Scale assumptions: Before diving into implementation, establish targets for daily active users, workouts recorded per day, and feed requests per second. Consider that usage is bursty—weekend mornings see peak activity.
Questions to Clarify
- What scale should the design target? How many daily active athletes, workouts uploaded per day, and feed page loads?
- Is there a live-tracking feature where followers see an athlete's position during the workout, or is sharing only after the workout is saved?
- What visibility options exist? Should the system hide the start/end of routes near an athlete's home address?
- How long should raw GPS traces be retained, and at what resolution (one point per second, per meter, etc.)?
- Should the feed be strictly chronological, or can it use ranking signals?
Hints
Hint 1
The recording layer lives entirely on the device. Design a local storage strategy that survives app termination and ensures exactly-once upload semantics.
Hint 2
GPS traces can be huge—thousands of points per workout. Separate raw location data from the derived summary statistics that most views actually need.
Hint 3
For the social feed, choose between fan-out-on-write and fan-out-on-read. Consider what happens when an athlete has hundreds of thousands of followers.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Functional and Non-Functional Requirements
Functional:
- Record GPS workouts offline with start/pause/resume/stop
- Display live metrics during recording
- Save workouts with metadata (name, sport type, visibility)
- Upload workouts reliably with exactly-once semantics
- Display workout detail pages with maps and statistics
- Support following relationships between athletes
- Generate a personal feed of followed athletes' recent workouts
- Allow kudos and comments on workouts
Non-functional:
- Recording must work without network connectivity
- Upload must survive app crashes and device restarts
- No duplicate workouts from retried uploads
- Privacy settings enforced on every read
- Low latency for feed loads (< 500ms p95)
- High availability for reads; eventual consistency acceptable for writes
Scale Estimation
Assume:
- 50 million daily active athletes
- 10 million workouts uploaded per day
- Average workout: 30 minutes, 1 GPS point per 5 seconds = 360 points
- Average 50 followers per athlete; 100 feed loads per active user per day
Storage:
- GPS data: 10M workouts × 360 points × 50 bytes ≈ 180 GB/day raw
- Activity metadata: 10M × 5 KB ≈ 50 GB/day
- Total new data per day: ~230 GB; ~85 TB/year
Traffic:
- Workout uploads: 10M / 86400 ≈ 115 uploads/sec (avg), 5× at peak = 575/sec
- Feed loads: 50M × 100 / 86400 ≈ 58K reads/sec (avg), 10× at peak = 580K/sec
High-Level Architecture
Client (Mobile App):
- Local SQLite database for in-progress and completed workouts
- Background sync service with exponential backoff retry
- GPS sensor interface with battery-efficient sampling
Backend Services:
- Upload API: accepts workout payloads, enforces idempotency
- Activity Service: stores and retrieves workout metadata and statistics
- GPS Storage: handles raw track data (separate from metadata)
- Feed Service: generates and serves personalized feeds
- Graph Service: manages follow relationships
- Engagement Service: handles kudos and comments
Data Stores:
- Relational DB (PostgreSQL): users, activities metadata, follows, kudos, comments
- Object Storage (S3): raw GPS tracks as gzipped JSON or protobuf
- Cache (Redis): feed timelines, activity summaries, hot metadata
- CDN: serves rendered map tiles and activity images
Recording and Upload Path
On-Device Recording
- Start workout: app creates a local record with a client-generated UUID (idempotency key), sport type, and start timestamp
- GPS sampling: collect lat/lon/elevation/timestamp every 5 seconds, append to local buffer
- Live stats: compute distance (haversine between points), pace, elapsed time in-app
- Pause/resume: write pause/resume events to the local record; exclude paused intervals from statistics
- Stop and save: finalize the workout, compute summary stats (total distance, duration, average pace, elevation gain), assign visibility setting
All data lives in the device's SQLite database. No network required.
Upload Path
- Background sync: a persistent WorkManager job (Android) or BackgroundTasks (iOS) tries to upload all unsynced workouts
- Payload: client sends activity metadata (UUID, name, sport, stats, visibility) and raw GPS track (compressed)
- Idempotency: Upload API checks if an activity with this UUID already exists; if yes, return 200 (no-op); if no, proceed
- Persist metadata: write activity record to PostgreSQL with athlete_id, UUID, timestamp, stats, visibility
- Persist GPS track: write raw points to S3 at path
{athlete_id}/{activity_uuid}.json.gz - Mark synced: API returns success; client marks the local record as uploaded
- Retry logic: if upload fails, exponential backoff (1s, 2s, 4s, ..., max 1 hour) until success
The UUID guarantees that retries are safe—duplicate requests are ignored.
Data Model
Users table:
user_id (PK), username, email, profile_photo_url, created_at
Activities table:
activity_id (PK), user_id (FK), client_uuid (unique), activity_name, sport_type,
start_time, duration_sec, distance_m, avg_pace_sec_per_km, elevation_gain_m,
visibility (enum: public, followers, private), gps_track_url (S3 path), created_at
Follows table:
follower_id (FK users), followee_id (FK users), created_at
PRIMARY KEY (follower_id, followee_id)
Kudos table:
kudo_id (PK), activity_id (FK), user_id (FK), created_at
UNIQUE (activity_id, user_id)
Comments table:
comment_id (PK), activity_id (FK), user_id (FK), text, created_at
GPS data: stored in S3 as {user_id}/{activity_uuid}.json.gz, containing array of [{lat, lon, ele, ts}, ...]. Accessed only when rendering the map on the activity detail page.
Feed Architecture
Fan-Out on Write (Chosen Approach)
When an athlete uploads a new activity:
- Activity Service writes the activity record to PostgreSQL
- Feed Worker (async job) queries the Follows table for all followers of this athlete
- For each follower, append activity_id to that follower's feed timeline in Redis (sorted set, scored by timestamp)
- Trim each timeline to the most recent 500 activities to bound memory
Reading the feed:
- Client requests feed for user X
- Feed Service reads user X's timeline from Redis (sorted set range query)
- Batch-fetch activity metadata from PostgreSQL (with visibility filter)
- Hydrate with athlete names, profile photos
- Return paginated result (e.g., 20 activities)
Advantages:
- Fast reads: O(1) Redis lookup + single batch DB query
- Simple consistency: when you load your feed, it's already built
Handling high-follower athletes:
- If an athlete has > 100K followers, skip fan-out-on-write for them
- Instead, mark them as "celebrity" and fan-out-on-read: when a user loads their feed, merge in recent activities from followed celebrities via a separate query
- This avoids writing millions of timeline entries for one activity
Alternative: Fan-Out on Read
Query all followed athletes' recent activities at read time. Slower (requires join or scatter-gather), but simpler for uneven follow distributions. Not chosen here due to read latency requirements at scale.
Privacy Enforcement
Every read path checks visibility:
- Feed query: filter out activities where
visibility = 'private'OR (visibility = 'followers'AND viewer is not a follower) - Activity detail page: before serving, verify viewer is allowed per the visibility rule; return 403 if not
- Profile page: apply the same filter when listing an athlete's history
Implementation:
- In SQL:
WHERE (visibility = 'public') OR (visibility = 'followers' AND viewer_id IN (SELECT follower_id FROM follows WHERE followee_id = activity.user_id)) OR (user_id = viewer_id) - Cache visibility checks for the viewer's follow graph in Redis to avoid repeated joins
Additional Considerations
Map rendering: Pre-generate static map images (via Mapbox Static API or similar) at upload time and cache in CDN. Serve interactive maps client-side with the full GPS track fetched on demand.
Engagement: Kudos and comments are lightweight writes to their respective tables. Invalidate cached activity detail pages when new kudos/comments arrive. Optionally, fan out notifications to the activity owner.
Monitoring:
- Upload success rate, retry counts, time-to-upload p50/p99
- Feed load latency, cache hit rate
- Privacy filter correctness (audit logs for 403 responses)
- Storage growth rate for GPS data
Failure modes:
- S3 upload fails but metadata succeeds: retry GPS upload separately; activity page shows "processing" until GPS is available
- Redis timeline eviction: fall back to database query (slower but correct)
- Celebrity athlete creates write hotspot: rate-limit fan-out workers; use fan-out-on-read hybrid
Summary
The design separates concerns cleanly: the device owns recording and guarantees upload, the backend stores raw GPS separately from summary data, and the feed is pre-built for fast reads while handling high-follower edge cases. Idempotency keys eliminate duplicates, and privacy checks are enforced at every read boundary. The architecture scales horizontally by sharding users and caching aggressively.