Workout Tracking System with Live Trails and Leaderboards
Medium · System Design · Software Engineer · Onsite
Prompt
Design an endurance workout tracking platform (for sports such as running, cycling, and hiking) without assuming any company-specific proprietary infrastructure. The product must support three core capabilities:
- Live route sharing for followers: When an athlete opts into live tracking (for example, Maya beginning a Monday morning run
act_9d4ain Sydney), approved followers can view her in-progress GPS path updating on a map in near real time while respecting location privacy boundaries. - Top individual workouts over arbitrary date windows: Athletes and coaches can query the best
ksingle activities (by distance, moving time, or elevation gain) across any[from_date, to_date]range—such as the10longest runs in Canada between2026-04-10and2026-06-05. - Cumulative period leaderboards: Users can view summed athlete standings across calendar periods (weekly, monthly, yearly) for global, country, club, or followed-athlete scopes, including tie-consistent personal rank lookups (for example, Liam viewing
#31,408at24.0 kmon"Weekly Running Distance — Canada").
State your product, scale, latency, reliability, and privacy assumptions explicitly, explain the trade-offs behind each architectural choice, and show how you would validate correctness with concrete traces, tests, and production metrics.
Scope & Expectations
- Explicit assumptions & capacity math: Establish realistic traffic, storage, freshness, timezone, and privacy constraints before choosing protocols and databases.
- End-to-end APIs & data layout: Separate high-rate ephemeral live GPS streaming from durable workout processing, arbitrary date-window top-k indexing, and cumulative leaderboard updates.
- Correctness & privacy invariants: Prevent double-counting under mobile retries or stream replays, handle deletions and ties accurately, and enforce follower/block/privacy-zone rules immediately.
- Validation & operational readiness: Demonstrate how example walk-throughs, automated property/chaos tests, and live reconciliation jobs prove end-to-end reliability.
Step-by-step walkthrough
Clarify requirements, concrete examples, and assumptions
This design combines three very different access patterns—live GPS paths for followers, best single workouts over an arbitrary date window, and cumulative athlete leaderboards—using standard, vendor-neutral building blocks. Grounding our discussion in three concrete user scenarios makes every requirement and edge case sharp from minute one:
- Live trail: Maya in Sydney starts a 12 km morning run at
06:30Monday local time (19:30Sunday UTC) and opts into live sharing. Two of her 140 approved followers open the app and see her route drawn on a map with a dot advancing every few seconds—except for the first 250 meters inside her home privacy zone. - Top activities by time range: a running coach queries "top 10 longest single runs in Canada between
2026-04-10and2026-06-05", or Noah queries "my 10 highest-elevation bike rides between2025-03-01and2025-09-30". - Leaderboard: Liam opens "Weekly Running Distance — Canada (
2026-W19)" (or "People I Follow"), seeing the top 50 total distances plus his own rank (#31,408at24.0 km)—even if he ties with another runner at24,000 m.
Functional requirements
- Phones and GPS watches record workouts (sport, 1 Hz GPS coordinates, altitude, heart rate) offline-first and upload the complete track file when finished.
- Live trails: when an athlete opts in, approved followers can see who among the people they follow is currently active and watch that trail update in near real time.
- Top activities (
top-ksingle workouts): return the bestk(k <= 100) individual activities by distance, moving time, or elevation gain for one sport over any[from_date, to_date]window, scoped touser:{id},country:{code}, orglobal. - Leaderboards (summed user totals): rank athletes by cumulative distance, moving time, or elevation gain across standard calendar periods (
week,month,year) forglobal,country,club, orfollowing. - Social & privacy controls: follow/unfollow, private accounts requiring follow approval, user blocks, circular home/work privacy zones, and leaderboard opt-out.
Non-functional requirements
- Live trail latency: under 10 seconds at p95 from GPS satellite fix on the phone to follower's map.
- Zero lost workouts & exact counting: flaky mobile networks must never lose a workout or double-count its kilometers on a leaderboard (idempotency—repeating the same request produces the exact same stored result as running it once).
- Query speed & freshness: finished workouts appear on leaderboards within 60 seconds (p99); leaderboard and top-activity reads return in under 200 ms (p99).
- Immediate privacy enforcement: GPS points inside a privacy zone never reach any follower, and blocking or unfollowing a viewer cuts off their live stream within seconds.
Explicit assumptions
- Local start date governs time buckets: Maya's Monday
06:30run in Sydney counts toward Monday (2026-05-04) and ISO week2026-W19(Monday–Sunday in the athlete's local time zone at start), even though UTC is still on Sunday evening. Workouts crossing midnight belong entirely to their local start date. - 7-day late-upload grace window: if a hiker records offline in the mountains on Sunday and syncs on Tuesday, last week's leaderboard updates to include it. Seven days after a period ends, that period's leaderboard freezes (
final) so published standings and prizes never shift retroactively (while the athlete's personal lifetime totals still update). - Canonical SI units: distances are stored as integer meters and durations as integer seconds to avoid floating-point drift; clients format kilometers or miles.
- Live trail: Maya in Sydney starts a 12 km morning run at
Back-of-the-envelope numbers
Using Little's Law (
concurrent items in flight = arrival rate × average duration), we size live traffic separately from completed-workout storage:Users & daily workout volume (assumed scale) Registered users / Daily Active Users (DAU) 50M registered / 10M DAU Completed workouts per day 4M/day (~46/s average, ~133/s at peak hour) Average workout duration & GPS rate 50 min (3,000 s) @ 1 point/s = 3,000 GPS points Live concurrent trails at peak hour (12% of daily starts = 480,000 starts/hour ≈ 133.3 starts/s) Workouts in progress simultaneously 133.3 starts/s × 3,000 s = ~400,000 active workouts Live-shared trails (25% opt-in) ~100,000 concurrent live trails Live ingest (1 batch every 5 s per phone) 100,000 / 5 s = 20,000 HTTPS requests/s (100k pts/s) Live payload bandwidth (~24 B/point) 100,000 pts/s × 24 B ≈ 2.4 MB/s raw GPS data Live viewers (~2 viewers/trail average) ~200,000 open WebSockets (~40,000 pushes/s) Celebrity tail case 1 pro marathoner watched live by 300,000 followers! Completed workout storage & social graph Full GPS track file (3,000 pts × 24 B) ~72 KB raw -> ~25 KB compressed (.FIT / Protobuf) Track object storage growth 4M/day × 25 KB = ~100 GB/day -> ~36.5 TB/year Activity summary rows 4M/day = 1.46B rows/year × ~500 B ≈ 730 GB/year Follow graph (avg 150 follows × 50M users) 7.5B directed edges × 2 directions × ~40 B ≈ 600 GB Read queries (leaderboards + top activities) 10M DAU × 3 queries/day 30M queries/day (~350/s average, ~1,000/s peak)Four architectural decisions follow directly from this math: 1. Keep live GPS batches out of the relational database.
20,000 writes/sof disposable in-progress dots belong in fast in-memory structures (Redis) that expire after the run ends, while the durable database sees only~133 transactions/sof finished workouts! 2. Design for the 300,000-viewer celebrity outlier, not just the 2-viewer average. Gateway nodes must multiplex one internal subscription across thousands of local viewer sockets. 3. Never scan 1.46 billion rows per year for arbitrary date ranges. Answering "top 10 runs between Apr 10 and Jun 05" under 200 ms requires compact pre-aggregated daily and monthly top-k buckets.API design
1. Workout recording & completion (Mobile / Watch -> HTTPS) POST /v1/activities Body: {"activity_id": "act_9d4a..." (client-generated UUID), "sport": "run", "started_at": "2026-05-04T06:30:04+11:00", "share_live": true} -> 201 Created {"activity_id": "act_9d4a...", "live_token": "..."} (Idempotent on activity_id) POST /v1/activities/{id}/points Body: {"seq": 42, "points": [{"t": 1777836814, "lat": -33.8688, "lon": 151.2093, "alt": 29, "hr": 154}]} -> 204 No Content (Duplicate or older `seq` ignored) POST /v1/activities/{id}/finish Body: {"ended_at": "2026-05-04T07:26:12+11:00", "format": "fit"} -> 200 OK {"upload_url": "https://storage.../put-presigned-15m"} (Phone PUTs compressed track file) 2. Live trails (Follower App -> REST + WebSocket) GET /v1/live/following -> [{"activity_id": "act_9d4a...", "athlete": {...}, "sport": "run", "distance_m": 7420}] GET /v1/activities/{id}/trail?since_seq=0 -> {"points": [...downsampled <= 1,000 pts...], "last_seq": 42, "status": "live"} WS /v1/stream Client sends: {"subscribe": "act_9d4a..."} Server pushes: {"activity_id": "act_9d4a...", "seq": 43, "points": [...]} 3. Top single activities over any date range GET /v1/top-activities?sport=run&metric=distance_m&from=2026-04-10&to=2026-06-05 &scope=country:CA&limit=10 -> {"items": [{"rank": 1, "activity_id": "...", "user": {...}, "value": 42195, "local_date": "2026-05-17"}], "as_of": "2026-06-06T09:15:00Z"} 4. Period leaderboards (summed totals per athlete) GET /v1/leaderboards/run/distance_m/week:2026-W19?scope=country:CA&limit=50&around=me -> {"entries": [{"rank": 1, "user_id": "u_9", "value": 186500}, ...], "me": {"rank": 31408, "value": 24000}, "board_status": "live" | "final", "as_of": "..."}Why three subtle API choices save headaches later: - Client-generated
UUID(activity_id): if a sweaty runner taps "Save" in an elevator and the phone retries three times, all three calls carry the exact sameactivity_idso we never create duplicate workouts. - Plain HTTPS batches from the runner's phone, WebSockets only for viewers: runners move between cell towers and OS background modes where persistent sockets drop constantly; stateless 5-second HTTPS POSTs withseqnumbers retry cleanly. - Pre-signed URL for final track upload: a pre-signed URL is a time-limited cryptographic upload link to object storage (like S3), letting phones upload 25 KB–2 MB GPS files straight to storage instead of tying up API server memory.Data model
1. Social & user DB (Sharded relational / KV store) users user_id (PK), name, country_code, account_privacy (public | followers_only), live_sharing_default (followers | nobody), leaderboard_opt_out (bool), privacy_zones_json [{lat, lon, radius_m}] following PK (follower_id, followee_id), status (active | pending) -- sharded by follower_id followers PK (followee_id, follower_id), status (active | pending) -- sharded by followee_id blocks PK (actor_id, blocked_id) 2. Activities & totals DB (PostgreSQL sharded by `user_id`) activities activity_id (PK), user_id, sport, state (live | processing | complete | deleted), start_utc, start_local_date, tz_name, country_code, distance_m, moving_time_s, elevation_gain_m, visibility (public | followers | private), is_flagged (bool), s3_track_key, summary_polyline Local shard indexes: (user_id, sport, start_local_date) (sport, start_local_date, distance_m DESC) period_totals PK (user_id, sport, period_type, period_key), distance_m, moving_time_s, elevation_gain_m, activity_count, updated_at Example: ('u_28', 'run', 'week', '2026-W19') -> 24000 m, 8120 s, 195 m, 2 runs frozen_boards PK (sport, metric, period_key, scope), snapshot_blob_key, frozen_at 3. Ephemeral & ranking index layer (Redis Cluster — 100% rebuildable from DB) live:user:{user_id} -> activity_id (TTL 60 s, refreshed on each 5 s GPS batch) live:act:{activity_id}:points -> capped list of privacy-trimmed GPS batches (TTL 1 h after finish) live:act:{activity_id}:meta -> hash: {last_seq, distance_m, status} lb:{sport}:{metric}:{period}:{scope} -> Sorted Set (ZSET): member = user_id, score = total top:{sport}:{metric}:{scope}:{bucket} -> ZSET of up to 200 best (value, activity_id) + `floor` metadata where `bucket` is `day:YYYY-MM-DD` or `month:YYYY-MM`Two concepts to define clearly: - Summary polyline: a compact ASCII string (Google's Encoded Polyline format) compressing a 3,000-point route into ~400 characters so feed cards draw crisp route thumbnails without fetching files from S3. - Redis Sorted Set (
ZSET): an in-memory data structure that associates each unique member (user_idoractivity_id) with a numericscore, keeping members sorted inO(log N)time for both updates and top-N range reads.High-level architecture
Runner's Phone / Watch | (A) Every 5 s: POST /points (HTTPS) | (B) On finish: PUT .FIT file via pre-signed URL v v [ API Gateway ] [ Object Storage (S3): Raw GPS Tracks ] | | v v [ Live Ingest Service ] [ Track Processor Workers ] | 1. Check live_token & seq > last_seq | Clean GPS spikes, compute official distance/elev, | 2. Strip points inside athlete privacy_zones | detect multi-device duplicates, trim privacy zones v v [ Redis Cluster: Live State ] [ Sharded Activities DB (key = user_id) ] | Append points, refresh 60 s TTL, | Single ACID transaction: | SPUBLISH trail:{activity_id} | activities + period_totals + outbox v | [ WebSocket Gateway Fleet ] v (Change Data Capture / Outbox Relay) | Verify active follow + not blocked [ Kafka: activity-events (partitioned by user_id) ] v | | | Approved Followers (Live Map) v v v [ Leaderboard Updater ] [ Top-K Bucket Updater ] [ Push Notifier ] | | v v [ Redis Cluster: `lb:*` ZSETs & `top:*` Day/Month ZSETs ] ^ | Viewer / Coach App ---> [ Ranking & Query API ] -+ (Falls back to DB shards + nightly reconciliation)Notice how cleanly the fast disposable live path (left) is separated from the exact durable ranking path (right): if Redis live state ever restarts mid-run, nobody loses a single meter of their workout because the phone uploads the complete authoritative
.FITfile down the right-hand path when finished.Deep dive 1: real-time live trails for followers
1. Discovering who is live (
fan-out on read)How does
GET /v1/live/followingfind which of the people I follow are running right now? There are two classic patterns: - Fan-out on write: when Maya starts a run, write"Maya is live"into the inbox of every follower. Fine for 140 followers—catastrophic when a pro marathoner with 5,000,000 followers taps Start! - Fan-out on read (our choice): when Maya sends a 5-second GPS batch, we update one single key:SET live:user:{maya_id} act_9d4a EX 60. When a viewer opens the app, we fetch theirfollowinglist (~150 IDs on average) and pipelineGET live:user:*across the Redis Cluster. At 10M DAU opening the app 3 times/day,10M × 3 × 150 / 86,400 s ≈ 52,000 Redis key reads/s—trivial for a small Redis Cluster, with zero celebrity write spike, and if Maya's phone battery dies mid-run, the 60-second TTL automatically clears her live badge within a minute!2. Streaming updates—including the 300,000-viewer marathoner
We broadcast trail batches inside Redis using sharded pub/sub (
SPUBLISHin Redis 7), which hashestrail:{activity_id}to one specific Redis shard instead of copying every message across every node in the cluster. Each WebSocket Gateway server subscribes totrail:{activity_id}at most once, no matter how many local users are watching that runner:Redis shard owning `trail:act_pro` | (1 message every 5 seconds — just 15 network hops total!) +---> WS Gateway 1 ---> fans out in local RAM to 20,000 connected follower sockets +---> WS Gateway 2 ---> fans out in local RAM to 20,000 connected follower sockets ... +---> WS Gateway 15 --> fans out in local RAM to 20,000 connected follower sockets (= 300,000 viewers served @ 60,000 socket writes/s fleet-wide)If an athlete marks a race broadcast
public, we go even cheaper: serveGET /trailthrough a CDN with a 5-second cache TTL so 1,000,000 anonymous spectators cost ~1 origin read per CDN edge every 5 seconds. Followers-only trails never use a shared CDN cache because every subscriber requires an individual follow + block check.3. Live privacy guarantees
- Ingest-time privacy-zone stripping: coordinates falling inside an athlete's hidden home/office circle (
distance(pt, center) <= radius_m) are stripped before touching Redis or pub/sub so raw home coordinates never exist in live caches or logs. Official workout distance still counts accurately from the full end-of-run.FITfile! - Instant revocation on block or unfollow:
POST /blockor togglingshare_live = falsepublishes a control event causing WebSocket Gateways to terminate that viewer's subscription socket within seconds.
- Ingest-time privacy-zone stripping: coordinates falling inside an athlete's hidden home/office circle (
Deep dive 2: exact top activities over any date range
Why do plain database indexes fail on "top 10 longest runs in Canada between
2026-04-10and2026-06-05"? - An index on(country, sport, start_local_date)scans every single Canadian run in those 57 days (millions of rows) to find the longest 10. - An index on(country, sport, distance_m DESC)walks all-time longest marathons from years ago, skipping thousands of out-of-range rows whenever a user asks for a narrow window like "last Tuesday".The solution: hierarchical daily and monthly top-200 buckets
For a single user (
scope = user:{id}), even an ultrarunner logs < 1,000 runs/year, so reading their user shard's(user_id, sport, start_local_date)index is instant.For
globalandcountry:{code}scopes, we maintain a Redis Sorted Set of the topB = 200activities for every single calendar day (day:2026-04-10) and every full calendar month (month:2026-05). Any[start, end]date range decomposes into whole months in the middle plus single days at the two ends:Query window: 2026-04-10 .. 2026-06-05 (k = 10, bucket size B = 200) |-- 21 day buckets --|--- 1 month bucket ---|-- 5 day buckets --| Apr 10 ........ Apr 30 May 2026 Jun 01 ...... Jun 05 Total buckets read = 21 + 1 + 5 = 27 buckets (at most 27 × 200 = 5,400 candidates -> pick top 10!) Even a full 365-day custom window touches <= 30 + 11 + 30 = 71 buckets (~14,200 candidates, < 5 ms).Why is taking the top
k(k <= 100) across these buckets 100% mathematically exact (not an approximation)? Because if an activity is truly among the topkacross the entire date range, fewer thankactivities beat it across the entire range—so certainly fewer thank(<= 100 < 200) beat it inside its own day or month! Therefore, it is guaranteed to sit inside its bucket's stored top 200.Protecting the bucket invariant under deletes, edits, and late uploads (the
floorrule)Here is the subtle bug that trips up even experienced engineers: suppose a bucket holds at most
B = 3runs ([42 km, 38 km, 35 km]), and earlier we evicted a34 kmrun. Now someone deletes their38 kmrun (leaving[42 km, 35 km], size2 < 3), and a late upload arrives with30 km! If we blindly inserted30 kmjust because the bucket has room (size < 3), the bucket would hold[42 km, 35 km, 30 km]—returning30 kmin a top-3 query while missing the34 kmrun we evicted earlier!To make deletes, edits, and late uploads 100% exact, each bucket stores
floor: the highest(value, activity_id)ever evicted from that bucket (Noneif the bucket has never overflowedB = 200):Bucket invariant: If floor is None: bucket holds ALL valid activities for that day/month. If floor is not None: bucket holds EVERY valid activity strictly greater than `floor`.import heapq from datetime import date, timedelta def first_of_next_month(d: date) -> date: if d.month == 12: return date(d.year + 1, 1, 1) return date(d.year, d.month + 1, 1) def cover_range_with_buckets(start_date: date, end_date: date) -> list: """Split inclusive [start_date, end_date] into whole-month buckets and edge day buckets.""" bucket_keys = [] cursor = start_date while cursor <= end_date: month_end = first_of_next_month(cursor) - timedelta(days=1) # Use a single month bucket whenever cursor sits on the 1st and the whole month fits if cursor.day == 1 and month_end <= end_date: bucket_keys.append(f"month:{cursor.year:04d}-{cursor.month:02d}") cursor = month_end + timedelta(days=1) else: bucket_keys.append(f"day:{cursor.isoformat()}") cursor += timedelta(days=1) return bucket_keys def insert_candidate_into_bucket(bucket: dict, value: int, activity_id: str, capacity: int = 200): """Maintain exact top-capacity invariant: bucket = {'entries': set of (val, id), 'floor': tuple|None}.""" candidate = (value, activity_id) floor = bucket["floor"] # Reject any insert (new, late upload, or lowered edit) at or below an already-evicted entry! if floor is not None and candidate <= floor: return bucket["entries"].add(candidate) if len(bucket["entries"]) > capacity: evicted = min(bucket["entries"]) bucket["entries"].remove(evicted) # Every entry inside was > old floor, so the newly evicted minimum becomes the new floor bucket["floor"] = evicted def query_top_k(buckets_by_key: dict, start_date: date, end_date: date, k: int) -> list: """Merge precomputed day/month buckets to find exact top-k (value, activity_id) in range.""" merged_candidates = [] for key in cover_range_with_buckets(start_date, end_date): bucket = buckets_by_key.get(key) if bucket is not None: merged_candidates.extend(bucket["entries"]) return heapq.nlargest(k, merged_candidates)In Redis,
insert_candidate_into_bucketruns as one atomic Lua script on the bucket's ZSET. What if deletes shrink a bucket that has evicted items (floor is not None) below150entries? A background worker queries the top 200 from every DB shard's(sport, start_local_date, distance_m DESC)index, refills the ZSET back to 200, and resetsfloor(and iffloor is None—say a quiet day in a small country with only 30 runs total—we never trigger a refill because all 30 runs are already present!). Memory is tiny:5 sports × 3 metrics × 51 scopes (global + 50 countries) × 200 entries = 153,000 entries/day, or ~1.4 GB for 90 hot days in Redis (older day buckets live in PostgreSQL).Deep dive 3: idempotent leaderboards and tie-safe ranks
Why
ZINCRBYcorrupts leaderboards—and how absolute totals fix itIf a worker updates Redis leaderboards with
ZINCRBY lb:run:distance:week:2026-W19 12000 u_28("add 12 km to user 28"), any Kafka consumer restart or network retry adds another 12 km, silently giving the runner 24 km instead of 12 km!Instead, the Track Processor executes one atomic PostgreSQL transaction on
u_28's database shard using a Change Data Capture (CDC) / transactional outbox event carrying the new absolute period total:BEGIN; -- Step 1: Insert workout once using client UUID; if 0 rows returned, this is a duplicate retry! WITH newly_inserted AS ( INSERT INTO activities (activity_id, user_id, sport, start_local_date, distance_m, moving_time_s, elevation_gain_m) VALUES (:activity_id, :user_id, 'run', '2026-05-04', 12000, 3360, 95) ON CONFLICT (activity_id) DO NOTHING RETURNING user_id, distance_m, moving_time_s, elevation_gain_m ), -- Step 2: Only if newly_inserted produced a row, add its numbers to period_totals and return the NEW total updated_week AS ( INSERT INTO period_totals (user_id, sport, period_type, period_key, distance_m, moving_time_s, elevation_gain_m, activity_count) SELECT user_id, 'run', 'week', '2026-W19', distance_m, moving_time_s, elevation_gain_m, 1 FROM newly_inserted ON CONFLICT (user_id, sport, period_type, period_key) DO UPDATE SET distance_m = period_totals.distance_m + EXCLUDED.distance_m, moving_time_s = period_totals.moving_time_s + EXCLUDED.moving_time_s, elevation_gain_m = period_totals.elevation_gain_m + EXCLUDED.elevation_gain_m, activity_count = period_totals.activity_count + 1 RETURNING user_id, distance_m ) -- Step 3: Write the new absolute total (e.g., 24,000 m) to the outbox in the exact same transaction INSERT INTO outbox (partition_key, event_type, payload_json) SELECT user_id, 'TotalsUpdated', json_build_object('period', 'week:2026-W19', 'distance_m', distance_m) FROM updated_week; COMMIT;Because Kafka partitions
activity-eventsbyuser_id,u_28's total updates arrive in strict commit order, and the Leaderboard Updater simply overwrites the score withZADD lb:run:distance:week:2026-W19:country:CA 24000 u_28: - DeliveringZADD ... 24000 u_28five times still leaves24,000! - Deleting or editing a workout simply subtracts insideperiod_totalsand emits the new lower absolute total (orZREMif0).Serving top-50, tie-aware ranks, and "People I Follow" boards
- Top 50:
ZREVRANGE key 0 49 WITHSCORESruns inO(log N + 50)(~0.5 ms). - Exact rank with ties (standard competition ranking
1, 2, 2, 4): Redis'sZREVRANKbreaks ties alphabetically byuser_id, unfairly ranking one24,000 mrunner#2and another#3. Instead, we look up the user's scoreS = ZSCORE key u_28(24000) and count strictly higher scores:rank = 1 + ZCOUNT key (24000 +inf— stillO(log N)in Redis, and every runner at24,000 mcleanly shares rank#2! - "People I Follow" leaderboard: we never materialize 50 million custom boards! On read, we fetch the viewer's
followingIDs (capped at 5,000) and issue oneZMSCORE lb:run:distance:week:2026-W19:internal_all u_3 u_9 ..., filter out blocked/unauthorized accounts, and sort those ~150 numbers in memory in < 2 ms. Noticeinternal_allincludesfollowers_onlyaccounts that are intentionally excluded from publicglobal/countryZSETs so approved friends still appear on your personal following board!
- Top 50:
Scaling, failure handling, and tricky edge cases
Scaling & resilience
- Hot global leaderboard reads: millions of runners open
globalweekly running distance on Sunday evening; caching top-50 pages in API memory for 5 seconds absorbs massive read spikes whilearound=mechecksZSCORE+ZCOUNTinO(log N). - Redis shard loss: live boards rebuild by streaming
period_totalsrows from PostgreSQL shards;finalboards (> 7 days past period end) restore directly fromfrozen_boardssnapshots so post-freeze late uploads never alter historical winners. - Anti-cheat & visibility changes: workouts exceeding physical sport limits (e.g., running 45 km/h due to forgetting to stop the app in a car) are saved with
is_flagged = trueand excluded fromperiod_totalsandtop:*buckets until reviewed. Switching an account frompublictofollowers_only(or togglingleaderboard_opt_out) emits aVisibilityChangedevent that immediately runsZREMacross publiclb:*andtop:*keys.
Easy-to-miss edge cases
- Timezone travel + late offline sync: an athlete runs Sunday
20:30in Los Angeles (04:30Monday UTC), flies to London, and syncs Tuesday. Because we persist the GPS-derivedstart_local_date(Sunday) at recording start, the run credits last week's board (open under the 7-day grace window), never shifting when the phone later enters a new timezone. - Dual-device recording (watch + phone): recording the same run on both a GPS watch and a phone in a pocket would double weekly distance! During track processing, if a new workout overlaps
>= 80%in UTC[start_utc, end_utc]with an existing workout of the same(user_id, sport), we mark the lower-fidelity recording as a duplicate (duplicate_of) and exclude it fromperiod_totals. - Broken device clocks: timestamps > 24 hours in the future (or predating account creation) are flagged instead of polluting future week/month buckets.
- Hot global leaderboard reads: millions of runners open
Validation with end-to-end traces, tests, and production metrics
Tracing our three prompt scenarios end to end
- Maya's Sydney live run: point recorded
06:40:00, sent in 5 s batch at06:40:05, privacy-checked +SPUBLISHed + pushed over WebSocket by06:40:05.3-> 5.3 s worst-case delay (< 10 s p95 target). - Coach's 57-day Canada top-10 query: 27 Redis ZSET reads pipelined in 1 round-trip (~3 ms), merging <= 5,400 tuples in Python/Go (~1 ms) -> < 15 ms total (< 200 ms p99 target).
- Liam's retried marathon upload: second upload hits
ON CONFLICT (activity_id) DO NOTHING, emits 0 outbox events, leavesperiod_totalsand Redis untouched.
Automated test strategy
- Property-based bucket test: generate thousands of random workouts, late uploads, deletes, and score-lowering edits across random dates, asserting
query_top_k(...)matches a brute-force filter-and-sort over all active rows on 1,000 random[from, to]windows (specifically catching any brokenfloorlogic!). - Idempotency & replay chaos test: duplicate HTTP
/finishcalls and force Kafka partition replays from offset 0; verifyperiod_totalsand everylb:*ZSET match single-delivery ground truth bit-for-bit. - Privacy canary test: synthetic runner emits points inside and outside a 250 m home privacy circle; assert 0 inside-zone coordinates ever appear in
/trail, WebSocket frames, or logs, and verifyPOST /blockdrops an open follower WebSocket within 5 seconds.
Production monitoring & nightly reconciliation
- Nightly SQL-vs-Redis reconciliation job: recomputes top 1,000 entries and sampled user totals from
period_totalsand compares against live Redislb:*andtop:*keys—paging if mismatch count > 0. - Key SLO alerts: synthetic live-trail delay (
p95 < 10 s), Kafka leaderboard consumer lag (p99 < 60 s), query latency (p99 < 200 ms), and privacy-canary violations (target = 0).
- Maya's Sydney live run: point recorded
Summary of key trade-offs
- Ephemeral Redis + sharded pub/sub for live trails vs. database writes: handles 20,000 GPS batches/s cheaply in RAM without taxing durable storage, accepting that a Redis node crash briefly interrupts live map dots while the phone preserves the full official workout.
- Fan-out on read (
live:user:*) vs. fan-out on write: avoids 5-million-write spikes when celebrity athletes start a run, trading ~150 fast pipelined key checks whenever a follower opens the app. - Daily + monthly top-200 ZSET buckets with
floortracking vs. raw SQL scans: delivers exact sub-20 ms top-k answers over any custom date range, trading ~1.4 GB of Redis RAM, a cap ofk <= 100, and occasional shard refills after heavy deletions. - Absolute totals via transactional outbox (
ZADD) vs. deltas (ZINCRBY): requires storingperiod_totalsin PostgreSQL first, in exchange for making retries, replays, edits, and deletes effortlessly idempotent. - Athlete local start date + 7-day freeze window vs. strict UTC cut-off: matches human intuition ("my Monday morning run"), using a 7-day grace window before snapshotting
finalboards so offline athletes aren't penalized and finished competitions never shift afterward.
Intuition & how it works
Think of a global fitness app as running three very different scoreboards at three different speeds:
1. Live trails work like chalk footsteps on a sidewalk: runners drop lightweight breadcrumb batches into fast memory every 5 seconds so friends can follow along right now, and those breadcrumbs wash away an hour after the run ends because the runner's watch uploads the permanent, official track file at the finish line.
2. Top single activities over any date range work like keeping a Trophy Shelf of the top 200 workouts for every single calendar day and every full calendar month. When someone asks for the top 10 runs between Apr 10 and Jun 05, you never rummage through hundreds of millions of diary pages—you pull down Apr 10–30's 21 daily shelves, May's 1 monthly shelf, and Jun 1–5's 5 daily shelves, and pick the longest 10 from that tiny pile!
3. Weekly and monthly leaderboards work like a bank ledger paired with a wall scoreboard: a transactional database calculates each athlete's exact running total first, and then overwrites (never blindly adds to!) their number on the wall scoreboard so a retried upload can never count the same marathon twice.
Why do the obvious designs fail? First, inserting 100,000 live GPS points per second into a relational database turns disposable dots into a massive disk bottleneck—and pushing "Maya started a run" to all 5 million followers of a famous marathoner triggers millions of wasted writes. Second, answering "top 10 longest runs between Apr 10 and Jun 05" with a SQL query either scans tens of millions of rows in that date window or walks all-time marathons outside the window, timing out either way. Third, updating a leaderboard with incremental ZINCRBY +12 km silently double-counts workouts whenever a mobile phone retries a flaky upload or an event stream replays after a restart.
Walk through 4 concrete events to see how all three subsystems stay fast and exact:
1. 06:30 Monday in Sydney (19:30 Sunday UTC) — Maya starts a live run:
-> Phone sends client UUID `act_9d4a` and 5-second HTTPS GPS batches (seq=1, 2, ...).
-> Live Ingest strips points inside Maya's 250 m home privacy circle, refreshes
`live:user:maya` (60 s TTL), and broadcasts via Redis sharded pub/sub (`SPUBLISH`)
to WebSocket Gateways watching `act_9d4a`.
2. 07:26 — Maya finishes (12,000 m) and uploads her .FIT file twice on a spotty train:
-> Upload #1: PostgreSQL transaction inserts `act_9d4a`, adds 12,000 m to Maya's
local-Monday week `2026-W19` in `period_totals` (new total = 24,000 m), and writes an
outbox event `TotalsUpdated(u_maya, 2026-W19, 24000)`.
-> Upload #2 (retry): hits `ON CONFLICT (activity_id) DO NOTHING` -> stops immediately!
3. 07:26:02 — Stream consumers update Redis rankings idempotently:
-> Leaderboard Updater runs `ZADD lb:run:distance:week:2026-W19:AU 24000 u_maya`
(repeating `ZADD 24000` is harmless!) and computes tie-safe rank via `1 + ZCOUNT (24000 +inf`.
-> Bucket Updater checks `12000 > floor` and adds `(12000, act_9d4a)` to `day:2026-05-04`
and `month:2026-05` top-200 buckets.
4. 09:15 — Coach queries top 10 Canada runs for `2026-04-10 .. 2026-06-05`:
-> Query API fetches 21 Apr day buckets + 1 May month bucket + 5 Jun day buckets (27 keys),
merges <= 5,400 candidates in memory, and returns the exact top 10 in < 15 ms.
Key trade-offs
- Live GPS points in Redis vs. durable database tables. Keeping in-progress trails in RAM with sharded pub/sub (a Redis 7 feature that routes channel messages only to the cluster shard owning that channel) makes handling 20,000 requests/s cheap and sub-second. The trade-off is that a Redis node crash briefly interrupts the live map view, which is completely acceptable because the athlete's device saves every second locally and uploads the complete
.FITfile at the end. - Stateless 5-second HTTPS batches from phones vs. persistent mobile WebSockets. Sending numbered 5-second HTTPS requests survives cell-tower handoffs and OS background throttling far better than a fragile persistent socket on the runner's phone, trading up to 5 seconds of batching delay (well within our 10-second p95 goal) for rock-solid reliability.
- Fan-out on read vs. fan-out on write for "who is live now". Fan-out on read means checking ~150
live:user:*keys when a follower opens the app rather than pushing status updates to millions of follower inboxes when an athlete starts. It costs ~52,000 fast Redis reads/s across 10M daily users, completely eliminating celebrity write storms. - Absolute totals (
ZADD) via transactional outbox vs. score increments (ZINCRBY). Maintainingperiod_totalsin PostgreSQL and publishing events via a transactional outbox (writing data and its outbound Kafka event inside one database commit) adds one database upsert per finished workout (~133/s at peak), in exchange for making retries, Kafka replays, edits, and deletes 100% idempotent (safe to apply multiple times without double-counting). - Precomputed daily/monthly top-200 ZSET buckets vs. ad-hoc SQL scans. Redis Sorted Sets (
ZSETs) storing the top 200 workouts per day and month answer arbitrary date-range top-k queries exactly in milliseconds (~1.4 GB RAM for 90 days), trading offk <= 100, an evictionfloorcheck on inserts/edits, and rare cross-shard refills if heavy deletions shrink a full bucket below 150 items. - Athlete local start date + 7-day freeze vs. strict UTC cut-offs. Bucketing by local start date ensures a Monday 6:30 AM run in Sydney or a Sunday 9 PM run in California lands in the week the runner actually experienced, while freezing boards 7 days after period close keeps contest winners permanent without dropping weekend offline hikes.
Common mistakes
- Writing every 1 Hz live GPS coordinate into the primary SQL database, turning 100,000 disposable points/s into a severe storage and lock bottleneck.
- Using
ZINCRBYwithout deduplication for leaderboards, causing every retried mobile finish call or replayed Kafka batch to double-count an athlete's distance. - Scanning raw activity rows—or relying only on fixed weekly boards—for arbitrary date-window top-activity queries, which either times out on wide date windows or cannot answer custom ranges like
Apr 10 .. Jun 05. - Forgetting the eviction
floorwhen maintaining top-k buckets, allowing a lowered edit or late upload to slip into a bucket that shrank below 200 after a deletion and rank ahead of better workouts that were trimmed earlier! - Bucketing workouts by UTC timestamp or server upload timestamp, placing a Sydney Monday-morning run into Sunday's week or pushing a Sunday mountain run synced on Tuesday into the wrong week.
- Trimming home privacy zones only when generating the final map, leaking the athlete's home address to followers watching the live stream.
- Checking follow/block permissions only when a WebSocket first connects, allowing a freshly blocked user to keep watching the rest of an athlete's live run.
- Using raw
ZREVRANKfor leaderboard rank, breaking ties arbitrarily by user ID instead of standard competition ranking (1 + ZCOUNT key (score +inf, where tied scores share the exact same rank). - Double-counting simultaneous phone + watch recordings when an athlete records the same run on two devices at once.
Follow-up questions
- Which parts of the architecture break first if user traffic and workout volume grow tenfold, and how would you re-partition them? At 500M users and 200,000 live GPS batches/s, live ingest and Redis live shards still scale horizontally by
activity_id, with adaptive server-driven batching (widening phones from 5 s to 10 s intervals during regional peak surges). A single global weekly running ZSET with ~60M members would become a single-shard memory and CPU hotspot (~6 GB on one Redis node), so we partition global boards by country (or 64 user-hash shards): global top-100 merges the top 100 from each partition in milliseconds, and exact global rank sumsZCOUNT key (score +infin parallel across those partitions (or serves fast percentile estimates above 100,000th place from a compact score histogram). Object storage (~365 TB/year compressed) uses automated lifecycle tiering to move raw.FITtracks older than 90 days into cold archive storage while keeping lightweight summary polylines hot. - Which operational metrics, synthetic checks, and reconciliation alarms would you put on dashboards in production? Track end-to-end live-trail latency using a synthetic runner-and-follower canary (
p95 < 10 s), live ingest HTTP error rates, WebSocket gateway connection counts, and reconnect rates. On the ranking pipeline, alert on outbox/Kafka consumer lag (board freshness p99 < 60 s), query APIp99 < 200 ms, top-k bucket refill frequency, and implausible-speed cheat flags. Most importantly, alert immediately if the nightly SQL-vs-Redis reconciliation job finds any score mismatch (target = 0) or if privacy-zone canary bots detect even a single coordinate inside a hidden home radius. - Which subtle correctness or privacy edge case do candidates most often overlook in this domain? Offline late uploads interacting with local timezones and board freezing. Suppose a runner starts at
20:30Sunday in Los Angeles (04:30Monday UTC) with no cell service, flies to New York on Monday, and uploads on Tuesday: the system must use the GPS-recorded local start date (Sunday), credit last week'speriod_totalsand still-open leaderboard (inside the 7-day grace window), and—if uploaded 10 days late instead—update personal lifetime stats without mutating last week's already-snapshottedfinalleaderboard. A close runner-up is recording the exact same run on both a watch and a phone, which silently doubles leaderboard distance unless>= 80%time-overlapping workouts of the same sport are deduplicated on ingest. - If asked to code a working single-node prototype in a 60-minute interview, what would you keep versus strip out? Build a clean single-process service with in-memory Python data structures behind the exact same method boundaries so every correctness invariant is testable:
follows/blockssets,live_trails[activity_id]storing(seq, privacy_filtered_points)polled viaget_trail(viewer_id, activity_id, since_seq)instead of WebSockets,seen_activitiesUUID set for idempotent completion,period_totals[(user_id, sport, period)]storing integer meters, andactivities_by_day[(sport, local_date)]lists. Answertop_activities(from_date, to_date, k)withheapq.nlargest(k, ...)across days in the range, and compute competition ranks with1 + sum(score > my_score). Skip Kafka, Redis Lua scripts, S3 pre-signed URLs, and multi-tier month buckets during coding, then explain in two minutes how each maps onto your clean interfaces at 50M-user scale.
Follow-up questions
- Which parts of the architecture break first if user traffic and workout volume grow tenfold, and how would you re-partition them?
- Which operational metrics, synthetic checks, and reconciliation alarms would you put on dashboards in production?
- Which subtle correctness or privacy edge case do candidates most often overlook in this domain?
- If asked to code a working single-node prototype in a 60-minute interview, what would you keep versus strip out?
Similar questions
- In-Memory Spreadsheet Engine with Formulas and Cycle Handling
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency