Design Fitness Tracking

How to design a fitness app that records GPS activities offline, uploads them safely, shares live location and shows a feed of friends' activities.

Case study26 minLesson 5 of 8
On this page
  1. Clarify the problem
  2. Estimate the scale
  3. Define the API (optional)
  4. Model the data
  5. High-level design
  6. Deep dives
  7. Bottlenecks and failures
  8. What a strong answer sounds like
  9. Follow-up questions

A fitness tracking app records runs and bike rides with the phone's GPS, shows the route and statistics such as distance, pace and climb, lets friends see each other's activities in a feed, and can share a runner's position live. It is a common interview question because the data is created on a phone that is often offline, so uploads that arrive late, twice or half finished must all be handled correctly.

The steps below follow A Framework for Any Design.

Clarify the problem

The first five minutes
Interviewer

Design a fitness tracking app for runs and bike rides.

You

I understand the core as recording an activity with GPS, showing its statistics, and sharing it to friends' feeds. Does recording have to work with no signal, and do you want live tracking, where a friend watches me move?

Interviewer

Yes to both. Recording must work fully offline, and live sharing is opt-in, mostly for safety.

You

How many activities a day, how long is a typical one, and how many followers does a typical user have?

Interviewer

About 10 million activities a day, 45 minutes on average. Most users have tens of followers, and a few professional athletes have millions.

You

Then my top priority is that an activity is never lost and never stored twice, even with bad networks and retries. A feed that is a minute behind is acceptable, and live positions can be about 15 seconds old. I would leave out heart-rate sensors, training plans and payments. Do you want segment leaderboards?

Interviewer

Only in outline.

  • Functional requirements: record an activity with GPS while offline, upload it when the phone is online, show statistics and a map, show a feed of the activities of people you follow, share a live position, and rank segment times in outline.
  • Non-functional requirements: an activity is never lost or duplicated, recording never needs the network, an activity appears in friends' feeds within about a minute of upload, live positions are at most about 15 seconds old, and an activity page loads in under 300 ms.
  • Out of scope: sensors other than GPS, training plans, payments and messaging.

Estimate the scale

  • Size of one activity: the phone records one point a second, so a 45-minute activity has 45 × 60 = 2,700 points. At about 20 bytes a point (time, latitude, longitude, altitude and accuracy) that is 54 KB raw.
  • Uploads: 10 million ÷ 86,400 seconds is about 116 uploads a second on average. Weekend mornings are busier, so assume a peak of 5 times the average, about 580 a second.
  • Feed writes: if an activity has 50 followers, then 10 million × 50 = 500 million feed entries a day, which is about 5,800 a second.
  • Live sharing: if 50,000 people share their position at peak and each sends an update every 15 seconds, that is about 3,300 writes a second.
Estimate: Trace storage for a year

How much storage do the GPS traces need per year if you keep every point?

You know
  • 10 million activities a day
  • 2,700 points per activity, 20 bytes per point raw
  • Delta encoding plus compression shrinks traces to about a fifth

Show the working
  1. Raw: 2,700 × 20 B = 54 KB per activity
  2. Compressed: 54 KB ÷ 5 ≈ 11 KB
  3. Per day: 10 million × 10.8 KB ≈ 108 GB
  4. Per year: 108 GB × 365 ≈ 39 TB, about 40 TB

Estimate 40 TB (anything from 10 TB to 150 TB is a good answer)

Tens of terabytes a year of files that are always read whole is a job for object storage, not for database rows.

Your turn: Define the API

Write an upload call that the phone can retry any number of times without creating two activities. Then add the feed and live-sharing calls.

Compare with a model answer

The phone generates the activity id when recording starts and uploads with PUT /activities/{id}, so a repeated upload changes nothing. The feed is a paginated GET, and live sharing is a small POST of recent points plus a GET for viewers.

Define the API Optional

Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.

HTTP API
PUT  /activities/{activity_id}           id = UUID made on the phone at start
  headers: Content-SHA256: 9c1e...
  body: compressed trace file + { "type": "run", "title": "...", "visibility": "followers" }
  201 Created     { "activity_id": "a7f3...", "status": "processing" }
  200 OK          same id, same file: already stored, returns the same activity
  409 Conflict    same id, different file (a bug on the phone; never overwrite)
 
GET  /activities/{activity_id}           stats, simplified route line, segment efforts
GET  /feed?cursor=...&limit=20           friends' activities, newest upload first
 
POST /live                               start sharing   -> { "live_id": "lv_81", "viewer_link": "..." }
POST /live/{live_id}/points              batch of the last 15 s of points
GET  /live/{live_id}                     latest position + short trail, for viewers
  200 { "pos": [...], "updated_at": "...", "ended": false }

The decision worth arguing is who creates the activity id. If the phone creates it at the start of recording, the upload is a PUT to a name the phone already knows, and every retry lands on the same record. This is an idempotency key that exists before any network call is made.

Your turn: Model the data

Where do the GPS points live, and what goes in the database? Think about what each screen needs to read.

Compare with a model answer

Each activity's points are one compressed file in object storage, which is always read whole. The database holds one summary row per activity with its statistics and a simplified route line for feed cards. Feeds hold activity ids, and live positions are short-lived keys in memory.

Model the data

Records
activities                              -- partitioned by user_id
  activity_id   UUID PRIMARY KEY        -- made on the phone
  user_id       BIGINT
  file_sha256   CHAR(64)                -- detects "same id, different file"
  trace_key     TEXT                    -- "traces/u42/a7f3-9c1e.gz": id + hash
  status        VARCHAR(12)             -- processing | ready | failed
  started_at    TIMESTAMP               -- from GPS time, not the phone clock
  uploaded_at   TIMESTAMP
  distance_m, moving_s, climb_m INT
  route_line    TEXT                    -- about 100 points, for cards and thumbnails
  visibility    VARCHAR(10)             -- only_me | followers | everyone
 
follows         (follower_id, followee_id)       -- both directions indexed
feed_items      (user_id, uploaded_at, activity_id)   -- ids only, newest first
segment_efforts (segment_id, user_id, elapsed_s, activity_id)   -- every effort
segment_bests   (segment_id, user_id, elapsed_s)   -- index (segment_id, elapsed_s)
 
live:{live_id}  -> last 20 points, expires 10 min after the last update

A trace is written once and always read whole, so it is stored as a file in object storage. Feeds, profiles and statistics pages read the summary row instead. The table is partitioned by user_id, because "show my activities" is the most common query. A relational or a wide-column database would both work, as long as activity_id is a unique key.

Your turn: High-level design

Sketch the path from "the phone gets a signal" to "a friend sees the run". Which steps should happen before the server answers the phone, and which after?

Compare with a model answer

Before the answer, the server stores the file, inserts the row if it is absent and publishes an "uploaded" event. After the answer, workers compute statistics, match segments and add the activity to followers' feeds. Doing the slow work after the answer keeps uploads fast and retries cheap.

High-level design

The upload stores the file and the row and then answers the phone, and workers that can be retried do everything else.

The activity service stores the file and the row and then hands off to workers, which compute statistics, segment efforts and feed entries.Phone app to API gateway (PUT, GET /feed); API gateway to Activity service; Activity service to Trace files (raw file); Activity service to Activity DB (insert if absent); Activity service to Uploaded events (uploaded), asynchronous; Uploaded events to Processing workers, asynchronous; Processing workers to Activity DB (stats, efforts); Processing workers to Feed store (fan-out); Activity service to Feed store (read feed).Phone appAPI gatewayActivity serviceTrace filesActivity DBUploaded eventsProcessingworkersFeed storePUT, GET /feedraw fileinsert if absentuploadedstats, effortsfan-outread feed

request and replyasynchronous message

The activity service stores the file and the row and then hands off to workers, which compute statistics, segment efforts and feed entries.
Record offline, upload twice, appear onceUse the arrows or ← → keys
  1. Record offline, upload twice, appear once, step 1Phone app to API gateway; API gateway to Activity service; Activity service to Trace files; Activity service to Activity DB; Activity service to Uploaded events, asynchronous; Uploaded events to Processing workers, asynchronous; Processing workers to Activity DB; Processing workers to Feed store; Activity service to Feed store.Phone appofflineAPI gatewayActivity serviceTrace filesActivity DBUploaded eventsProcessingworkersFeed store
    points saved
    1,200

    1Leo presses Start with no signal. The phone creates the id a7f3 and writes points to a local file, flushing it every few seconds so that a crash loses seconds of data and not the whole run.

  2. Record offline, upload twice, appear once, step 2Phone app to API gateway; API gateway to Activity service; Activity service to Trace files; Activity service to Activity DB; Activity service to Uploaded events, asynchronous; Uploaded events to Processing workers, asynchronous; Processing workers to Activity DB; Processing workers to Feed store; Activity service to Feed store.Phone app1 to uploadAPI gatewayActivity serviceTrace filesActivity DBUploaded eventsProcessingworkersFeed store
    points saved
    2,700

    2He stops after 45 minutes with 2,700 points, which is 11 KB compressed. The phone computes the statistics immediately, and the upload waits in a local queue.

  3. Record offline, upload twice, appear once, step 3Phone app to API gateway; API gateway to Activity service; Activity service to Trace files; Activity service to Activity DB; Activity service to Uploaded events, asynchronous; Uploaded events to Processing workers, asynchronous; Processing workers to Activity DB; Processing workers to Feed store; Activity service to Feed store.Phone appAPI gatewayActivity serviceTrace filesActivity DBUploaded eventsProcessingworkersFeed store

    3The signal comes back, and the phone sends PUT /activities/a7f3 with the file and its hash.

  4. Record offline, upload twice, appear once, step 4Phone app to API gateway; API gateway to Activity service; Activity service to Trace files; Activity service to Activity DB; Activity service to Uploaded events, asynchronous; Uploaded events to Processing workers, asynchronous; Processing workers to Activity DB; Processing workers to Feed store; Activity service to Feed store.Phone appAPI gatewayActivity serviceTrace filesa7f3-9c1e.gzActivity DBUploaded eventsProcessingworkersFeed store

    4The service writes traces/u42/a7f3-9c1e.gz. The key includes the file's hash, so a retry rewrites the same bytes and a different file can never overwrite this one.

  5. Record offline, upload twice, appear once, step 5Phone app to API gateway; API gateway to Activity service; Activity service to Trace files; Activity service to Activity DB; Activity service to Uploaded events, asynchronous; Uploaded events to Processing workers, asynchronous; Processing workers to Activity DB; Processing workers to Feed store; Activity service to Feed store.Phone appAPI gatewayActivity serviceTrace filesActivity DBa7f3: processingUploaded eventsProcessingworkersFeed store
    rows for a7f3
    1

    5It inserts the row only if a7f3 is absent, with status processing, and then publishes an "uploaded" event.

  6. Record offline, upload twice, appear once, step 6Phone app to API gateway; API gateway to Activity service; Activity service to Trace files; Activity service to Activity DB; Activity service to Uploaded events, asynchronous; Uploaded events to Processing workers, asynchronous; Processing workers to Activity DB; Processing workers to Feed store; Activity service to Feed store.Phone apptimeoutAPI gatewayActivity serviceTrace filesActivity DBUploaded eventsProcessingworkersFeed store
    rows for a7f3
    1

    6The 201 reply is lost while the phone switches to Wi-Fi. The phone cannot tell whether the upload worked, so it keeps the file.

  7. Record offline, upload twice, appear once, step 7Phone app to API gateway; API gateway to Activity service; Activity service to Trace files; Activity service to Activity DB; Activity service to Uploaded events, asynchronous; Uploaded events to Processing workers, asynchronous; Processing workers to Activity DB; Processing workers to Feed store; Activity service to Feed store.Phone appAPI gatewayActivity serviceTrace filesActivity DBexists: 200Uploaded eventsProcessingworkersFeed store
    rows for a7f3
    1

    7The phone retries the PUT. The id a7f3 already exists with the same hash, so the service returns 200 and there is still one row.

  8. Record offline, upload twice, appear once, step 8Phone app to API gateway; API gateway to Activity service; Activity service to Trace files; Activity service to Activity DB; Activity service to Uploaded events, asynchronous; Uploaded events to Processing workers, asynchronous; Processing workers to Activity DB; Processing workers to Feed store; Activity service to Feed store.Phone appAPI gatewayActivity serviceTrace filesActivity DBa7f3: readyUploaded eventsProcessingworkersFeed store

    8A worker reads the event and the file, removes GPS jumps, computes distance and climb, simplifies the line to about 100 points and matches segments.

  9. Record offline, upload twice, appear once, step 9Phone app to API gateway; API gateway to Activity service; Activity service to Trace files; Activity service to Activity DB; Activity service to Uploaded events, asynchronous; Uploaded events to Processing workers, asynchronous; Processing workers to Activity DB; Processing workers to Feed store; Activity service to Feed store.Phone appAPI gatewayActivity serviceTrace filesActivity DBUploaded eventsProcessingworkersFeed store+50 entries
    feed entries
    50

    9The worker writes the id into the feeds of Leo's 50 followers. Entries are keyed by follower and activity, so if the event is delivered twice the same 50 entries are written, not 100.

  10. Record offline, upload twice, appear once, step 10Phone app to API gateway; API gateway to Activity service; Activity service to Trace files; Activity service to Activity DB; Activity service to Uploaded events, asynchronous; Uploaded events to Processing workers, asynchronous; Processing workers to Activity DB; Processing workers to Feed store; Activity service to Feed store.Phone appAPI gatewayActivity serviceTrace filesActivity DBUploaded eventsProcessingworkersFeed store

    10A friend opens the app. The service reads her feed ids, loads the summary rows, drops any activity she may no longer see and returns the cards.

1 / 10

Deep dives

Recording offline and syncing safely

The problem is that the phone is the only place the activity exists until the server confirms it, and the network between the two is unreliable. The design has to survive a killed app, a lost connection, a lost reply and a retry. It rests on four rules.

First, the phone writes locally before anything else. GPS works without a data connection, so points go into an append-only file on the phone, flushed every few seconds. If the operating system kills the app, it reopens the file and continues the same activity. Second, the phone creates the activity id when recording starts, as a random UUID. Third, uploads come from a local queue that retries with increasing delays, and the phone deletes its copy only after it receives a 200 or 201. Fourth, every server step can be repeated safely: the file key includes the file's hash, the row is inserted only if it is absent, and feed entries are keyed by follower and activity.

The remaining question is when the phone sends the data. Streaming every point keeps the server current, but it fails where there is no signal and drains the battery. Uploading one file when the activity ends needs a single small request and is naturally idempotent, but a phone that is lost mid-run loses the run. Uploading chunks during the activity limits that loss to the last chunk, but the server must assemble late, out-of-order chunks. One file at the end is the right choice for normal activities, and chunking is worth mentioning for very long events such as a 24-hour race.

Storing GPS traces

The problem is choosing a store for about 27 billion points a day. Every reader asks for a whole trace, and nobody asks for "point 1,734 of activity a7f3", and that access pattern decides the answer.

A row per point in a relational table would mean 10 million × 2,700 = 27 billion rows a day, about 312,500 inserts a second, and each row's overhead is larger than the 20-byte point. A time-series database compresses points well, but it is built for range reads across many series, while here every read is one whole activity. A compressed file per activity is about 11 KB, so a year is about 40 TB of cheap object storage, and one read returns everything the map needs.

Where the GPS points are stored
OptionGood atBad atPick it when
One row per pointIt is easy to query with SQL.It needs about 312,500 inserts a second, and each row's overhead is larger than the point.Use it for a small app or as an analytics copy, but not as the main store.
Time-series databaseIt compresses well and answers time-range queries.It is built for range reads across many series, but each read here is one whole activity.Use it when you need to query across many activities by time.
One compressed file per activity Usual defaultEach file is about 11 KB, the year's data is about 40 TB of cheap storage, and one read gets everything.You cannot query inside the file, so searchable fields must go in the summary row.Use it when traces are always read whole, which is the case here.

Delta encoding is what makes the file small. Consecutive points are only metres apart, so storing the difference from the previous point turns 4-byte coordinates into one or two bytes.

Live location sharing

Live sharing lets a friend follow a runner's position, usually for safety. It must be a separate, lossy path, because a failure in live sharing must never affect recording or the saved activity.

Live points are overwritten in memory, read by a few viewers and deleted ten minutes after the last update.Runner's phone to Live service (points every 15 s); Friend's phone to Live service (poll every 15 s); Live service to Live positions (set, expire 10 min).Runner's phoneFriend's phoneLive serviceLive positionspoints every 15 spoll every 15 sset, expire 10 min
Live points are overwritten in memory, read by a few viewers and deleted ten minutes after the last update.

The phone sends the last 15 seconds of points to the live service. The service overwrites one key that holds the latest 20 points, and the key expires 10 minutes after the last update. Viewers poll every 15 seconds. That is about 3,300 writes a second, which one in-memory store with a replica can handle. Only a few people watch each runner and each needs an update every 15 seconds, so polling is simpler than a persistent connection. The realtime communication lesson compares the push options.

The viewer should see how old the position is, for example "last update 6 minutes ago" when the runner has lost signal, instead of a dot that looks current.

The friends feed

The mechanics are the same as in Design a News Feed: the activity id is written into each follower's list when it is posted (fan-out on write), except for the few athletes with millions of followers, whose activities are fetched when a follower opens the feed (fan-out on read). Three details are specific to fitness activities.

  • Activities arrive late. A Saturday run may be uploaded on Monday. The feed orders by upload time so that friends see it, and the card shows the activity date.
  • Fan-out waits for processing. The feed card needs the distance and the route line, so the fan-out starts only after the statistics are ready.
  • Visibility can change after fan-out. Feeds store only ids, and the read path drops activities the reader may not see, so making a run private takes effect immediately.

Bottlenecks and failures

At 10 times the load there are 100 million activities a day and about 5,800 uploads a second at peak. The activity service is stateless, so it scales by adding servers. Object storage absorbs about 400 TB a year, and the activity table scales by adding partitions. The first component to strain is the feed fan-out, which becomes about 58,000 entries a second. You can lower the follower count above which activities are fetched on read, and you can let the fan-out lag by a few seconds at peak.

Component that failsWhat happensWhat you do
The networkRecording is not affected, because it never needs the network.The phone's upload queue retries when the connection returns.
An activity serverUploads that were in progress fail.The phone retries the same PUT, and the result is still one activity.
The event queueRows stay in processing and nothing reaches the feeds.Uploads still succeed. A sweeper republishes rows stuck for more than 10 minutes, and idempotent workers make any duplicates harmless.
The activity databaseUploads and activity pages fail until a replica takes over.The phones keep their files and retry, so no activity is lost, and the replica is promoted automatically.
A processing workerThe event it was handling is not acknowledged.The queue delivers the event to another worker.
The live storeViewers lose the position until the next update.Positions reappear within 15 seconds, because the phone keeps sending them.

What a strong answer sounds like

LevelWhat the answer does
JuniorThe answer streams GPS points into a table and builds the feed with a query over the people you follow.
Mid-levelThe answer records locally and uploads at the end, stores traces as files with summary rows, and reuses fan-out on write for the feed.
SeniorThe answer creates the id on the phone, makes every server step repeatable, keeps live sharing on a separate lossy path, and handles late uploads and visibility changes.
A lost replyStrong answer
Interviewer

The upload reply times out. What does the phone do?

You

It retries the same PUT /activities/a7f3. The id was created at the start, so the server either creates the activity or finds the existing one and returns 200, and only then does the phone delete its copy. Every step behind the upload is repeatable, so the retry cannot create a second activity.

Interviewer

What if two devices upload the same run, such as a watch and a phone?

You

They create different ids, so the server stores two activities. After processing I would detect overlap, meaning the same user with mostly the same time range, and ask the user which one to keep instead of guessing.

Follow-up questions

The phone's clock is wrong. Does it matter?

It does not matter for the statistics, because pace and ordering use each point's GPS time, which is accurate. The server sets uploaded_at itself, so a wrong phone clock cannot affect feed order.

How do you handle GPS noise?

A worker drops points with poor reported accuracy, rejects jumps that imply an impossible speed and smooths what remains. Distance is computed from the cleaned line, because noise in the raw points adds distance.

How do segment leaderboards work?

A segment is a fixed stretch of road that users compare times on. A worker checks whether the cleaned route passes through the start and end of each nearby segment, using a geographic index to find candidates, and writes one row to segment_efforts for every match. It updates segment_bests only if the new time beats the user's old best, and the leaderboard reads the first rows of that table by elapsed time.

How do you stop the app from revealing where someone lives?

The user can define a privacy zone around home or work. The server hides the part of the route inside the zone when it builds the route line and the map for everyone except the owner, and it never returns the hidden points to other users.

Self-review: fitness tracking0 of 12

After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".

Before drawing

Numbers and interfaces

Design and depth

Failure