Workout Tracker Backend: Live Routes, Period Rankings, Social Boards
System DesignModel answerLast updated
Design the backend for a workout-tracking app with real-time route sharing to followers, top-workout queries over date ranges, and ranked boards of aggregated user stats.
You are asked to design the backend for a mobile app where people record runs and rides with GPS, and share them with the people who follow them.
The product must support three capabilities:
- Live route sharing. While a user is exercising, their followers can open the app and watch the route being drawn in near real time.
- Best workouts in a time window. A user can ask for the top workouts by a chosen metric (for example distance) within a date range, across different scopes: their own workouts, workouts by people they follow, or everyone.
- Ranked boards. Weekly, monthly and all-time rankings per sport and metric, viewable globally or restricted to people the user follows, including a "where do I stand" view.
What to cover in your answer
- Clarifying questions, plus the functional and non-functional requirements you would assume.
- A rough capacity estimate (users, concurrent workouts, write rate, storage).
- API sketch and data model, including which store holds what.
- A high-level architecture, then deeper dives on each of the three capabilities.
- Correctness issues: retries, duplicate uploads, edited or deleted workouts, late offline uploads, time zones, cheating.
- Privacy handling (visibility settings, hidden zones near home).
- Trade-offs, failure modes, and how you would validate the design with tests and metrics.
Hints
Hint 1
The three capabilities have very different shapes: a high-rate write stream with few readers, a range query over history, and continuously updated per-user aggregates. Consider a different storage and freshness model for each.
Hint 2
For best single workouts in a date range, think about bucketing by day and merging bounded top-K lists. Ask whether the same trick still works when the ranking is based on a per-user sum.
Hint 3
For ranked boards, consider an in-memory sorted structure per period, and think about idempotent updates, edits and deletes applied as deltas, assigning the period by workout start time in the user's time zone, and a periodic rebuild from the source of truth.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Framing
This is really three workloads in one product, and a strong answer treats them separately:
- Live routes: write-heavy streaming, very few readers per stream, freshness in seconds.
- Top workouts in a range: ranking over history, where the unit being ranked is a single workout.
- Boards: ranking of per-user aggregates (for example total weekly distance), which behaves differently from ranking single workouts.
Putting all three into one SQL table with ORDER BY is the classic weak answer.
2. Requirements and scale
Functional: record a workout with GPS points; followers watch an in-progress route; query top workouts by scope, metric and range; weekly, monthly and all-time boards per sport and metric, globally or among followees.
Non-functional: live lag under about 5 s; board reads under 100 ms; boards may be eventually consistent by a few seconds; no acknowledged GPS point is lost; privacy rules enforced.
Back-of-envelope (assumed): 50M users, 5M daily active, 500K concurrent workouts at peak. One point per 5 s gives about 100K points/s. Clients batch every 15 s, so roughly 33K write requests/s. About 10M finished workouts per day, each around 2K points, about 20 KB compressed, so about 200 GB/day of tracks. Average 100 followers, but some accounts have over 1M.
3. API and data model
POST /activitiesto start,POST /activities/{id}/pointswith{seq, points[]},POST /activities/{id}/finish.WS /live/{id}for the point stream;GET /feed/livefor followees currently active.GET /activities/top?scope=&type=&metric=&from=&to=&limit=.GET /leaderboards/{type}/{metric}/{period}?scope=&around=me.
The sequence number makes batch uploads idempotent, so flaky mobile clients can retry safely.
| Store | Content |
|---|---|
| Sharded relational DB | users, follow edges (indexed both ways), workout rows (metrics, visibility, status, pointer to track) |
| Object store | finished track as a compressed polyline |
| Redis | recent live points with TTL, set of active workouts per user, sorted sets for rankings |
| Kafka | point stream and workout lifecycle events (started, finished, edited, deleted) |
4. Architecture
- Ingest service validates, dedupes on
(activity_id, seq), writes to Kafka partitioned by activity ID (ordering per workout), and acks only after the durable write. - Live consumer appends to the workout's recent-points list and publishes on a per-workout pub/sub channel.
- WebSocket gateway: a viewer gets a snapshot, then subscribes. We push only to people actually watching (fan-out on read), not to all followers.
- Finish pipeline stores the full track, computes the summary, writes the DB row and emits a
finishedevent that ranking consumers use. - Notifications ("X started a run") use fan-out on write for normal accounts and async batching for very large ones.
5. Deep dive: live routes
- Privacy at ingest: drop points inside the user's hidden zones before they reach any live channel; check visibility again on subscribe.
- Discovery: compute "who I follow is live" on read by intersecting followees with the active set. For heavy followers, keep a per-user live set maintained on write, only for normal accounts.
- Sizing: about 1M concurrent viewers at 50K connections per node is roughly 20 gateway nodes. Nodes are stateless; on failure clients reconnect and re-snapshot.
6. Deep dive: top workouts in a range
- Personal scope: index on
(user_id, type, start_ts). A user has at most thousands of workouts, so filter and sort is cheap. - Global scope: one sorted set per day, type and metric, trimmed to top K. Each workout belongs to exactly one day, so merging the per-day top-K lists across the range gives the exact global top K. Cost is O(days x K); add weekly and monthly buckets for long ranges.
- Following scope: pull followees' workouts in the range from the DB (bounded by follow count) and rank them.
7. Deep dive: boards (the subtle part)
Boards rank per-user sums, and the per-day top-K merge does not work for sums: someone ranked 11th each day can be first for the week. So keep a full sorted set per period, for example lb:run:distance:week:2025-W15.
- On each finished workout,
ZINCRBY. 50M members is a few GB, acceptable; shard by sport and period. - "My rank" and "around me" via reverse-rank and range commands in O(log N).
- Following scope: batch-fetch scores for the followee IDs (cap around 1-2K), then sort.
- Idempotency: record processed workout IDs per period. Edits apply a delta (subtract old, add new); deletes subtract. Redis is a derived view; the DB is the source of truth.
- Period assignment: use the workout's start time in the user's time zone, not processing time, so late offline uploads land in the right past period.
- Anti-cheat: flag impossible speeds (for example a car trip logged as a run) before counting.
- Reconciliation: a nightly job recomputes boards from the DB, diffs against Redis and repairs drift; it doubles as the rebuild path after data loss.
8. Trade-offs
- Redis vs DB
ORDER BY: Redis gives O(log N) ranks but costs memory and is eventually consistent; a DB rank over 50M rows scans too much. - Fan-out on read vs write: read-time is cheaper for celebrities and for live streams; write-time is fine for normal accounts and notifications. A hybrid is typical.
- Exact vs approximate: per-day top-K merging is exact for single workouts; for sums, exactness needs the full set.
9. Failure modes and validation
- Kafka or consumer lag: viewers see stale routes; alert on end-to-end lag p95.
- Redis loss: rebuild boards from the DB; serve the last snapshot meanwhile.
- Duplicate or out-of-order batches: dedupe by sequence; test with replayed and shuffled batches.
- Tests: property test that incremental board updates equal a from-scratch recompute; edit/delete delta tests; time-zone boundary tests (workout at 23:59 local on a period edge); privacy tests confirming no hidden-zone points ever reach a subscriber.
- Metrics: live lag, board read latency, drift found by reconciliation, dropped-point rate.
10. Common mistakes
- Using one SQL table and
ORDER BYfor everything. - Merging per-day top-K for summed boards.
- Pushing live updates to every follower instead of only active viewers.
- Bucketing by processing time rather than workout start time.
- Forgetting idempotency, edits, deletes and privacy zones.