Skip to content

Design a Fitness Tracking App (Strava)

Intermediate 89 min read Part 17 of 18

Design Strava: offline GPS recording, track upload and storage, live sharing, segment matching and leaderboards, and a friends' activity feed at scale.

The Problem#

We want to build a fitness tracking app like Strava. A runner opens the app, presses Start, and puts the phone in a pocket. For the next hour the app records where they are, how far they have gone, how fast, and how long they have been moving, even when they run through a forest with no signal. When they press Stop and Save, the run is uploaded, appears on a map, is compared against thousands of other runners who did the same climb, and shows up in the feeds of their friends, who can give it a like ("kudos").

Think of a running club with a very careful timekeeper. Each member carries a notebook (the phone) and writes down their position every second, no matter where they are. When they get back to the clubhouse (network), they hand the notebook to the club secretary (the upload service), who copies it into the club archive (track storage). A referee (the segment matcher) checks whether the run went up any of the club's famous hills and writes the times on the wall of records (leaderboards). The notice board (the activity feed) tells every friend what each member did today. A few members want family to follow them live on a long, lonely ride, so they carry a radio (live sharing) that reports their position every few seconds.

The pieces look simple. The hard parts are:

  • The phone is the system of record during the activity. The network can disappear for hours. The app must record, compute and display accurate stats with no server help, and never lose an activity, even if the app crashes or the battery dies.
  • Scale of concurrent activities. On a sunny Sunday morning, millions of people record at the same time. If every phone sent every GPS point to the server, that alone would be millions of writes per second.
  • GPS is noisy. Raw positions jump around by 5–20 metres, drift under trees and between tall buildings, and vanish in tunnels. Distance, pace and elevation must be computed carefully or every runner's numbers will be wrong.
  • Matching tracks to segments. Every uploaded track must be checked against a huge library of user-created segments (a climb, a sprint along a street) to find which ones it covers and how long each took. This is a geometric problem at the scale of millions of uploads per day.
  • Leaderboards with filters. A segment leaderboard ranks each athlete's best time, and users can filter it by age, weight class, gender, friends, clubs and time period.
  • Privacy. A GPS track reveals where someone lives and when they are away from home. A public aggregate map can reveal secret places. Strava learned this in public in 2018, when its global heatmap exposed military bases (Deep Dive 11).

Background: a few terms used in this design#

  • Activity. One recorded workout: a run, a ride, a walk. It has a start time, a sport type, summary stats and a track.
  • Track, stream, sample. The track is the time series recorded during the activity. Each sample (or trackpoint) is one reading: time, latitude, longitude, and optionally elevation, heart rate, cadence and power. A stream is one column of that series, such as all the heart-rate values. Storing data as streams (one array per field) instead of rows compresses far better.
  • GPS fix and accuracy. A fix is one position estimate from the satellite receiver. Phones report a horizontal accuracy (for example "±8 m"), which we use to drop bad points.
  • Elapsed time and moving time. Elapsed time runs from start to finish. Moving time excludes stops (traffic lights, a coffee break). Pace and speed are usually computed from moving time.
  • Auto-pause. The app pauses itself when the athlete stops moving and resumes when they move again.
  • Segment. A user-defined stretch of road or trail with a start and an end, such as "Hawk Hill climb". Every time anyone's activity covers it, that is a segment effort with an elapsed time.
  • KOM, QOM, CR. King or Queen of the Mountain is the fastest time on a cycling segment; Course Record is the fastest on a running segment. A PR (personal record) is an athlete's own best time on a segment.
  • Kudos. Strava's like button.
  • Follower and friend. We use "friend" for anyone the athlete follows; the feed shows activities from the people you follow.
  • Polyline. A compact text encoding of a list of coordinates (each point stored as a small offset from the previous one). It is how we ship map previews.
  • FIT, GPX, TCX. Standard activity file formats. FIT is a compact binary format from Garmin's ecosystem; GPX and TCX are XML. Watches and bike computers produce them, and the app must accept them.
  • Geohash and S2 cells. Ways to cut the Earth into a grid of cells with short ids, so we can index and look up "what is near here" quickly. See Geospatial Indexing and Proximity Search.
  • Beacon or live tracking. Sharing your position in real time with chosen people during an activity, for safety. Strava calls its feature Beacon.

Clarifying Questions#

QuestionAssumed answer
Which activities?Running and cycling with GPS. Other sports (swimming, strength) reuse the same model with fewer streams; indoor activities have no GPS track.
What must happen during an activity?Start, pause, resume, stop and save. While recording, show route on a map, distance, elapsed and moving time, current and average pace or speed, with no network needed.
Must the app work offline?Yes. Recording and on-screen stats must work with no connectivity for the whole activity. Upload happens later, automatically.
How many users and concurrent activities?Design for 150 M registered athletes, 30 M daily active users, 40 M activities uploaded per day, and 10 M concurrent activities at the global peak.
Can people see friends' activities?Yes: a feed of recent activities from people you follow, and a detail page for each activity (map, stats, splits, segment efforts).
Real-time sharing?Yes, opt-in per activity: chosen contacts can follow the athlete's live position, with updates every few seconds. Not every activity is shared live.
Leaderboards?Segment leaderboards (best effort per athlete) with filters, and periodic leaderboards such as "most distance this week" among friends and in clubs.
Who creates segments?Users create them from their own activities; the system matches every new activity against all segments.
External devices?Yes: watches and bike computers upload FIT, GPX or TCX files, directly or via partner integrations.
Privacy?Per-activity visibility (everyone, followers, only me), hidden start and end areas near home, opt-out from aggregate maps.
Out of scope?Friend management, authentication, comments and kudos mechanics, route planning, payments. We mention them only where they touch the core.
Consistency needs?High availability over consistency. A friend may see an activity a few seconds late; a leaderboard may lag by a minute. An athlete's own saved activity must never be lost or duplicated.

Requirements#

Functional requirements#

  1. Record: athletes can start, pause, resume, stop and save runs and rides; the app keeps recording through app restarts and loss of network.
  2. Live stats on the device: during the activity the app shows the route so far, distance, time and pace or speed, accurate and updated every second, computed locally.
  3. Upload and process: saved activities (from the app or from devices) are uploaded, deduplicated, processed into summary stats, splits and map previews, and stored durably.
  4. View activities: athletes can view their own completed activities and those of friends, including the map, stats and segment efforts.
  5. Feed: athletes see a feed of recent activities from the people they follow.
  6. Real-time sharing: an athlete can share a live activity with chosen people, who see the position update every few seconds.
  7. Segments and leaderboards: activities are matched against segments; each segment has a leaderboard of athletes' best efforts, with filters; periodic leaderboards rank athletes by distance or time.

Non-functional requirements#

  • Availability over consistency. Recording never depends on the server. Server-side reads (feeds, activity pages) aim for 99.9% availability; eventual consistency of seconds is fine.
  • Works offline. The full recording flow works with no connectivity; data syncs when the network returns, without user action.
  • Accurate local stats. Distance within about 1–2% of the true distance for a typical outdoor run, updated every second with no network round trip.
  • No lost or duplicated activities. Once the athlete presses Save, the activity survives crashes, reboots and flaky networks, and retries never create duplicates.
  • Scale. 10 M concurrent activities, 40 M uploads per day with peaks of a few thousand per second, and feeds for 30 M daily users.
  • Low latency where people wait. Upload processing a few seconds; feed and activity pages under 200–300 ms at p99 from the API; live-shared positions visible within 5–15 seconds.
  • Battery. Recording an hour should cost a modest share of the battery, so GPS and radio use must be careful.
  • Privacy by default. Private activities never appear in feeds, leaderboards or aggregate maps; hidden start and end zones are respected everywhere a track is shown.

Capacity Estimation#

We use the method from Back-of-the-Envelope Estimation. For a sense of real scale: Strava passed 1 billion uploaded activities in 2017, and by 2020 it had more than 50 million users and more than 3 billion activities. That is roughly 2 billion activities in three years, or about 2 million a day on average at the time. The interview asks for much more (10 M concurrent activities), so we design for a service several times larger and check that the numbers hang together.

Activities and concurrency.

  • Assume 40 M activities per day, with an average recorded duration of about 1.1 hours.
  • Activity-hours per day: 40 M × 1.1 = 44 M. Spread over 24 hours that is about 1.8 M concurrent activities on average.
  • Activity is very peaky. Weekend mornings in Europe and the Americas overlap, good weather multiplies it, and New Year and big races add more. A peak of about 3× average gives 5.5 M. Designing for 10 M concurrent leaves close to 2× headroom for growth and events.

Samples recorded on the device.

  • Phones record about one sample per second. Some watches use "smart recording", which writes a point only when something changes, so their files are smaller.
  • At peak: 10 M activities × 1 sample per second = 10 M samples per second worldwide. This is the number that tells us not to send every sample to the server as it is recorded (Deep Dive 5).
  • A raw sample (time, latitude, longitude, elevation, accuracy, heart rate, cadence, power) is about 40 bytes in memory and about 60 bytes in an on-device SQLite table with overhead. A 1-hour activity is 3,600 samples, about 216 KB on the phone. That is nothing for a modern phone, even for a 12-hour ultra ride (2.6 MB).

Uploads.

  • 40 M uploads per day is about 460 per second on average. Uploads cluster when morning activities end, so assume a peak of 5× the average: about 2,500 uploads per second, and design for 3,000.
  • With delta encoding and compression (Deep Dive 4), a 1-hour track is about 30–50 KB on the wire. Device files are bigger: an hour of FIT data is commonly 100–200 KB before compression. Use 60 KB as the average upload.
  • Ingress: 40 M × 60 KB = 2.4 TB per day, about 28 MB/s on average and about 150 MB/s at peak. Bandwidth is easy; per-upload processing (parsing, cleaning, segment matching) is where the CPU goes.

Storage.

  • Canonical processed streams: about 40 KB per activity compressed, so 40 M × 40 KB = 1.6 TB per day, about 580 TB per year. With a second copy of the original uploaded file (kept for reprocessing and export) at about 60 KB, add 2.4 TB per day, which goes to cheaper cold storage.
  • In total, about 1.5 PB per year of track data before replication. Object storage with erasure coding (about 1.4× overhead) handles this cheaply.
  • Activity metadata (ids, owner, sport, start time, summary stats, privacy, polyline preview): about 2 KB per activity, so 80 GB per day, about 30 TB per year. This fits in a sharded database comfortably.

Segments and efforts.

  • Assume a library of 50 M segments (an assumption for our design). Each is a short polyline with a start, an end and a bounding box, about 2 KB: 100 GB in total. The spatial index over them fits in memory on a handful of machines.
  • Assume an average of 10 segment efforts per activity (a city ride can cross dozens; a treadmill run crosses none). That is 400 M efforts per day, about 4,600 per second on average and about 25,000 per second at peak.
  • An effort row (segment id, athlete id, activity id, start offset, elapsed time, moving time, date, a few attributes) is about 60 bytes: 24 GB per day, about 9 TB per year.

Feeds and reads.

  • 30 M daily users open the feed about 8 times a day: 240 M feed reads per day, about 2,800 per second on average and 10,000 per second at peak.
  • Activity detail views (own and friends'): about 15 per user per day, 450 M per day, about 5,000 per second on average, 20,000 at peak. Each detail view needs the stream data for charts and the map, so the stream store must serve about 20,000 object reads per second at peak (most are cached).
  • Fan-out on write (Deep Dive 10): with an average of 50 followers, 40 M × 50 = 2 B feed inserts per day, about 23,000 per second on average, 100,000 at peak.
  • Kudos: about 10 per activity, 400 M per day, about 4,600 writes per second.

Live sharing.

  • Assume 5% of activities are shared live at peak: 500,000 live sessions.
  • If each sends one batch every 10 seconds (Deep Dive 6), that is 50,000 location batches per second, each a few hundred bytes.
  • Assume two viewers per session, watching on and off: 1 M viewer connections at most, much fewer actually open at any moment.
QuantityAveragePeak / total
Concurrent activities1.8 M10 M (design)
GPS samples recorded on devices1.8 M per second10 M per second (stay on devices)
Uploads460 per second3,000 per second
Track data stored4 TB per dayabout 1.5 PB per year
Segment efforts written4,600 per second25,000 per second
Feed reads2,800 per second10,000 per second
Activity detail views5,000 per second20,000 per second
Feed inserts (fan-out)23,000 per second100,000 per second
Live-share location batches—50,000 per second

The key conclusion: the device does the real-time work, and the server does the heavy work after the activity. Server-side real-time traffic exists only for the small fraction of activities that are shared live.

Core Entities#

  • Athlete: id, name, home country, birth year (for age-group filters), weight class (optional), sex (optional, for leaderboard categories), privacy defaults, hidden zones.
  • Activity: id (generated by the client), athlete id, sport, start time and time zone, elapsed and moving time, distance, elevation gain, average speed, visibility, device, status (uploading, processing, ready), summary polyline.
  • Track (streams): the time series of the activity, stored as columns: time, latlng, altitude, distance, speed, heart rate, cadence, power, temperature, moving flag. Stored in object storage, referenced from the activity.
  • Upload: id, athlete id, file type (FIT, GPX, TCX, app-native), external id from the device, content hash, status and error.
  • Segment: id, name, sport, polyline, start and end points, distance, average grade, bounding box, cell ids for the spatial index, creator, hazardous or flagged state.
  • Segment effort: id, segment id, activity id, athlete id, start index and end index in the track, elapsed time, moving time, start date, and an optional average power and heart rate.
  • Leaderboard entry: for each (segment, athlete), the best effort id and its time; plus periodic totals per athlete (distance this week).
  • Follow: follower id, followee id, created at.
  • Feed item: owner (the viewer), activity id, author id, created at.
  • Live session: id, activity id, athlete id, allowed viewers, last known position, sequence number, started and expires at.

API Design#

During recording the app needs no server calls. Everything else is plain HTTPS with JSON, plus a streaming channel for live viewers.

# Upload (app or device file). The client generates activity_id once, at Start.
POST /v1/uploads
  { "activity_id": "a_01HV...", "file_type": "app_v3", "sha256": "...", "bytes": 48213 }
  -> 201 { "upload_id": "u_9f2", "put_url": "https://...signed...", "chunk_bytes": 262144 }
PUT  <put_url>  (resumable, chunked; Content-Range)
POST /v1/uploads/u_9f2/complete      -> 202 { "status": "processing" }
GET  /v1/uploads/u_9f2               -> { "status": "ready", "activity_id": "a_01HV..." }
 
# Activities
GET  /v1/activities/{id}             -> summary, polyline, splits, segment efforts
GET  /v1/activities/{id}/streams?types=latlng,altitude,heartrate&resolution=medium
PATCH /v1/activities/{id}            { "title": "Sunday long run", "visibility": "followers" }
 
# Feed
GET  /v1/feed?cursor=eyJ0Ijo...&limit=20
 
# Live sharing
POST /v1/live-sessions               { "activity_id": "...", "viewer_ids": ["..."] }
  -> { "session_id": "ls_77", "share_url": "...", "write_token": "..." }
POST /v1/live-sessions/ls_77/points  { "seq": 412, "points": [[t, lat, lng, alt], ...] }
GET  /v1/live-sessions/ls_77?since_seq=400          (poll)
GET  /v1/live-sessions/ls_77/events                 (SSE, Last-Event-ID resumes)
 
# Segments and leaderboards
POST /v1/segments                    { "activity_id": "...", "start_index": 812, "end_index": 1430 }
GET  /v1/segments/{id}/leaderboard?filter=friends&age=35_44&period=this_year&cursor=...
GET  /v1/leaderboards/distance?scope=club:c_12&period=week

Design notes:

  • The client creates the activity id (a ULID or UUID) when the athlete presses Start. Every retry of the upload carries the same id, so the server can treat it as an idempotency key (see Idempotency and Safe Retries). A content hash catches the same file uploaded twice under different ids, for example once by the watch and once by hand.
  • Upload is asynchronous. The upload call only stores the bytes and queues the job. The client then polls the status or gets a push. Strava's public API works the same way: a file upload is queued, the client is told to poll no more than once a second, and Strava says mean processing time is under 2 seconds; segment matching can finish after the activity is already visible.
  • Streams are fetched separately from the activity summary, with a resolution parameter. A feed card needs only the polyline; the detail page loads medium-resolution streams for charts; analysis tools load full resolution.
  • Live points are batched and carry a sequence number so that retries and reordering are harmless.
  • Cursors, not offsets for feeds and leaderboards, so pages stay stable while new data arrives.

High-Level Design#

We build the design one requirement at a time, then combine everything into the full picture.

1) Start, pause, stop and save an activity#

Everything in this step happens on the device. The app has a recorder that turns location and sensor callbacks into samples, a local database (SQLite or the platform equivalent) that stores them as they arrive, and a sync queue that uploads finished activities when the network allows.

  • Start creates an activity row in the local database with a client-generated id and the state recording.
  • Every sample is written to the local database within a second or two (batched in small chunks), so a crash or a dead battery loses at most a few seconds.
  • Pause and resume are just events in the same local log. They also stop and start the moving-time clock.
  • Stop ends recording. Save marks the activity as ready_to_upload and adds it to the sync queue. Discard deletes it locally.
  • The recorder runs as a foreground service on Android and as a background location session on iOS, so it keeps running with the screen off.

Deep Dive 1 covers the state machine, crash recovery and offline behaviour in detail.

2) Show route, distance and time during the activity#

The live stats are computed locally from the same samples. There is no server call at all. Each new sample that passes the filters adds the distance from the previous accepted point (great-circle distance, Deep Dive 2), updates elapsed time from the device clock and moving time from the auto-pause state, and recalculates pace from a rolling window of the last 20–30 seconds. The map draws the recorded points on top of cached map tiles; if tiles are not cached (no network), the app still draws the line on a blank background.

This choice comes straight from two requirements: the app must work offline, and stats must be accurate and current. A server round trip every second would fail both.

3) Upload and process a saved activity#

When the network is available, the sync queue uploads the activity. The upload service stores the raw bytes in object storage and puts a job on a queue. A processing pipeline then parses the file, cleans the track, computes summary stats, writes the canonical streams and the activity record, and emits an activity_created event. Segment matching, feed fan-out and leaderboard updates all hang off that event.

The client's activity id makes the whole chain idempotent: re-uploading the same activity finds the existing record instead of creating a second one. Deep Dive 3 covers resumable uploads, duplicates and device files; Deep Dive 12 covers the pipeline's reliability.

4) View your own and your friends' activities#

An activity service serves activity pages. It reads the activity record (summary, polyline, privacy) from the activity database, checks that the viewer may see it (owner, follower, or public), and returns a page that links to the streams. Streams are fetched from object storage through a cache or CDN at the resolution the client asks for.

Privacy is enforced on the server for every read. Hidden start and end zones are applied when the polyline and streams are generated for anyone other than the owner (Deep Dive 11).

5) The activity feed#

The feed shows recent activities from the people you follow. Because most athletes have tens to a few hundred followers, we fan out on write: when an activity is created, a fan-out worker pushes a small item (activity id, author id, time) into each follower's feed list. Reading a feed is then a single range read plus a batch lookup of activity summaries. Athletes with huge followings (professional cyclists) are handled differently (Deep Dive 10).

6) Share an activity live#

When an athlete turns on live sharing, the app starts a live session and sends small batches of positions every few seconds whenever it has signal. A live location service keeps the latest positions per session in memory (Redis), and viewers either poll for changes or hold an SSE connection that pushes new points. If the athlete's phone loses signal, viewers see "last seen 4 minutes ago" and the app sends the backlog when it reconnects.

Deep Dive 6 compares polling, SSE and WebSockets for this and explains catch-up after disconnections.

7) Segments and leaderboards#

The segment matcher consumes activity_created events, finds candidate segments near the track using a spatial index over segment start and end points, checks each candidate precisely against the track, and writes segment efforts. A leaderboard service keeps, for each segment, every athlete's best effort, sorted by time, and answers filtered queries. Periodic leaderboards (distance this week) are fed from per-athlete totals.

Deep Dives 7, 8 and 9 cover matching, segment leaderboards and periodic leaderboards.

The full high-level design#

Components:

  • Recorder, local database and sync queue (device): record samples from GPS and sensors, filter them, store them durably on the device, compute live stats, and upload saved activities when the network allows.
  • Load balancer and API gateway: TLS, authentication, rate limits per user and per partner app, routing to services.
  • CDN: map tiles (so the app can cache them for offline areas), public activity images, and cached stream files.
  • Upload service: accepts resumable uploads, deduplicates by activity id and content hash, stores original files, queues processing.
  • Activity processor: parses FIT, GPX, TCX and the app's own format; cleans and resamples the track; computes stats, splits and the polyline; writes canonical streams and the activity record; emits events.
  • Event log (Kafka): the backbone between the write path and everything that happens after upload; replayable for reprocessing.
  • Live location service, pub/sub and realtime gateway: accept batched live points, keep the latest state in Redis, and push or serve updates to authorised viewers.
  • Segment matcher: finds which segments each activity covers and how long each took.
  • Leaderboard service: maintains best efforts per athlete per segment and periodic totals; answers filtered and paginated queries.
  • Feed fan-out and feed service: push activity ids into followers' feeds and serve feeds with hydrated summaries.
  • Analytics, heatmap and safety jobs: offline aggregation (heatmaps, city reports) and checks for impossible speeds or vehicle-assisted efforts.
  • Data stores: a sharded relational or wide-column activity database, object storage for files and streams, a feed store, Redis for hot state, a segment database with a spatial index, and a wide-column effort store.

Key Flows#

Flow 1: record a run with no signal, upload it later#

The local copy is kept until the server confirms the activity is processed. If the upload is interrupted, the app resumes from the last acknowledged chunk; if the app is killed, the sync queue picks the job up again on the next launch or when the OS grants background time.

Flow 2: a watch file arrives twice#

Two checks catch duplicates: the exact content hash, and an overlap check (same athlete, same sport, start times within a minute and most timestamps overlapping), which catches the same workout recorded by both phone and watch. Strava's upload API returns a "duplicate of activity" error in this situation; our design does the same.

Flow 3: a friend follows a live ride and briefly loses connection#

Flow 4: matching a new ride to segments#

Flow 5: open the feed#

Data Model#

We store three very different kinds of data:

  • Activity metadata is small, structured, and read by id or by "this athlete's activities, newest first". A sharded relational database or a wide-column store both work; we use PostgreSQL sharded by athlete id for the metadata, because owners edit titles and privacy, and transactions help when an activity, its upload record and its privacy settings change together.
  • Tracks are large, immutable after processing (except reprocessing), and read whole. They live as compressed objects in object storage.
  • Segment efforts, feeds and live points are high-volume, append-mostly, and read by one key in time order. These suit a wide-column store (Cassandra, ScyllaDB, Bigtable) or Redis for the hot part.

Segments, their index cells and their leaderboards:

The activity table, sharded by athlete_id so an athlete's list of activities is one shard and one index range:

CREATE TABLE activities (
  activity_id      TEXT PRIMARY KEY,          -- client-generated ULID
  athlete_id       BIGINT      NOT NULL,
  sport            TEXT        NOT NULL,      -- run, ride, walk ...
  start_time       TIMESTAMPTZ NOT NULL,
  tz               TEXT        NOT NULL,
  elapsed_s        INT, moving_s INT,
  distance_m       REAL, elev_gain_m REAL,
  visibility       TEXT        NOT NULL DEFAULT 'followers',
  status           TEXT        NOT NULL,      -- processing, ready, failed
  summary_polyline TEXT,                      -- privacy-trimmed preview
  stream_key       TEXT,                      -- object storage key
  content_sha256   BYTEA,
  device           TEXT,
  created_at       TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX ON activities (athlete_id, start_time DESC);
CREATE UNIQUE INDEX ON activities (athlete_id, content_sha256);

Segment efforts in a wide-column store, written twice in two shapes because they are read in two ways:

-- Cassandra-style CQL. Efforts of one segment, bucketed by year so
-- a famous climb does not become one enormous partition.
CREATE TABLE efforts_by_segment (
  segment_id bigint, year int, effort_id bigint,
  athlete_id bigint, activity_id text, elapsed_s int, start_date date,
  PRIMARY KEY ((segment_id, year), effort_id)
);
 
-- Efforts of one athlete on one segment, for "my efforts" and PR history.
CREATE TABLE efforts_by_athlete_segment (
  athlete_id bigint, segment_id bigint, start_date date, effort_id bigint,
  elapsed_s int, activity_id text,
  PRIMARY KEY ((athlete_id, segment_id), start_date, effort_id)
) WITH CLUSTERING ORDER BY (start_date DESC, effort_id DESC);

This is query-driven modelling: we start from the reads ("all efforts on this segment this year", "my efforts on this segment") and shape one table per read, duplicating data on purpose. The year bucket in the partition key follows the same idea as bucketing chat messages by time window: it keeps every partition bounded even for segments that get thousands of efforts a day. For more on this style see Apache Cassandra in Practice and Data Modeling.

The track object itself is a small columnar file (Deep Dive 4): a header with the activity id, format version, sample count and which streams are present, then one compressed block per stream (time, latlng, altitude, distance, heart rate, cadence, power, moving flag).

DataStoreWhy
Activity metadata, uploads, privacyPostgreSQL (or MySQL with Vitess), sharded by athlete idEdited by owners, needs uniqueness and small transactions; read by id and by athlete
Original files and canonical streamsObject storage (S3, GCS) with lifecycle tiersLarge, immutable, read whole; cheap per GB; CDN-friendly
Segments and segment geometryPostgreSQL with PostGIS, plus an in-memory cell index in the matcherRich geometry queries for creation and editing; fast lookups for matching
Segment effortsCassandra, ScyllaDB or BigtableHundreds of millions of writes a day, read by key ranges
Segment leaderboards (hot)Redis sorted sets, rebuilt from the effort storeRank and range queries in microseconds
FeedsRedis lists for recent items, Cassandra for longer historyFan-out writes at 100,000 per second, range reads per viewer
Follow graphSharded relational or wide-column, both directions"Who do I follow" and "who follows me" lookups
Live pointsRedis with a TTL (hours)Small, hot, short-lived
EventsKafkaDecouples processing steps; replay for reprocessing
Aggregates and heatmapsData lake (Parquet) and batch jobsBig scans, privacy filtering before publishing

For the general method of matching access patterns to stores, see Choosing a Database: A Decision Guide.

Deep Dives#

1. Recording on the device, and working offline#

This is the first deep dive interviewers usually ask for: "the runner is in the mountains with no signal for three hours. What happens?" The answer shapes the whole design, so it is worth walking through the options.

Bad: stream every sample to the server and compute stats there. The app sends each GPS fix as it arrives and the server returns distance and pace. It fails the moment the signal drops, which on trails and in tunnels is constantly. It also burns battery (the cellular radio stays in a high-power state for several seconds after every transmission, so many tiny sends cost far more energy than one larger send), and it creates 10 M writes per second at peak for data nobody is reading yet.

Good: keep samples in memory and upload at the end. This works offline and is cheap. But if the app crashes, the OS kills it to reclaim memory, or the phone dies at kilometre 38 of a marathon, the whole activity is gone. Losing someone's marathon is the worst bug this product can have.

Great: a durable local log plus a sync queue (local-first). The phone is the system of record during the activity. Every few samples are appended to a local database, the live stats are computed from the same stream, and a separate sync queue uploads finished activities whenever the network allows. The server only ever sees complete, saved activities (plus optional live-sharing batches, Deep Dive 6).

The recording state machine

The state lives in the local database, not only in memory. When the app starts, it looks for any activity whose state is Recording or Paused. If the last sample is recent (say under 30 minutes old) it resumes recording, with the gap marked as a pause; otherwise it moves the activity to Stopped and asks the athlete to save or discard. Either way, nothing recorded before the crash is lost.

Writing samples durably without killing the battery

Writing one row per sample means one transaction per second for hours. On flash storage each commit has a cost (journal writes, fsync). A good compromise:

  • Keep a small in-memory buffer and flush it as one chunk every 5–10 samples (or every few seconds), in a single transaction. A crash loses at most that buffer.
  • Use SQLite in write-ahead-log mode, so appends are sequential and readers (the UI) do not block the writer.
  • Store each chunk compactly: integer microdegrees, relative timestamps, small deltas. An hour is a few hundred KB.
  • Never rewrite old chunks during the activity. Pauses, laps and edits are events appended to the same log. The final activity is derived from the log when the athlete saves.
-- On-device schema (SQLite)
CREATE TABLE local_activity (
  activity_id TEXT PRIMARY KEY,      -- ULID generated at Start
  sport TEXT NOT NULL,
  state TEXT NOT NULL,               -- recording, paused, stopped, saved, uploading, uploaded
  started_at_ms INTEGER NOT NULL,
  upload_attempts INTEGER NOT NULL DEFAULT 0,
  server_upload_id TEXT
);
CREATE TABLE sample_chunk (
  activity_id TEXT NOT NULL,
  chunk_no INTEGER NOT NULL,
  first_ts_ms INTEGER NOT NULL,
  payload BLOB NOT NULL,             -- 5-10 encoded samples
  PRIMARY KEY (activity_id, chunk_no)
);
CREATE TABLE activity_event (
  activity_id TEXT NOT NULL, ts_ms INTEGER NOT NULL,
  kind TEXT NOT NULL                 -- pause, resume, lap, autopause, autoresume
);

Keeping the recorder alive

Mobile operating systems kill background apps to save power. The recorder must use the platform's sanctioned mechanisms:

  • Android: a foreground service with a visible notification and the location foreground-service type. Some manufacturers add aggressive battery savers that still kill apps, so the app should detect gaps in samples and guide users to exempt it.
  • iOS: background location updates enabled for the session, with the app declared as a location app. The OS delivers locations even with the screen off.
  • Watches: often the watch is the recorder and the phone only relays the file. The same local-first rules apply on the watch.

Clocks and time

Use the monotonic clock for elapsed and moving time, because the wall clock can jump (time-zone changes on a long ride, network time corrections). Use the GPS or wall time only to stamp the start time and each sample. Store the athlete's time zone at start, so "Morning Run" and weekly totals are computed in local time.

Offline maps

The line is drawn from local samples, so the route always shows. Map tiles need the network unless they were cached. Apps can let athletes download a region in advance (vector tiles compress well: a city region is tens of MB). With no tiles, show the line on a plain grid; the stats are unaffected.

The sync queue

  • Saved activities are uploaded in order, one at a time or a few in parallel, with exponential backoff and jitter on failure.
  • The queue is persistent and survives app restarts. On Android it can be driven by WorkManager with a "network connected" constraint; on iOS by background URL sessions, which let the OS finish the upload even if the app is suspended.
  • Every attempt sends the same activity id, so retries are idempotent (Deep Dive 3).
  • The local copy is deleted only after the server confirms the activity is processed, and even then can be kept for a few days as a safety net.

Trade-offs

ChoiceBenefitCost
Local-first recordingWorks offline, no data loss, no server load during activitiesTwo implementations of stats (device and server) that must agree; app bugs can corrupt data and need careful migrations
Chunked durable writesCrash loses only secondsSlightly more battery and storage writes than a pure memory buffer
Upload only on saveMassive reduction in server writesFriends do not see progress unless live sharing is on

What a strong candidate says: "The device is the source of truth until the activity is saved. I persist samples in small chunks, compute stats locally, and upload the finished activity with a client-generated id so retries are safe. The server only gets real-time data for the few activities shared live."

2. Turning noisy GPS into accurate distance, pace and elevation#

The requirement "accurate local statistics" is mostly a signal-processing problem.

What goes wrong with raw GPS

  • Noise. Under open sky a phone's position error is typically 3–10 m. In "urban canyons" between tall buildings, reflections (multipath) can push errors to 20–50 m. Under heavy tree cover accuracy drops too.
  • Cold start and drift. The first fixes after Start can be hundreds of metres off until the receiver has a good lock. Recording should wait for a fix with accuracy under about 20 m, or mark early points as low quality.
  • Gaps. Tunnels and bridges cause missing points.
  • Jitter inflates distance. Distance is the sum of the lengths between consecutive points. Noise that moves the points sideways makes the path zig-zag, and a zig-zag line is always longer than the true line. At low speed, this effect dominates.

A worked example shows why. Suppose a walker moves 1.4 m per second and we sample once per second. If each point had independent noise of 3 m on each axis, the difference between two consecutive points would have noise with variance 2 × 3² = 18 m² per axis. The measured step would be roughly the square root of (1.4² + 2 × 18) ≈ 6.2 m instead of 1.4 m: a walk would look four times longer than it was. Real GPS errors are strongly correlated from one second to the next (the error wanders slowly), so the real inflation is much smaller, often a few percent. But at low speeds and in poor signal it becomes large, which is why stationary phones "walk" and why every serious tracker filters.

The filtering pipeline

  1. Accuracy gate. Drop fixes whose reported horizontal accuracy is worse than a threshold (for example 30–50 m), or keep them flagged for display only.
  2. Speed gate. Drop points that imply an impossible speed for the sport: more than about 12 m/s for running (faster than an elite sprinter) or 30 m/s for cycling. These are usually multipath jumps.
  3. Smoothing. A Kalman filter combines a simple motion model ("the athlete keeps roughly the same velocity") with each new measurement, weighting each by its uncertainty. When the reported accuracy is poor, the filter trusts its prediction more; when accuracy is good, it follows the measurement. The output is a smoother track with a sensible estimate of speed.
  4. Minimum movement. Only add distance when the filtered position has moved more than a small threshold, which suppresses jitter when the athlete is standing still at a traffic light.
  5. Auto-pause. If the filtered speed stays below a threshold (for example 0.5 m/s for running, 1 m/s for cycling) for a few seconds, enter auto-pause; leave it when speed stays above a slightly higher threshold. The two thresholds (hysteresis) stop the state from flickering.

A one-dimensional version of the Kalman update, applied to latitude and longitude separately (in metres), shows the idea:

// Constant-position Kalman filter per axis; q = process noise per second (m^2/s).
type Axis = { x: number; p: number }; // estimate (m) and its variance (m^2)
 
function kalmanStep(s: Axis, z: number, accuracyM: number, dtS: number, q = 3): Axis {
  // Predict: uncertainty grows with time since last fix.
  const pPred = s.p + q * dtS;
  // Measurement variance from the reported accuracy.
  const r = accuracyM * accuracyM;
  // Gain: how much to trust the new measurement (0..1).
  const k = pPred / (pPred + r);
  return { x: s.x + k * (z - s.x), p: (1 - k) * pPred };
}

With a reported accuracy of 5 m (r = 25) and a predicted variance of 10, the gain is 10 / 35 ≈ 0.29, so the estimate moves 29% of the way toward the new point. With accuracy 50 m (r = 2,500), the gain falls to 0.004 and the bad point barely moves the track. Production filters also model velocity (a constant-velocity state per axis), which tracks a moving athlete with less lag.

Distance on a sphere

For short steps we compute the haversine (great-circle) distance between consecutive filtered points:

  • a = sin²(Δφ/2) + cos φ₁ · cos φ₂ · sin²(Δλ/2)
  • d = 2R · atan2(√a, √(1 − a)), with R ≈ 6,371 km and φ, λ in radians.

Worked example: two points 0.0001° of latitude apart (same longitude). Δφ = 0.0001 × π / 180 ≈ 1.745 × 10⁻⁶ rad, so d ≈ R × Δφ ≈ 6,371,000 × 1.745 × 10⁻⁶ ≈ 11.1 m. One unit in the fifth decimal place of latitude is about 1.1 m; the seventh is about 1.1 cm. That is why we store coordinates as integers in units of 10⁻⁷ degrees (Deep Dive 4).

Over a 10 km run, the difference between haversine and a flat-Earth approximation is negligible; what matters is the noise handling above. For long rides at high latitudes, the flat approximation drifts, so use haversine everywhere for simplicity.

Pace

Instantaneous pace from 1-second steps is jumpy. The display uses a rolling window (the last 20–30 seconds of moving time) and the average pace uses total distance over moving time. The two numbers on screen answer different questions ("how fast am I going now" and "how fast have I gone overall").

Elevation

  • GPS altitude is poor: vertical error is typically 1.5–3 times the horizontal error.
  • A barometric altimeter (in most phones and watches) is very precise for relative changes but drifts with weather; it must be calibrated at the start, using GPS altitude or a known height.
  • Elevation gain is the sum of climbs, so noise again inflates it. Apply a threshold: only count a climb once altitude has risen by more than 2–3 m from the last low point (hysteresis again).
  • On the server, we can replace or correct the altitude stream with a digital elevation model (DEM), a global grid of terrain heights. Public DEMs such as SRTM have about 30 m resolution, which is good for running and cycling on terrain but wrong on bridges and in tunnels, so the server prefers barometric data when the device has it.

Server recomputation

When the activity is uploaded, the server recomputes stats from the streams with the same (versioned) algorithms. The app shows the device's numbers during the activity and the server's numbers afterwards. They must be close; if they differ by more than a percent or two, users notice and complain. Keeping one shared library for the filters (compiled for both mobile platforms and the server) avoids this drift.

Simplifying the route for display

A 3,600-point track is far more than a feed card needs. The Ramer–Douglas–Peucker algorithm simplifies a line: keep the two end points, find the point farthest from the straight line between them, and if it is farther than a tolerance ε (for example 5–10 m), keep it and recurse on the two halves; otherwise drop everything in between. It typically reduces a run to 100–300 points with no visible change at feed-card size. The average running time is O(n log n); the worst case is O(n²) for adversarial shapes. The simplified line is then encoded as a polyline string (Deep Dive 4).

3. Uploading, deduplicating and accepting device files#

Making uploads reliable on bad networks

A finished run is usually 30–50 KB compressed, small enough to send in one request. Long rides with high-rate sensor data, or activities with photos, can be several MB. The upload has to survive a train going into a tunnel halfway through.

  • Bad: one big POST with retries from scratch. It works for small files but wastes data and time on poor links, and the app can be suspended mid-request.
  • Good: upload to object storage with a signed URL. The upload service issues a pre-signed URL; the app sends bytes directly to object storage, so our API servers do not hold slow connections. See Pattern: Handling Large Files and Blobs.
  • Great: resumable, chunked upload plus an explicit "complete" call. The app sends 256 KB chunks with Content-Range. After a failure it asks how many bytes the server has and continues from there. Object stores provide this natively (S3 multipart upload, GCS resumable uploads), and protocols such as tus standardise it. For tiny tracks the app uses a single PUT; the same code path handles both.

Exactly-once activities with at-least-once delivery

Networks deliver "at least once": the app may send the same upload three times because responses were lost. We make the effect "exactly once":

  1. The activity id is generated on the device at Start and stored with the activity. Every upload attempt carries it.
  2. The upload service does an insert-if-absent keyed by activity_id. A second attempt finds the existing row and returns its current status (uploading, processing, ready) instead of creating a new one.
  3. The processing job is keyed by activity id too, so if two jobs run (a retry after a timeout), the second sees the activity already ready and does nothing, or overwrites with identical output.
  4. Downstream consumers (segment matcher, feed fan-out, totals) are idempotent by activity id (Deep Dive 12).
-- Idempotent creation of an upload record
INSERT INTO uploads (activity_id, athlete_id, sha256, status, created_at)
VALUES ($1, $2, $3, 'uploading', now())
ON CONFLICT (activity_id) DO NOTHING
RETURNING upload_id;
-- No row returned: read the existing row and return its status to the client.

Duplicates from different sources

The same workout often arrives twice: from the watch maker's cloud and from a manual file upload, or from both the phone app and the watch. Two checks:

  • Exact duplicates: the same file content. A unique index on (athlete_id, content_sha256) rejects it.
  • Overlapping recordings: different files of the same workout. Look up the athlete's activities that start within a few minutes and overlap in time by more than, say, 80%. If found, mark the new one as a duplicate, or keep the one with better data (a watch with a heart-rate strap beats a phone in a pocket) and let the athlete choose.

Accepting device files

Real fitness platforms must read the formats that devices produce. Strava's developer documentation lists FIT, TCX and GPX (plus a limited JSON format for strength workouts), says new formats are not planned, and requires a timestamp on every trackpoint, with position, elevation and heart rate optional. Our design follows the same rules.

  • FIT (Flexible and Interoperable Data Transfer) is a compact binary format. A FIT file is a sequence of definition messages (which describe the layout of a message type: which fields, which sizes) and data messages that follow that layout. An activity file contains, among others, record messages (timestamp, position, altitude, speed, heart rate, cadence, power, temperature), lap messages, session messages (sport, totals) and event messages (timer start and stop). Because the layout is declared once and then reused, each record is only a few dozen bytes.
  • GPX (GPS Exchange Format) 1.1 is XML. Base GPX has positions, elevation and time; heart rate, cadence and temperature come from extensions such as Garmin's track point extension. Parsing XML is slower and the files are larger, but GPX is universal.
  • TCX (Training Center XML) is Garmin's XML format, which adds laps and power through extensions.

The parser normalises all of them into the same internal stream model. It must be strict about structure but tolerant of vendor quirks (missing fields, duplicated timestamps, clock jumps), and it must protect the platform: limits on file size, number of points and XML depth stop a malicious file from exhausting memory.

Asynchronous processing and status

The upload call returns quickly with processing. The client then polls the status endpoint or waits for a push notification. Strava's public API documents the same shape: files are queued for processing, clients should poll no more often than once per second, the mean processing time is under 2 seconds, and segment matching may finish after the activity itself is ready. That last detail matters: we make the activity visible as soon as its stats are ready and attach segment results when they arrive, instead of making the athlete wait for the slowest step.

Partner integrations and our own API

Watches and bike computers typically sync to their maker's cloud, which then pushes the activity to us through a partner API (OAuth 2.0 authorisation by the athlete, then server-to-server pushes). In the other direction, third-party apps (coaching tools, nutrition apps) read athletes' activities from our API.

Strava's public API is a useful model of how to protect such a platform:

  • Rate limits per application, with a short window and a daily window. The default is 200 requests per 15 minutes and 2,000 per day overall, with a separate, lower limit for read ("non-upload") endpoints. The 15-minute windows reset at fixed times (on the hour and at :15, :30, :45), the daily window at midnight UTC, and requests over the limit get 429 Too Many Requests. Usage is reported in response headers so clients can slow down before they hit the wall. See Rate Limiting and Throttling.
  • Webhooks instead of polling. An application registers a single subscription and receives a POST when an athlete's activity is created, updated (title, type, privacy) or deleted, or when an athlete revokes access. The event carries only ids and the changed fields; the application fetches details if it needs them. The receiver must answer with 200 within two seconds, and delivery is retried up to three attempts in total, so receivers should queue the work and process it asynchronously. Subscription setup verifies the callback URL with a challenge that the receiver must echo back.
  • Privacy flows through the API. For an app without permission to see private activities, a change from public to "only you" arrives as a delete event, and the reverse as a create event.

The same ideas apply inside our system: thin events with ids, idempotent receivers, and a clear contract on acknowledgement time and retries.

4. Storing tracks: the data model for time series#

Tracks are the largest data in the system (about 1.5 PB per year). The choice of storage shape decides cost, read latency and how easy it is to reprocess.

Option comparison

  • Bad: one row per sample in a relational database. 40 M activities × about 4,000 samples = 160 B rows per day, about 1.9 M inserts per second on average. Each row carries per-row overhead (tens of bytes) and index entries. Reads of a whole track touch thousands of rows. This is the most expensive possible layout for data that is always read whole.
  • Good: a time-series database (TimescaleDB, InfluxDB, a wide-column table keyed by activity id with a time clustering column). These handle high write rates and compress well, and they suit queries across many series ("average heart rate of all my runs this year"). But most reads here are "give me this one activity's streams", and analytics across activities happen in batch jobs anyway. See Time-Series Databases.
  • Great: one immutable, compressed, columnar object per activity in object storage, with the metadata row in the activity database pointing to it. A read is one GET of 20–50 KB, easy to cache at a CDN. Writes are one PUT per activity. Storage is the cheapest per GB, with lifecycle tiers. Reprocessing writes a new version next to the old one.

Inside a track object

Store streams (columns), not rows. Each stream is encoded to suit its data, then compressed:

StreamRaw typeEncodingTypical size per sample
timeseconds since startdelta, then run-length (mostly 1, 1, 1...)well under 1 byte
latlngint32 in 10⁻⁷ degrees (about 1.1 cm)delta, zigzag, varint3–4 bytes for both
altitudeint in decimetresdelta, zigzag, varintabout 1 byte
heart rateuint8 bpmdelta, zigzag, varintabout 1 byte
cadenceuint8delta or run-lengthunder 1 byte
poweruint16 wattsdelta, zigzag, varint1–2 bytes
movingbooleanrun-lengthalmost nothing
distancederivednot stored, recomputed from latlng0

Why deltas. Consecutive points are close. A runner at 3 m/s moves about 2.7 × 10⁻⁵ degrees per second, which is 270 units of 10⁻⁷ degrees. Storing the difference (270) instead of the absolute value (378,346,100) cuts the number from 4 bytes to 2. Zigzag encoding maps signed differences to unsigned numbers (0, −1, 1, −2, 2 become 0, 1, 2, 3, 4) so small negative numbers also stay small. Varint encoding stores small numbers in fewer bytes (7 bits per byte plus a continuation bit).

Worked size for a 1-hour run with heart rate and cadence:

  • latlng: 3,600 × 4 bytes ≈ 14.4 KB
  • altitude: 3,600 × 1 byte ≈ 3.6 KB
  • heart rate: 3.6 KB; cadence: about 2 KB; time and moving: under 0.1 KB
  • total about 24 KB before a general-purpose compressor such as zstd, about 16–20 KB after.

That matches the capacity estimate (30–50 KB per upload including power, temperature and file overhead). Compared with 3,600 rows of about 100 bytes in a database (360 KB plus indexes), the columnar object is more than 10 times smaller.

Several resolutions

Most readers do not need every point:

  • Full resolution for analysis tools, exports and reprocessing.
  • Medium (about 1,000 points) for charts on the activity page, downsampled by time or distance.
  • Low (100–300 points, simplified with Ramer–Douglas–Peucker) for maps on feed cards, encoded as a polyline string stored directly in the activity row.

Strava's API reflects this: activity summaries carry a summary_polyline, and the streams endpoint returns one array per stream type with a resolution field and the original_size.

Polyline encoding

The encoded polyline format (designed by Google for maps) turns a list of coordinates into a short ASCII string:

  1. Multiply each coordinate by 10⁵ and round (about 1.1 m precision).
  2. For every point after the first, take the difference from the previous point.
  3. Shift the signed value left by one bit; if it was negative, invert all bits. (This is zigzag encoding again.)
  4. Split into 5-bit chunks, lowest bits first. Set the 0x20 bit on every chunk except the last.
  5. Add 63 to each chunk so it lands in printable ASCII.

Worked example (our own): three points near Oakland, (37.83461, −122.25209), (37.83492, −122.25174), (37.83530, −122.25150). The first point encodes as iq|eF and pjdiV. The second point's latitude difference is +31 units: shifted left it is 62 (binary 111110), which splits into the chunks 30 and 1; with the continuation bit the first becomes 62; adding 63 gives 125 and 64, which are the characters } and @. Its longitude difference +35 encodes as eA. The third point gives kA and o@. The whole line is iq|eFpjdiV}@eAkAo@: 18 characters for three points, and each further nearby point costs only about 4–6 characters.

Lifecycle, reprocessing and deletion

  • Tiers. Recent tracks (last 30–90 days) are read most, so they sit in the standard tier and in caches. Older ones move to infrequent-access tiers. The original uploaded files, needed only for reprocessing and export, go to archive tiers. See Data Lifecycle, Tiering and Retention.
  • Reprocessing. When the cleaning or elevation algorithm improves, a batch job reads originals, writes new canonical objects with a higher format_version, and switches the pointer. Because objects are immutable, a bad version can be rolled back by switching the pointer back.
  • Deletion. Deleting an activity deletes its metadata, all its objects (all versions), efforts, feed items and cached copies. An event drives the clean-up so nothing is missed. For a full account deletion, keys per athlete (crypto-shredding) make sure even backup copies become unreadable.
  • Analytics copies. Aggregate jobs (heatmaps, city reports) should not read millions of small objects. A nightly job writes privacy-filtered points into a data lake in Parquet, partitioned by date and region.

5. Scaling to 10 million concurrent activities#

The number "10 M concurrent activities" sounds frightening until we ask what the server actually has to do for each of them while it is in progress. With the local-first design the answer is: nothing, unless the activity is shared live. The load moves to two other places: the upload wave at the end of activities and the live-sharing subset.

Three options for the in-progress data

ApproachServer writes at 10 M concurrentWorks offlineBatteryVerdict
Send every sample as it is recorded10 M per secondNoWorstBad
Send a batch every minute for every activityabout 170,000 requests per second, 10 M samples per secondPartly (needs a backlog)MediumGood, but wasteful: almost nobody reads the data
Upload once on save; stream only shared activitiesabout 3,000 uploads per second plus 50,000 small batches per second for 5% sharedYesBestGreat

The great option is also simpler to operate: the expensive real-time path serves only people who asked for it.

Absorbing the upload wave

Sunday mornings, public holidays and big races create waves of uploads: thousands of runners of a city marathon finish within a few hours and upload together. The write path is built as a queue-based pipeline, so a wave becomes a backlog instead of an outage:

  • The upload service does very little work (store bytes, insert a row, enqueue), so it stays fast even when processing falls behind.
  • Each stage scales independently on consumer lag. Parsing and stats need about 50–200 ms of CPU per activity; segment matching is heavier (about 100–500 ms for a long ride in a dense city). At 3,000 uploads per second, that is roughly 600 cores for processing and 900–1,500 cores for matching at peak, which an autoscaled fleet handles.
  • Priorities. A runner waiting to see their run matters more than a partner backfilling a year of history or a reprocessing job. Separate queues (or priority lanes) for interactive uploads, partner bulk syncs and reprocessing keep the interactive path fast. Bulk work runs in the gaps.
  • Partitioning by athlete id keeps one athlete's uploads, edits and deletes in order, which simplifies totals and feeds.

Data stores at peak

  • Activity database: about 3,000 inserts per second and 20,000 reads per second (most served from cache). Sharded by athlete id across, say, 32–64 PostgreSQL primaries, each sees a few hundred writes per second, far below its limits. See Partitioning and Sharding.
  • Effort store: 25,000 writes per second at peak, each about 60 bytes, written to two tables: a small Cassandra or ScyllaDB cluster handles this easily. See Pattern: Scaling Writes.
  • Feed store: up to 100,000 small inserts per second during the fan-out wave; Redis cluster for the hot recent items, with writes batched per follower shard.
  • Object storage: 3,000 PUTs per second and 20,000 GETs per second (mostly absorbed by caches). Object stores scale to this level per bucket prefix if key names are spread (for example, prefix the key with a hash of the activity id rather than a date).

Hot spots that concurrency creates

  • A race. 30,000 marathon runners all cross the same segments in a few hours. The segment leaderboard for "Marathon final 5 km" receives thousands of updates in minutes. A single-writer per segment, batching updates every second, avoids lock contention (Deep Dive 8).
  • A famous athlete. A professional's activity is opened by hundreds of thousands of people within an hour of upload. The activity page and streams are cached at the CDN, so the origin sees a handful of requests. Their feed fan-out uses the pull model (Deep Dive 10).
  • New Year's Day or a global challenge. The whole system sees a spike. Load tests at 2× the previous peak before such days, plus graceful degradation (delay segment matching, shrink feed pages, pause non-critical jobs), keep the core working. See Capacity Planning and Load Testing.

Regions

Athletes are served from a home region close to them (for example, Europe, the Americas, Asia-Pacific). Their activities, efforts and feeds live there. Segments are global data but read-mostly, replicated to every region. Cross-region interactions (a European following an American) read the other region's summary through a replicated cache. This keeps writes local and latency low.

What a strong candidate says: "Concurrency is a client-side problem here. The server scales with uploads per second and with the live-shared subset. I put a queue between upload and processing, scale each stage on lag, and keep interactive uploads ahead of bulk work."

6. Real-time sharing of activities with friends#

Live sharing has different requirements from everything else in the system:

  • Opt-in and small. Only a few percent of activities are shared live, usually long rides, trail runs and solo outdoor activities where safety matters.
  • Latency of seconds, not milliseconds. A family member checking where a cyclist is needs updates every 5–15 seconds, not 100 ms.
  • The sender is on a poor network. Coverage disappears on mountain roads. The design must handle long gaps and send backlogs efficiently.
  • The sender's battery matters most. Each upload wakes the cellular radio.

Sender side

  • The app keeps recording locally exactly as before. Live sharing is an extra upload path that reads from the same local log.
  • It sends a batch of new points every N seconds, where N adapts: about 5 seconds when moving fast with good signal, 15–30 seconds when the battery is low, and only "last known position" when the gap is long.
  • Each batch has a sequence number and the points since the last acknowledged sequence. A lost batch is simply included in the next one. The server ignores sequences it has already seen.
  • After a long offline period the app does not replay every point: it sends the latest position and a simplified line (Ramer–Douglas–Peucker) for the gap.
  • The session has an explicit end (activity stopped) and an expiry (for example 24 hours) so a forgotten session does not keep sharing a location.

Delivering updates to viewers

Bad: viewers poll the activity database. Every viewer reading the database every few seconds creates load on the store that also handles uploads, for data that changes every 10 seconds.

Good: viewers poll a cache-backed live endpoint. The live location service keeps each session's recent points in Redis (a stream or list with a cap, plus the latest point in a hash). Viewers call GET /live-sessions/{id}?since_seq=n every 5–10 seconds and get only new points. Polling is simple, works through every proxy and firewall, and costs little: 1 M open viewers polling every 10 seconds is 100,000 small requests per second, served from memory. For public share links, a CDN can even cache the response for a couple of seconds.

Great: push with server-sent events, with polling as a fallback. Viewers open an SSE stream (one-way, server to client, over plain HTTP). The realtime gateway subscribes to the session's channel and forwards each new batch as an event whose id is the sequence number. SSE fits because the data flows one way, it reconnects automatically, and it carries the Last-Event-ID header on reconnect, which gives us catch-up for free. WebSockets would also work but add a bidirectional protocol we do not need. See Polling, Long Polling, SSE, WebSockets and Webhooks and Pattern: Pushing Realtime Updates.

How the fan-out scales:

  • 500,000 live sessions at peak, with batches every 10 seconds, is 50,000 publishes per second.
  • Each gateway subscribes only to the channels of sessions its viewers are watching. Redis 7's sharded pub/sub sends a message only to the shard that owns the channel instead of broadcasting it across the whole cluster, which keeps per-node load proportional to the channels it owns.
  • With two viewers per session on average, deliveries are about 100,000 per second, spread over a few dozen gateways.
  • An alternative to pub/sub is a dispatcher that keeps a map from session id to the gateways holding its viewers and sends each update directly. It avoids a broker hop but adds a registry to keep correct as gateways come and go.

Catching up after a disconnection

Viewers' phones lose connection too. Three layers keep the view correct:

  1. Last-Event-ID. When an SSE connection drops and reconnects (possibly to a different gateway), the browser or client sends the id of the last event it received. The gateway reads the session's Redis stream from that sequence onward, sends the missed batches, then continues live. Because the recent points are in shared Redis, any gateway can serve the catch-up.
  2. Client-side position tracking. The client stores the last sequence it rendered. When the app comes back from the background, it can call the polling endpoint with since_seq explicitly, render the gap, and then open SSE. Mobile clients should close the stream when backgrounded (the OS throttles it anyway) and reconnect on foreground, which saves battery.
  3. Bounded replay and deduplication. We keep at most the last few hours of points per session in Redis; for a longer gap the client fetches a simplified track of the whole session instead of thousands of points. Because both SSE and HTTP catch-up can deliver the same batch, the client deduplicates by sequence number and merges in order.

Live progress in the feed

A lighter version of live sharing is "Ana is running now" in friends' feeds. It needs only a presence flag and the start time, not positions, and can be shown from a small presence store (Redis keys with a TTL refreshed by the athlete app every few minutes).

Privacy for live sharing

  • Only the chosen viewers (or holders of the share link's secret token) can read a session; the gateway checks on subscribe and on every reconnect.
  • The share link expires when the session ends.
  • Hidden zones may be disabled for safety contacts (the point of the feature is that family can find you), but stay active for everyone else.
  • Live points are deleted when the session expires; the permanent record is the uploaded activity.

7. Matching activities to segments#

Segments are the feature that turns a personal log into a game. Every new activity must be checked against a library of tens of millions of segments, at up to 3,000 activities per second, and every effort's time must be measured precisely enough that a one-second difference on a leaderboard is meaningful.

The problem in geometric terms

A segment is a polyline from a start point to an end point. An activity covers a segment if the track passes close to the segment's start, then follows the segment's path within some tolerance, in the same direction, until it passes close to the segment's end. The effort's elapsed time is the time between crossing the start and crossing the end.

Step 1: candidate generation with a spatial index

Comparing each track with 50 M segments is impossible. We use a spatial index to cut the candidates to a few hundred:

  • Cover the Earth with cells (geohash, S2 or H3; see Geospatial Indexing and Proximity Search). A geohash of 7 characters is a cell of about 150 m × 150 m; S2 and H3 offer similar levels.
  • Index each segment by the cell of its start point (and the neighbouring cells, so a start near a cell edge is not missed). Also store its bounding box and end cell.
  • For a new track, compute the set of cells it passes through. A 40 km ride touches a few hundred cells.
  • Look up all segments whose start cell is in that set, then keep only those whose end cell is also in the set and whose bounding box intersects the track's bounding box.

The cell-to-segment map is about 50 M entries (a few GB), small enough to keep in memory on every matcher instance, refreshed from the segment database as segments are created or edited.

Step 2: precise matching

For each candidate, walk along the track:

// Simplified matcher for one candidate. Points are filtered and projected to metres.
function matchSegment(track: Pt[], seg: Segment, tolM = 30): Effort[] {
  const efforts: Effort[] = [];
  for (let i = 0; i < track.length; i++) {
    if (dist(track[i], seg.start) > tolM) continue;          // not at the start
    if (!sameDirection(track, i, seg)) continue;             // wrong way along it
    let v = 1, j = i;                                        // next segment vertex
    while (j < track.length && v < seg.points.length) {
      if (dist(track[j], seg.points[v]) <= tolM) v++;        // reached next vertex
      else if (distToPolyline(track[j], seg) > 2 * tolM) break; // left the corridor
      j++;
    }
    if (v < seg.points.length) continue;                     // did not finish
    const t0 = crossingTime(track, i, seg.start, seg.startBearing);
    const t1 = crossingTime(track, j - 1, seg.end, seg.endBearing);
    if (plausible(seg, t1 - t0)) efforts.push({ startIdx: i, endIdx: j - 1, elapsedS: t1 - t0 });
    i = j;                                                   // allow later laps
  }
  return efforts;
}

Important details:

  • Crossing time by interpolation. With 1-second samples, the athlete crosses the start line between two samples. We treat the start as a line perpendicular to the segment's first bearing and interpolate the time at which the track crosses it. Without this, efforts are quantised to whole seconds plus the sampling phase, and two riders with the same speed can differ by a second at random. Devices with "smart recording" (sparse points) make interpolation even more important.
  • Multiple efforts. A track that does six laps of a park segment has six efforts. After a match, continue scanning from the end index.
  • Direction. A climb segment ridden downhill must not match. Comparing the bearing of the track near the start with the segment's first bearing handles it.
  • Loops. For a segment that starts and ends at the same place (a lap), the matcher requires the track to leave the start area and visit most of the segment's vertices before it may match the end.
  • Tolerance. Too tight, and GPS noise causes missed matches; too loose, and a parallel road matches. 25–50 m works for most roads; dense cities with parallel streets need the "every vertex in order" rule to reject the wrong street.

Cost: a few hundred candidates, each checked in roughly linear time over the part of the track near it. With candidates sorted by start index and early exits, a long ride is matched in tens to hundreds of milliseconds.

Matching in reverse: a new segment

When someone creates a segment, it should have a leaderboard immediately, which means finding past activities that cover it. That is the inverse query: "which activities passed through these cells?"

  • Keep an inverse index from cell to activity ids (partitioned by cell and month), built by the processor for public activities. Look up the segment's start cell for the last N months, then run the precise matcher on those tracks.
  • For popular areas this can mean hundreds of thousands of tracks. Run it as a background job with a budget, newest first, and show the leaderboard as "still being calculated" until it finishes. Some products only backfill the creator's and their followers' activities and let the rest fill in over time.

Segment quality

  • Segments created from a noisy track are wrong forever. Simplify and snap the geometry when it is created, and reject segments that are too short (under about 100–200 m for rides) or that overlap an existing segment almost entirely.
  • Dangerous downhill segments encourage risky riding. Strava's API exposes a hazardous flag on segments; flagged segments can keep personal records but disable public leaderboards.
  • Editing or deleting a segment invalidates its efforts and leaderboards. Keep versions and recompute in the background.

8. Segment leaderboards#

A segment leaderboard answers: "who has the fastest time on this segment, and where do I rank?" Each athlete appears once, with their best effort. Users can filter by sex, age group, weight class, people they follow, clubs, and time period (today, this week, this month, this year, all time).

Data structure for the hot path

A sorted set (for example in Redis) per segment, with the athlete id as the member and the elapsed time as the score, gives all the core operations:

  • Insert or improve: ZADD lb:seg:{id} LT <score> <athlete>. The LT option (Redis 6.2 and later) only updates the score if the new one is lower, which is exactly "keep the athlete's best" in one atomic command, with no read-modify-write race.
  • Top 10: ZRANGE lb:seg:{id} 0 9 WITHSCORES.
  • My rank: ZRANK lb:seg:{id} <athlete>, O(log N).
  • My friends: ZMSCORE lb:seg:{id} <followee ids...> returns the scores of the given members in one call (Redis 6.2+); sort the results in the service.

Ties. Two athletes with the same time should be ordered by who did it first. Encode both into one score: score = elapsed_s × 100,000 + days_since_2000. Elapsed times under about 10⁶ seconds times 10⁵ stays below 2⁵³, so the double-precision score is exact. Lower is better on both parts.

Filters without a combinatorial explosion

Every filter combination as its own sorted set would multiply storage. A sensible split:

  • Materialise the popular views for each segment: overall, by sex, by age group, and "this year". That is about 10–15 sets per segment, created only for segments with real traffic.
  • Compute rare views on demand: "women aged 45–54 in my club this month" is answered by scanning the segment's best-effort rows (or the year's efforts) and filtering in memory, then caching the result for a few minutes.
  • Friends and clubs are computed at read time from the follow list (usually under a few hundred athletes) using ZMSCORE. Very large clubs can get their own materialised set.
  • Time windows (today, this week, this month) are separate sets per window with a TTL, so they expire on their own.

Memory and the long tail

Leaderboard entries are distinct (segment, athlete) pairs. Suppose 50 M new pairs a day; after a few years that is tens of billions. At about 60–100 bytes per sorted-set member, keeping all of them in Redis would need many TB of RAM, mostly for segments that nobody looks at.

So the source of truth is a database table of best efforts, and Redis holds only the hot segments:

CREATE TABLE best_efforts (
  segment_id   BIGINT  NOT NULL,
  athlete_id   BIGINT  NOT NULL,
  effort_id    BIGINT  NOT NULL,
  elapsed_s    INT     NOT NULL,
  effort_date  DATE    NOT NULL,
  sex CHAR(1), age_group SMALLINT, weight_class SMALLINT,
  PRIMARY KEY (segment_id, athlete_id)
);
CREATE INDEX ON best_efforts (segment_id, elapsed_s, effort_date);
 
-- Keep the best: only replace a slower effort.
INSERT INTO best_efforts VALUES ($1,$2,$3,$4,$5,$6,$7,$8)
ON CONFLICT (segment_id, athlete_id) DO UPDATE
  SET effort_id = EXCLUDED.effort_id, elapsed_s = EXCLUDED.elapsed_s,
      effort_date = EXCLUDED.effort_date
  WHERE best_efforts.elapsed_s > EXCLUDED.elapsed_s;

Partitioned by segment_id, a leaderboard page for a cold segment is one index range scan. When a segment becomes hot (many reads per minute), the service loads it into Redis and keeps it there while traffic lasts, an LRU policy over whole leaderboards. See Redis in Practice.

Writes at a race

On race day thousands of efforts hit one segment within minutes. Updating one sorted set or one database partition thousands of times is fine for Redis but causes lock contention on a single database row range. A single writer per segment (efforts are partitioned by segment id in the event log) batches all updates for a segment every second, applies only the improvements, and writes them in one transaction. See Pattern: Dealing with Contention.

Removing efforts correctly

Leaderboards must handle removals:

  • Activity deleted, made private, or flagged. If the removed effort was the athlete's best, we need their second best, which is why we keep every effort (efforts_by_athlete_segment). The leaderboard service recomputes that athlete's best from their remaining efforts and updates both the table and Redis.
  • Athlete changes age group or weight class. Their entries move between filtered sets; a background job handles it.
  • Rebuilds. Because Redis is a cache of the table, any hot leaderboard can be rebuilt from the table at any time.

Notifications

When the top position changes, the previous holder gets "You lost your KOM/QOM/CR". The leaderboard service emits an event whenever an update changes rank 1 (and optionally the top 10), and a notification service consumes it. A per-athlete rate limit stops a busy segment on race day from sending dozens of notifications.

Cheating and fairness

Leaderboards attract cheating. Reported cases include KOMs taken by people on motorbikes at over 100 mph, and criticism over fastest times from athletes banned for doping. Defences:

  • Plausibility rules per sport and segment: speeds or power far beyond human limits, an acceleration profile that looks like an engine, or GPS that disagrees with the phone's accelerometer.
  • Wrong sport type. A ride uploaded as a run takes every running CR in the area; speed checks catch most of these.
  • Community flagging. Users can flag efforts; flagged efforts are hidden pending review, and repeated abuse removes the athlete from leaderboards.
  • Manual activities (typed in, no GPS) never enter segment leaderboards.

9. Leaderboards of top athletes: distance, time and challenges#

The second kind of leaderboard ranks athletes by a total over a period: most kilometres run this week, most elevation climbed this month, longest ride in a club this year, progress in a monthly challenge. These are counters per (athlete, period, metric), ranked.

The naive approach and why it fails

"SELECT athlete_id, SUM(distance) FROM activities WHERE start_time in this week GROUP BY athlete_id ORDER BY 2 DESC LIMIT 100" works for a small club. For a global board over 30 M active athletes, it scans millions of rows on every request. Even cached, recomputing it every minute is wasteful when only a few hundred activities per second change it.

Incremental totals plus a sorted set

  • On every activity_created event, update the athlete's total for the relevant periods: athlete_totals (athlete_id, sport, period, metric) -> value.
  • Then write the absolute total into a sorted set per board: ZADD lb:run:distance:2026-W49 <total> <athlete>.

Writing the absolute value, not an increment (ZINCRBY), matters. Events are delivered at least once. If the processor crashes after incrementing but before committing its offset, an increment would be applied twice; a ZADD of the recomputed total is idempotent. The total itself is computed from the athlete's activities in that period (a small query on one shard), or maintained in a table with a per-activity contribution row so a duplicate event changes nothing:

CREATE TABLE period_contribution (
  athlete_id  BIGINT NOT NULL,
  period      TEXT   NOT NULL,     -- '2026-W49', '2026-12'
  sport       TEXT   NOT NULL,
  activity_id TEXT   NOT NULL,
  distance_m  REAL   NOT NULL,
  elev_m      REAL   NOT NULL,
  PRIMARY KEY (athlete_id, period, sport, activity_id)
);
-- Insert is a no-op for a duplicate event; the total is a SUM over a handful of rows.
INSERT INTO period_contribution VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT DO NOTHING;
SELECT sum(distance_m) FROM period_contribution
 WHERE athlete_id = $1 AND period = $2 AND sport = $3;

Deleting or editing an activity deletes or updates its contribution row and recomputes the total, which handles the hard cases (a ride re-labelled as a run, a deleted duplicate) cleanly.

Scale

  • Updates: 460 activities per second on average, 3,000 at peak, each touching 2–4 boards (week, month, year; global and per club). That is at most about 12,000 sorted-set writes per second, trivial for a Redis cluster.
  • A global weekly board for one sport is one sorted set with up to 30 M members, about 2–3 GB in Redis. That is a single hot key on one node. It is fine for writes at this rate; for reads, cache the top 100 in the API layer for 30–60 seconds, and serve "my rank" from ZREVRANK, which is O(log N).
  • If one key ever becomes too big or too hot, split the board by country (most people care about their country anyway) or by score bands, as in leaderboard designs for games.

Friends and clubs

  • Friends: the follow list is small (median tens, rarely more than a few thousand). Fetch the totals of the followed athletes with ZMSCORE on the global board, add the viewer, sort in memory. No per-viewer set is needed.
  • Clubs: a club can have hundreds of thousands of members. Maintain a sorted set per club and period; on each activity, update the boards of the athlete's clubs (most athletes belong to only a few). Club boards reset weekly, so the sets carry a TTL of a couple of weeks.

Time zones and period boundaries

"This week" must mean something. Options:

  • Global boards in UTC. Simple, but a New Zealander's Monday morning run counts for the previous week.
  • Personal and friends' boards in the athlete's local time zone, using the time zone stored at the start of each activity. The period key is computed from the local start time.
  • Club boards in the club's time zone.

We store the period key on each contribution row so boundaries are consistent everywhere.

Challenges

A challenge ("Run 100 km in December") is a periodic total with a goal. Progress is the same contribution table filtered by challenge; completion triggers a badge and a notification. Joining a challenge late should still count earlier activities in the window, so the join step backfills from the athlete's activities.

Anti-abuse

  • Manual entries and activities without GPS can be excluded from distance boards.
  • Implausible totals (a "run" of 300 km at 40 km/h) are flagged before entering global boards.
  • Activities made private disappear from public boards but still count in the athlete's own totals.

10. The activity feed for friends#

The feed is the social heart of the product: "what did the people I follow do recently?" It is read about 10,000 times per second at peak and written by every activity.

Fan-out on write, on read, or both

  • Fan-out on read: when a viewer opens the feed, fetch the recent activities of everyone they follow and merge them. Reads cost one query per followee (or a scatter-gather), which is slow for someone following 500 athletes.
  • Fan-out on write: when an activity is created, push its id into the feed list of every follower. Reads are one range read. Writes cost one insert per follower: 40 M activities × an average of 50 followers = 2 B inserts per day.
  • Hybrid: fan out on write for normal athletes; for accounts with many followers (professional athletes, brands, say above 10,000 followers), do not fan out; instead, merge their recent activities into the feed at read time.

The hybrid is the standard answer for social feeds, and it fits here particularly well because the follower distribution is very skewed: most athletes have a small, local network, a few have hundreds of thousands of followers.

The feed store

  • A capped list per viewer of the last 500–1,000 items (activity id, author id, sort time), in Redis for active users. 30 M daily users × 500 items × about 30 bytes ≈ 450 GB; in practice only recently active viewers are kept in memory, and others are rebuilt on demand.
  • Older pages come from a wide-column table feed_by_viewer (viewer_id, sort_time, activity_id) or are rebuilt by fan-out on read for the rare deep scroll.
  • Fan-out workers group followers by feed shard and send one pipelined batch per shard, so 100,000 inserts per second become a few thousand network calls.

Ordering and grouping

  • Order by activity start time, not upload time. A watch that syncs a week late should not put an old ride at the top of everyone's feed. If the activity is very old (more than a few days), it can be inserted at its true position or not fanned out at all.
  • Group activities. When several people ran or rode together, the feed should show one grouped card ("Ana, Ben and 4 others rode together"). Strava does this for public activities that happen at the same time and place. A practical method: when an activity is processed, look up other activities that started within about 10 minutes in the same or neighbouring cells (an index by start cell and start hour), then compare their tracks for overlap. Matching ones share a group id, which the feed uses to collapse cards.
  • Mostly chronological. Fitness feeds are usually chronological with light ranking (for example, boosting close friends or big achievements). Chronological is predictable and matches what athletes expect.

Hydration and privacy at read time

The feed list holds only ids. On read, the feed service batch-fetches summaries (title, stats, polyline, kudos count, photos) from the activity cache. This is also where privacy is enforced:

  • An activity made private after fan-out is filtered out at read time, because the summary says so.
  • A deleted activity is missing from the cache and the database, so it is dropped (and lazily removed from the list).
  • Blocks and mutes are applied per viewer.

Checking at read time is cheap (we fetch the summary anyway) and correct even when fan-out and privacy changes race.

Kudos and comments counters

Kudos are frequent, tiny writes (about 4,600 per second). Store each kudos as a row (activity id, athlete id) for uniqueness, and keep a counter in the activity cache incremented with HINCRBY, periodically reconciled with the row count. The giver sees their own kudos immediately from their client state (read-your-writes in the UI), even if a cache replica lags.

Pagination

Use a cursor made of the last item's (sort time, activity id). Offsets break when new items arrive at the top; the cursor stays stable.

For a broader treatment of feed design (ranking, celebrity problem, caching) see the news-feed case study in this handbook; the same building blocks apply here, with different numbers.

11. Privacy, safety and the global heatmap#

A fitness track is some of the most sensitive data a consumer app holds. It shows where someone lives (the start and end of most runs), when they are away from home, their routine, and sometimes where they work. Strava's history gives concrete lessons.

What has gone wrong in the real world

  • In November 2017 Strava published a global heatmap, a visualisation of aggregated public activity data. In January 2018 a student studying international security noticed that it revealed military bases, including US bases in Syria, forward operating bases in Afghanistan, and HMNB Clyde, the Royal Navy base in Scotland: soldiers' running loops lit up places that were otherwise blank on the map. Strava responded by focusing on privacy awareness and suggesting military users opt out of the heatmap.
  • In 2022 a separate flaw, this time through the segments feature, let researchers identify and track security personnel at military bases in Israel.
  • In 2023 a report claimed that heatmap data could reveal the home addresses of highly active users in remote areas.
  • In 2024 and 2025 newspaper investigations found that public activity data exposed the movements of world leaders' security teams and of crews at the French nuclear-submarine base at Île Longue.

The common thread is that aggregates and side features leak, not just the raw activity page. Each new view of the data (a heatmap, a segment leaderboard, "flybys" showing who passed you) is a new way to learn about individuals.

Controls an athlete needs

  • Visibility per activity: everyone, followers, or only you, with a default per athlete. Private activities never appear in feeds, leaderboards, heatmaps, flybys or group detection.
  • Hidden zones around places such as home and work: the part of the track inside the zone is hidden from everyone but the owner.
  • Hide start and end by distance (for example, the first and last 200 m to 1 km), which works even without defining a place.
  • Opt out of aggregates: heatmaps, city data products and similar.
  • Hide specific details: heart rate, start time, or the map entirely.

Hidden zones done right

A naive hidden zone is a circle of fixed radius r around the home. The track is cut where it enters the circle. The problem: the cut points of many activities all lie on the same circle, and three points on a circle determine its centre. An attacker who collects the visible start points of a few runs can compute the home location precisely.

Better implementations:

  • Offset the zone centre by a random amount (stored once per zone, never shown), so the circle is not centred on the home.
  • Vary the effective radius per activity or trim an extra random distance after the zone boundary, so cut points do not lie on one clean circle.
  • Trim by distance along the track ("hide the first 800 m") instead of a geometric circle, which avoids the circle-fitting attack entirely, although very regular routes can still leak information.
  • Apply the trim everywhere: the polyline, the streams served to non-owners, segment efforts that start or end inside the zone (do not show them on public leaderboards), and the start-point fields of the API.

The enforcement point matters. The privacy filter should be a single shared library that every read path calls (activity service, feed hydration, streams service, leaderboard service, export jobs), with tests that check each path. A feature added later that forgets the filter is how leaks happen.

Heatmaps and other aggregates

An aggregate heatmap counts how many activities passed through each pixel or cell. It looks anonymous but is not when counts are small: a single soldier's lap of a base produces a bright loop in an empty desert. Safeguards:

  • Use only public activities, after hidden-zone trimming, from athletes who did not opt out.
  • Minimum thresholds: show a cell only if enough distinct athletes (not activities) passed through it, for example at least 5–10. This is a k-anonymity style rule.
  • Remove sparse regions and add delay (do not publish recent weeks), so routines cannot be followed in near real time.
  • Add noise to counts. Differential privacy formalises how much noise is needed so that adding or removing any one athlete changes the output very little; for a heatmap, that means calibrated noise on cell counts and dropping cells below a noisy threshold.
  • Lower resolution for low-density areas.

Platform security

  • Encrypt location data at rest and in transit; limit employee access, and log every access to raw tracks.
  • Strong authentication for the API and partner integrations, with scopes (for example, "read private activities" is a separate permission). See Authentication and Authorization.
  • Export and deletion: athletes can download their data (original files and streams) and delete their account. Deletion must reach every copy: object storage, efforts, leaderboards, feeds, caches, analytics tables and backups (via key deletion). See Security Fundamentals for System Design.

What a strong candidate says: "Location data is sensitive. I enforce visibility and hidden zones in one library on every read path, hide segment efforts inside zones, and only publish aggregates over public data with distinct-athlete thresholds and delay, because the 2018 heatmap showed that aggregates leak."

12. The processing pipeline, reliability and operations#

Everything after the upload is an event-driven pipeline. Its job is to turn each saved activity into stats, streams, efforts, leaderboard entries, feed items and notifications, exactly once in effect, even though every component may fail and retry.

Stages and events

  • Topics are partitioned by athlete id up to the activity stage, so one athlete's create, edit and delete events are processed in order. The leaderboard writer re-partitions by segment id so each segment has one writer.
  • Every consumer is idempotent: writes are keyed by activity id (or by activity id plus segment id), using upserts and insert-if-absent. A replayed event produces the same rows. See Delivery Guarantees: At-Most, At-Least and Exactly-Once.
  • Edits and deletes are first-class events, not special cases. Changing an activity from "ride" to "run" triggers re-matching against running segments, moving the totals between sports, and updating feed cards.

Failures and how we handle them

  • Malformed files. Parsing fails; the activity is marked failed with a clear reason ("file has no timestamps"), and the original is kept for debugging. The client shows the error instead of retrying forever.
  • Poison events. An event that crashes a consumer repeatedly is moved to a dead-letter topic after a few attempts, with an alert, so it does not block its partition.
  • Downstream outage. If the effort store is down, the matcher pauses and its lag grows; uploads and activity pages still work. When the store recovers, the matcher catches up. Each stage can fall behind without breaking the stages before it.
  • Partial success. Activities become visible as soon as the processor finishes. Missing segment results are filled in when the matcher catches up, which is exactly the behaviour Strava documents for its upload API.
  • Reprocessing at scale. Because originals are kept and the event log can be replayed, a bug fix in, say, elevation correction can be applied to all affected activities by a batch job that emits activity_updated events, throttled so it does not starve live traffic.

Disaster recovery

  • Object storage is replicated across zones and, for originals, across regions.
  • The activity databases have synchronous replicas in another zone and asynchronous replicas in another region. RPO of seconds and RTO of minutes for the write path are realistic.
  • Redis data (leaderboards, feeds, live points) is a cache of durable data. After a total loss, leaderboards are rebuilt from the best-efforts table, feeds from the activity database and follow graph, and live sessions resume when phones send their next batch.
  • The device is also a backup: activities stay on the phone until confirmed, so even a server-side data loss window can be refilled by re-sync.

See Disaster Recovery and Backups for RPO and RTO trade-offs.

Observability

The metrics that matter most are about the athlete's experience, not just servers:

  • Lost activities: client-reported activities that never reached ready, which should be essentially zero. Track crash-free recording sessions by app version.
  • Time to visible: from "Save" to the activity appearing in the athlete's own list and in friends' feeds (p50 and p99).
  • Matcher and fan-out lag: consumer lag per topic and per region.
  • Stats agreement: how often device and server distance differ by more than 2%.
  • Live-sharing freshness: age of the latest point seen by viewers.

See Observability: Logs, Metrics and Traces.

Shipping the recorder safely

The recorder is the most critical code in the product, and it runs on millions of devices that update on their own schedule:

  • Staged rollouts (1%, 10%, 50%, 100%) watching crash rates and lost-activity reports, with the ability to halt.
  • Feature flags for new filters or formats, with server-side kill switches.
  • Local database migrations must be forward-compatible and tested against activities recorded by old versions; an upgrade during a recording must not lose the activity.
  • The server accepts every old upload format for years, because some phones never update.

See CI/CD and Deployment Strategies and Mobile System Design.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Phone OS kills the app mid-recordingActivity truncated or lost; the worst failure in the productForeground service or background location mode; write every sample to SQLite before anything else; resume a recording after a restart from the local journal
GPS jitter and signal loss (cities, tunnels, forests)Inflated distance, fake fast segments, broken leaderboardsAccuracy filter, speed sanity limits, Kalman smoothing, pause detection; server recomputes stats from raw samples
Upload storm after a big Sunday race or New Year's Day5–10× the normal upload rate; processing lag growsAccept-and-queue: upload path only stores the file and returns 202; processors autoscale on topic lag; matching and fan-out are allowed to fall behind for minutes
Duplicate uploads (watch and phone, retries)Double activities, double totals, double leaderboard entriesClient upload id and device external id as idempotency keys; content hash and time-overlap check per athlete
Popular segment (a famous climb) gets thousands of efforts per hourHot partition in the effort store and the leaderboard keyYear-bucketed effort partitions; one writer per segment; Redis ZSET only for the top N; batching of ZADDs per segment
Leaderboard cheating (car, motorbike, GPS spoofing)Unfair KOMs, user trust lostSpeed limits per sport and segment, flagging by athletes, review queue, removing efforts and re-ranking; hazardous segments excluded
Live-sharing viewer storms (a famous athlete shares a race)Fan-out overload, delayed pointsFan-out through pub/sub nodes; viewers poll a cached "latest points" key after a size threshold; SSE with Last-Event-ID for catch-up
Feed fan-out for athletes with millions of followersWrite amplification, slow feedsHybrid fan-out: push for normal athletes, pull and merge for big accounts; capped feed lists
Privacy leak through a new derived viewExposes homes, bases or routines; legal and reputational damageOne shared privacy filter used by every read path; hidden zones applied to efforts and heatmaps; distinct-athlete thresholds for aggregates
Processor bug corrupts stats for many activitiesWrong distances, wrong recordsKeep original files; replay a fixed version as activity_updated; throttled backfill; version the processing code per activity
Redis cluster lossLeaderboards, feeds and live sessions unavailableTreat Redis as a cache of durable data; rebuild boards from best_efforts, feeds from activities and follows; phones resend live batches
Region outageUploads fail in that regionPhones keep activities until confirmed and retry with backoff; DNS or anycast moves traffic to another region; originals replicated cross-region

What Interviewers Expect#

Mid-level. Gets the core loop right: record locally on the phone, upload the finished activity, store the file in object storage and the summary in a database, and show it in a friends' feed. Knows that GPS points are written to local storage during the run and that the server must handle retries without duplicates. Can sketch a leaderboard with a sorted set. Gives rough numbers for activities per day and storage per year.

Senior. Treats offline-first recording as the main reliability requirement and explains the local journal, the sync queue and idempotent upload. Separates the upload path from an asynchronous processing pipeline, so a spike in uploads only creates lag. Designs segment matching with a spatial candidate index and a precise path check, and explains how leaderboards stay correct under edits and deletes. Designs live sharing with batching on the phone and push to viewers, with catch-up after a reconnect. Picks stores per access pattern (object storage for tracks, relational or wide-column for activities and efforts, Redis for hot rankings) and justifies each one.

Staff and above. Frames the hard problems: battery versus accuracy on the device, correctness of rankings with noisy GPS and cheating, and privacy in derived data. Brings up the hidden-zone inference attack and the lesson of public aggregates. Plans for reprocessing (keep originals, replay with new code) and for clients that never update. Defines product-level SLOs (zero lost activities, time to visible in the feed, matcher lag) and how they are measured. Discusses cost (storage tiers for 1.5 PB a year, compute for 400 M segment efforts a day) and multi-region trade-offs, and knows which parts can be eventually consistent and which must not lose data.

Deep Dive: sizing every tierShow

Starting point (from the capacity section): 10 M concurrent activities at peak, 3,000 uploads per second, 25,000 segment efforts per second, 10,000 feed reads and 20,000 detail views per second, 100,000 feed inserts per second, 500,000 live sessions sending 50,000 batches per second.

Upload API.

  • Each upload is a 60 KB body written straight to object storage plus one small database row. A single instance handles several hundred such requests per second, limited mostly by TLS and network.
  • 3,000 per second / 300 per instance = 10 instances; run about 16 across zones for headroom and rolling deploys.

Processors (parse, clean, stats, streams).

  • Parsing a one-hour FIT file, filtering 3,600 points, computing stats, looking up elevation from a terrain model and writing streams costs roughly 50–100 ms of CPU. Use 100 ms.
  • 3,000 per second × 0.1 s = 300 cores busy at peak. At 60% target utilisation, 500 cores: about 32 machines with 16 cores, autoscaled down to a third of that at night.

Segment matcher.

  • Candidate lookup is cheap (a few hash lookups per track cell). The precise check is the cost: about 30 candidate segments per activity, each checked in 1–3 ms, so about 60 ms per activity.
  • 3,000 × 0.06 s = 180 cores at peak, about 20 machines with 16 cores. The segment index (50 M segments, about 100 GB with geometry) does not fit on one small machine, so shard it by region (geohash prefix), or keep only the candidate index (cell to segment ids, a few GB) in memory on every matcher and fetch geometry from a cache.

Object storage.

  • Writes: 3,000 originals plus 3,000 stream objects per second = 6,000 PUTs per second at peak. S3-style stores scale per prefix, so object keys start with a hash (for example a7/f3/act_123/streams.v2).
  • Reads: 20,000 detail views per second; recent and popular activities are served from a cache in front of the store, with a hit rate of about 80%, leaving about 4,000 GETs per second on the store.

Activity database.

  • Writes: 3,000 inserts per second plus updates (stats, kudos counts) at about the same rate.
  • Reads: detail views plus feed hydration (10,000 feed reads × 20 cards = 200,000 card lookups per second). The cache in front of the database absorbs most of this; the database sees maybe 20,000–40,000 reads per second.
  • Size: 30 TB per year of metadata. Shard by athlete id into 32 PostgreSQL shards, each about 1 TB per year, about 200 writes per second and about 1,000 reads per second. Each shard has one synchronous standby and one replica in another region.

Effort store (Cassandra or similar).

  • 25,000 efforts per second × 2 tables (by segment, and by athlete and segment) = 50,000 writes per second, 150,000 replica writes per second at replication factor 3.
  • Storage: 9 TB per year × 2 tables × 3 replicas = 54 TB per year.
  • A node comfortably sustains 10,000–20,000 writes per second and about 2 TB of data. Throughput needs about 10–15 nodes; storage needs about 27 new nodes per year. Start with 30 nodes per region and grow with data.

Redis for leaderboards.

  • Boards in Redis only for active segments. Assume 1 M segments with recent traffic, an average of 2,000 athletes each, about 100 bytes per sorted-set entry: 200 GB.
  • 25,000 ZADDs per second is light for Redis. About 10 shards of 32 GB, each with a replica. Cold segments are served from the best_efforts table.

Redis for feeds.

  • 30 M active feeds × 500 ids × about 20 bytes = 300 GB.
  • 100,000 inserts per second at peak, spread over shards. About 16 shards of 32 GB with replicas. Inactive users' feeds expire and are rebuilt on demand.

Live sharing.

  • 50,000 incoming batches per second: a few ingest instances.
  • Up to 1 M viewer connections, mostly idle SSE streams. At 50,000–100,000 connections per server, about 20 fan-out servers, plus Redis pub/sub or a dispatcher layer.

Kafka.

  • Upload, activity, effort, feed and notification events together: under 200,000 messages per second at peak, each under 1 KB. 6–9 brokers with replication factor 3, kept for 7 days for replay.

The cost lesson: storage of streams dominates the bill over years, processing CPU dominates at peak, and real-time infrastructure is small because only live-shared activities touch it.

Deep Dive: what the public record tells us about StravaShow

Most of Strava's internals are not public, but its history and its developer documentation show how a real system of this kind behaves. Use these as calibration, not as claims about its exact architecture.

Scale over time. Strava was founded in 2009. It passed 1 billion uploaded activities in 2017, and by 2020 had more than 50 million users and more than 3 billion activities. Our design targets a larger, hypothetical load (10 M concurrent activities), which is why we size for far more.

Device ecosystem. Activities arrive from Strava's own app and from third-party devices such as Garmin, Coros and Suunto, through device-maker integrations. That is the reason for supporting FIT, TCX and GPX, and for an external_id that identifies the source file (the API's examples show values such as garmin_push_...).

Uploads are asynchronous. The public upload API returns an upload id immediately; the client polls the upload status, no more than once per second. The documentation says mean processing time is under two seconds, and that segment results may appear later than the activity itself. Every trackpoint must carry a timestamp. A duplicate file is rejected with an error saying it duplicates an existing activity. This matches our accept-and-queue design and our separate matcher stage.

Rate limits and webhooks for partners. Third-party apps get a default of 200 requests per 15 minutes and 2,000 per day, with windows that reset at fixed quarter-hours and at midnight UTC, and HTTP 429 when exceeded; response headers report usage. Instead of polling, partners subscribe to webhooks for activity create, update and delete and for athlete deauthorisation; the receiver must acknowledge within two seconds, and delivery is retried a limited number of times. A change of visibility to "only you" is delivered as a delete, and the reverse as a create, which is a neat way to keep partner copies private. See Rate Limiting and Throttling.

Streams with resolution. The streams API returns separate arrays per type (time, latlng, distance, altitude, heartrate and so on) and supports a requested resolution, reporting the original size. That is the columnar, multi-resolution layout from Deep Dive 4.

Polylines everywhere. Activity summaries carry an encoded polyline of the route, using the widely used polyline algorithm (scale coordinates by 100,000, delta-encode, and pack into printable characters), which keeps feed cards small.

Segments, records and safety. Segments grew out of automatic climb detection. Leaderboards award KOM, QOM and course records, and have been criticised when athletes banned for doping or riders on motorbikes appeared at the top, with reported speeds as high as 112 mph. Athletes can flag suspicious efforts, and segments can be marked hazardous. Beacon is a safety feature that shares a live location with chosen contacts.

Privacy incidents. The 2017 global heatmap, the 2018 military-base discovery, the 2022 segment flaw that exposed Israeli personnel, the 2023 home-address concern, and the 2024 and 2025 reports on security teams and French submarine crews. Deep Dive 11 turns them into design rules.

Deep Dive: a 45-minute interview plan and follow-up questionsShow

A plan for the time.

MinutesWhat to do
0–5Clarify: sports, offline recording, live sharing, segments and leaderboards, feed, scale (DAU, activities per day, concurrent activities). State 10 M concurrent as the target
5–10Requirements and estimation: show that samples stay on the device, uploads are about 3,000 per second at peak, storage is about 1.5 PB per year
10–15Entities and API: activity, stream, segment, effort, leaderboard entry; upload, get activity, streams, feed, live session, leaderboard
15–25High-level design: recorder and local journal, upload API to object storage, queue, processors, matcher, leaderboards, feed, live-sharing path
25–40Deep dives: offline recording and idempotent upload, segment matching and leaderboard correctness, live sharing; one more if time allows (privacy or feed)
40–45Failures and trade-offs: upload spikes, hot segments, cheating, privacy leaks, region loss

Follow-up questions and strong answers.

  • "Why not stream every GPS point to the server during the activity?" At 10 M concurrent activities that is 10 M writes per second for data nobody reads in real time, and it costs battery and fails without signal. Record locally, upload once, and send batched points only for live sharing.
  • "What if the phone dies before upload?" Every sample is in SQLite on disk, so the activity survives a crash or reboot; on restart, the app finds the unfinished recording and offers to save it. Uploads stay queued until the server confirms.
  • "How do you stop the same run appearing twice from a watch and a phone?" Idempotency key per upload, external id per device file, and an overlap check: same athlete, overlapping time ranges, similar start points. Offer a merge or choose the device with sensors.
  • "How do you find which segments an activity matched, fast?" Index segments by the geohash cells their start points fall in; look up the cells the track passes through for candidates; then verify each candidate with start and end proximity, ordered path following and a distance tolerance.
  • "A popular climb has 200,000 efforts a year; how is its leaderboard fast?" Keep only each athlete's best per segment, maintain a sorted set in Redis with a tie-breaking score, have one writer per segment, and read ranks with ZRANK in O(log N).
  • "An athlete deletes an activity that held the KOM." Delete event, remove its efforts, recompute that athlete's best on the segment from remaining efforts, update the board, notify the new KOM holder.
  • "How would you show 'you are 3rd among friends'?" Get the athlete's following list (a few hundred), read their scores with ZMSCORE, and rank them in memory. No per-athlete precomputed boards.
  • "How do you make the heatmap safe?" Public activities only, after hidden-zone trimming; opt-out; a minimum number of distinct athletes per cell; delay; noise.
Deep Dive: best efforts, the fastest 1 km inside any runShow

Runners like to see "your fastest 1 km, 5 km and half marathon", computed from any part of any run, not only from races. This is a classic sliding-window problem over the distance stream.

The problem. Given samples with cumulative distance d[i] (metres, non-decreasing) and time t[i] (seconds), find the minimum of t[j] − t[i] over all pairs where d[j] − d[i] ≥ L, for L = 400 m, 1 km, 1 mile, 5 km, 10 km and so on.

A brute-force check of every pair is O(n²): for a 3-hour run with 10,800 samples that is about 58 million pairs per distance. Too slow at 3,000 activities per second.

Two pointers, O(n). Because distance only grows, for each end index j the best start is the largest i with d[j] − d[i] ≥ L. As j moves forward, that i only moves forward too. So one pass with two indices is enough.

// Fastest time to cover at least `len` metres. d: cumulative metres, t: seconds.
function bestEffort(d: number[], t: number[], len: number) {
  let best = Infinity, bestI = -1, bestJ = -1;
  let i = 0;
  for (let j = 0; j < d.length; j++) {
    // advance i while the window starting at i+1 still covers len
    while (i + 1 < j && d[j] - d[i + 1] >= len) i++;
    if (d[j] - d[i] < len) continue;
    // interpolate the exact start point so the window is exactly len
    const over = d[j] - d[i] - len;
    const segD = d[i + 1] - d[i];
    const frac = segD > 0 ? Math.min(over / segD, 1) : 0;
    const startT = t[i] + frac * (t[i + 1] - t[i]);
    const dur = t[j] - startT;
    if (dur < best) { best = dur; bestI = i; bestJ = j; }
  }
  return { seconds: best, from: bestI, to: bestJ };
}

Worked example. A run with samples every 10 s at a steady 5 m/s, except a fast stretch at 6 m/s from 2,000 m to 3,500 m. Any 1 km window inside the fast stretch takes 1,000 / 6 = 166.7 s; any window outside takes 200 s. The algorithm finds a window of 166.7 s starting anywhere between 2,000 m and 2,500 m and reports 2:47 per km. Interpolation matters: without it, sample spacing of 50–60 m would make every window slightly longer than 1 km and the times a second or two slow.

Practical points.

  • Run it on the cleaned distance stream from Deep Dive 2. One GPS spike of 200 m would otherwise create a fake world record.
  • Apply sanity limits per distance (a 1 km best effort under 2:10 is faster than the world record and must be flagged, not stored).
  • Compute all standard distances in one pass each, about 10 passes of 10,000 samples: under a millisecond.
  • Store results in an athlete-records table and compare with the previous best to award a PR badge. Deleting the activity that holds a record means recomputing that athlete's record from their remaining best efforts, the same pattern as segment leaderboards.
  • For cycling, the same idea gives power curves: the best average power for 5 s, 1 min, 5 min, 20 min and so on, over the power stream. Those windows are by time rather than distance, and a running sum over a fixed-length window finds each in O(n).
Deep Dive: sensors, watches and BluetoothShow

Many athletes record with sensors beyond GPS: heart-rate straps, power meters, cadence and speed sensors, and watches.

Bluetooth Low Energy profiles. Standard BLE (Bluetooth Low Energy) services make sensors interchangeable:

  • Heart Rate service (0x180D), with the Heart Rate Measurement characteristic (0x2A37). Each notification starts with a flags byte: bit 0 says whether the heart rate is a uint8 or uint16, and other bits say whether energy expended and RR intervals follow. RR intervals (the time between beats, in units of 1/1024 s) are what heart-rate-variability features use.
  • Cycling Power service (0x1818): instantaneous power in watts, plus optional pedal balance and crank revolution data, from which cadence is derived.
  • Cycling Speed and Cadence (0x1816) and Running Speed and Cadence (0x1814): cumulative wheel or crank revolutions with event times; the app turns differences into speed and cadence.
  • Many sports devices also speak ANT+, a separate low-power wireless protocol common on bike computers and watches.

How the recorder uses them. Sensor notifications arrive at their own rate (heart rate about once per second, power up to several times per second). The recorder keeps the latest value per sensor and writes it into each one-second sample row, so all streams share one time axis. If a sensor drops out, the field is left empty rather than repeating the last value forever, so charts show a gap and averages are not distorted.

Indoor activities. With no GPS, distance comes from a wheel-speed sensor, a smart trainer or a footpod. The activity has no map and no segments, and the server must not try to match it. Virtual rides from indoor platforms arrive as files with virtual coordinates and need their own sport type so they never land on outdoor leaderboards.

Watches record without the phone. A watch records its own FIT file and syncs later, either through the maker's cloud (which then pushes to us) or through the phone over Bluetooth. That is why the same activity can arrive twice, and why the upload path must deduplicate by external id and time overlap.

Deep Dive: group activities and flybysShow

When several friends ride together, Strava groups their activities into one group activity on the feed, and users can see "flybys": other athletes whose tracks passed theirs. Both are spatio-temporal joins over public activities.

Group detection.

  1. Candidates. When an activity is processed, look up other public activities that started within, say, 15 minutes and whose start points fall in the same or a neighbouring geohash-6 cell (about 1.2 km by 0.6 km). An index keyed by (start cell, start hour bucket) gives this in one or two lookups.
  2. Track comparison. For each candidate, resample both tracks at the same timestamps (every 10 s over the overlapping period) and measure the distance between the two positions at each step.
  3. Decision. If the two athletes were within about 50 m of each other for at least 60% of the overlapping time, and the overlap covers most of the shorter activity, treat them as a group.
  4. Merge into groups. Pairs form a graph; connected components are the groups. A union-find structure keyed by activity id makes it cheap to add a late upload to an existing group.

Cost: a typical activity has zero to a few candidates; the check is a few hundred distance calculations. It runs in the asynchronous pipeline and can lag behind without harm.

Flybys. A broader search: any public activity that came within about 100 m of mine at the same moment, even briefly. A useful structure is a space-time cell index: for each activity, record the set of (geohash-6 cell, 5-minute bucket) pairs its track occupied. Two activities that share a cell-bucket pair are flyby candidates; a precise time-aligned check confirms them. For 40 M activities a day with an average of 30 cell-bucket pairs each, that is 1.2 B index entries per day, kept only for a few weeks.

Privacy. Both features use only public activities from athletes who allow them, after hidden-zone trimming. Flybys in particular can tell a stranger who ran past you at a given time, so they deserve their own opt-out and should never use private data even internally.

Deep Dive: the mobile client and batteryShow

The recorder is a long-running app that competes with the OS for the right to keep running, and the athlete judges it mostly by battery life and by never losing a run.

Where the battery goes.

  • The GPS receiver is the biggest steady cost. One-second fixes with high accuracy keep it fully on.
  • The screen: an always-on map during a run can cost more than GPS. Encourage a lock-screen widget or a dark, simple recording screen.
  • The cellular radio: each wake-up for a network request keeps the radio in a high-power state for several seconds afterwards. Many small requests cost far more than one batched request. This is why live sharing sends a batch every 10–30 seconds instead of every point.
  • Sensors over BLE are cheap; BLE was designed for this.

Techniques.

  • Use the platform's fused location provider with the highest accuracy only while recording, and a lower rate when stopped (auto-pause).
  • Keep recording in a foreground service with a visible notification on Android, and with background location mode on iOS. Both platforms restrict background work aggressively, and some Android vendors kill background apps unless the user changes settings, so the app should detect a gap in samples and tell the user how to fix it.
  • Batch writes to SQLite (for example, commit every 5–10 samples in one transaction) to reduce disk wake-ups while keeping the risk of loss to a few seconds.
  • Do the heavy work (route matching, segment checks, upload of large files) after the activity, preferably on Wi-Fi or while charging for non-urgent tasks like uploading photos.
  • Live segments (showing a segment as you approach it during a ride) need the nearby segments downloaded before the ride starts, so the phone can match locally without network calls.

Testing. Battery and recording reliability are measured on real devices: replay recorded GPS traces through the app with simulated locations, run long-duration tests in background mode, and track the share of activities with sample gaps by device model and OS version. See Client, Mobile and Frontend Considerations.

Key Takeaways#

  • The device does the real-time work. At 10 M concurrent activities, samples stay on the phone in a local journal; the server sees one upload per activity, plus small batches only for live sharing.
  • Never lose an activity. Write every sample to disk first, keep the recording until the server confirms, and make uploads idempotent with a client upload id, a device external id and a time-overlap check.
  • Accept, then process asynchronously. The upload path stores the original file and returns; parsing, cleaning, stats, segment matching, leaderboards and feeds are idempotent pipeline stages that can lag during a Sunday-morning spike without failing.
  • Clean GPS before trusting it. Filter by accuracy and speed, smooth, detect pauses, correct elevation, and recompute stats on the server, because noisy points become fake records and wrong distances.
  • Store tracks as compressed columnar streams. Delta-encoded streams in object storage, a polyline for previews, several resolutions for charts, and the original file kept for reprocessing and export.
  • Segments are a spatial join plus a path check. A geohash candidate index finds possible segments in a few lookups; ordered path following with tolerances confirms them and finds exact start and end times by interpolation.
  • Leaderboards keep only each athlete's best. A conditional upsert on best efforts is the source of truth; Redis sorted sets with a tie-breaking score serve hot segments; one writer per segment; edits and deletes trigger recomputation.
  • Live sharing is a small, separate push system. Batched points from the phone, sequence numbers, SSE or WebSocket fan-out, and catch-up from a short recent buffer using Last-Event-ID.
  • Feeds are hybrid. Push activity ids to followers' capped lists, pull for very popular athletes, and apply privacy and visibility when the feed is read.
  • Privacy is a design constraint, not a setting. Hidden zones that resist inference, one privacy filter on every read path, and aggregates over public data only, with distinct-athlete thresholds, delay and noise.
  • Keep everything replayable. Originals plus an event log let you fix a processing bug for millions of activities, rebuild caches after a loss, and support clients that never update.