Backend Architecture for Activity Recording Platform
System DesignModel answerLast updated
Design a scalable system to capture high-frequency GPS data from mobile workout sessions, compute activity metrics, and serve historical workout information.
Backend Architecture for Activity Recording Platform
You need to architect a backend that powers a mobile application for recording physical activities like runs and bike rides. The platform must handle real-time location tracking, metric calculation, and historical data access.
Core Capabilities
Your system must support:
- Recording activities with start/pause/stop controls
- Capturing GPS data points (latitude, longitude, timestamp) sampled frequently (approximately once per second)
- Allowing users to browse their past activities with aggregate statistics
- Displaying detailed route visualizations for completed activities
Scale and Performance Goals
- Support 1 million simultaneous active recording sessions
- Minimize latency for real-time metric updates during active sessions
- Ensure historical data remains accessible with high uptime
- Protect user data with appropriate access controls and privacy measures
What to Deliver
Your design should cover:
- API contracts: Specify the key endpoints for session lifecycle management, data ingestion, and retrieval operations
- Data organization: Define schemas for user profiles, activity sessions, and location point streams
- Storage decisions: Justify your database choices considering write patterns, query needs, and data characteristics (consider relational, document, time-series, and object storage options)
- System architecture: Illustrate the data flow from mobile devices through ingestion pipelines, processing layers, and storage tiers, with attention to handling sustained high write rates
Hints
Hint 1
The write and read patterns are fundamentally different—don't force a single database to handle both
Hint 2
Client-side batching dramatically reduces server request volume
Hint 3
Consider where data lives during an active session versus after completion
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Activity Recording Platform Architecture
The central insight is recognizing two distinct workloads with opposing characteristics:
- Write-heavy ingestion: 1M active sessions generating location points every second
- Read-optimized history: Users querying their past activities and viewing specific routes
Attempting to serve both from a single database creates performance bottlenecks. Instead, separate hot path ingestion from cold storage retrieval.
Capacity Planning and Assumptions
Start by clarifying expectations:
- Point generation rate: At 1 point/second, 1M concurrent sessions yield 1M writes/second
- Client batching: Mobile apps should buffer 5-10 seconds of points locally, reducing server requests to 100-200k/second—a crucial optimization
- Data size per point: Encoding latitude/longitude as integer microdegrees, timestamp offsets, altitude and accuracy yields roughly 20-30 bytes per point
- Ingestion bandwidth: Approximately 30 MB/second of incoming data
- Typical session: A 45-minute activity captures ~2,700 points, totaling 80-90 KB raw or 15-25 KB compressed
- Daily storage: With 10M sessions daily, expect ~200 GB/day compressed, scaling to ~70 TB annually—object storage territory
- Query patterns: Historical browsing has modest QPS; route rendering fetches single complete objects
API Specification
POST /v1/sessions
body: {client_session_id, activity_type, start_time}
response: {session_id}
// Idempotent using client_session_id
POST /v1/sessions/{id}/data
body: {
sequence_number,
points: [{timestamp, lat, lng, altitude, accuracy}],
control_events: [{timestamp, event_type: "PAUSE"|"RESUME"}]
}
response: {live_stats: {elapsed_sec, active_sec, distance_m, current_pace}}
POST /v1/sessions/{id}/complete
body: {end_time, final_sequence}
response: {activity_summary}
GET /v1/users/me/activities?next_cursor=&page_size=20
GET /v1/activities/{id}
GET /v1/activities/{id}/path?detail=low|high
Key principles:
- Stream ordering: Pause/resume events travel in-band with location points to maintain chronological integrity
- Idempotency: Sequence numbers enable safe retries without duplicate processing
- Device time: Use client timestamps since network arrival order doesn't reflect capture order, especially for offline uploads
- Live feedback: Return computed metrics with each batch acknowledgment
Data Models
User accounts (relational store, low volume):
users(user_id PK, email, created_at, default_sharing, privacy_zones)
Activity summaries (sharded by user_id):
Choose either horizontally-sharded PostgreSQL or DynamoDB/Cassandra with partition key user_id and sort key start_time DESC.
activities(
user_id, activity_id, type, state,
start_time, end_time,
elapsed_seconds, active_seconds, distance_meters,
average_pace, elevation_gain,
bounding_box, path_storage_key, preview_image_key,
sharing_mode
)
Retrieving history becomes a single-partition scan with cursor-based pagination.
Point batches during recording (wide-column store):
point_batches(activity_id PK, sequence_number CK, encoded_data BLOB)
Written to Cassandra during active sessions with natural time-ordered clustering.
Finalized paths: After completion, consolidate batches into a single compressed object stored at s3://paths/{user_id}/{activity_id}.pb. Generate simplified polylines for map previews.
Storage Technology Choices
| Content | Technology | Rationale |
|---|---|---|
| User profiles, auth | PostgreSQL | Relational integrity, transactional, manageable size |
| Activity summaries | Sharded Postgres or DynamoDB | Efficient per-user range scans, row-level consistency |
| Real-time session state | Redis with TTL | Sub-millisecond latency for live metric reads |
| Streaming point batches | Kafka → Cassandra | Handles massive append-only writes, partitioned by session |
| Completed paths | S3 with CDN | Cost-effective, durable, whole-object reads, lifecycle tiering |
Why not a unified approach?
- Time-series or wide-column databases excel at write throughput but struggle with "my last 20 activities filtered by type"
- Traditional RDBMS handles filtering and joins well but can't sustain millions of point writes per second
- Geospatial indexes (PostGIS, geohashing) are valuable for "find nearby activities" features but unnecessary for rendering a single user's path
System Architecture
Mobile Apps ──(batches)──> Load Balancer ──> Ingestion API (stateless)
│
▼
Kafka (partitioned by activity_id)
┌────────────┼──────────────┐
▼ ▼ ▼
Stream Processor Batch Writer (Analytics sink)
(Flink/ksqlDB) → Cassandra
│
▼
Redis (live metrics) ──> returned to client
POST /complete ──> Finalization Worker:
fetch all batches → clean/reorder → compute final metrics
→ write summary → compress to S3 → generate thumbnail
Managing write scale:
- Client-side buffering: Batching reduces request rate by 5-10× and enables offline recording
- Stateless ingestion tier: Services validate authorization, enrich with metadata, and publish to Kafka. Scale horizontally behind load balancers.
- Kafka partitioning: Partition by
activity_idto guarantee ordering per session. With ~1,000 partitions, each handles ~1,000 points/second—easily manageable. - Stateful stream processing: Flink maintains small per-activity state (last point, cumulative distance, timer for auto-pause). Outputs live snapshots to Redis.
Metric computation:
- Quality filtering: Discard points with poor accuracy (>50m) or physically impossible speeds for the activity type
- Distance calculation: Sum haversine distances between consecutive filtered points
- Active time: Total elapsed time minus explicitly paused intervals and auto-detected stops (velocity below threshold)
- Pace: Computed as
active_time / distance
Live metrics are approximate. The finalization worker recomputes authoritative values from the complete ordered point set, handling late arrivals from offline uploads.
Reliability mechanisms:
- Kafka replication (factor 3) ensures message durability
- Cassandra writes are idempotent on primary key, making replays safe
- Auto-finalization sweeper handles abandoned sessions after a timeout period
- Eventual consistency for historical data—completed activities may appear in history after a brief delay; clients show local copies during sync
Read path optimization:
- Activity history: Single-shard query with short-lived user-scoped cache
- Path rendering: Summary record contains S3 key; service generates signed URLs or proxies through CDN
- Preview thumbnails: Pre-rendered static map images reduce on-demand rendering load
Common Pitfalls
- Over-indexing on geospatial features: Spatial queries aren't needed for the core path—save them for discovery features
- Trying to compute perfect metrics in real-time: Accept approximation during active sessions; finalize accurately post-completion
- Ignoring offline scenarios: Mobile connectivity is unreliable; design for batch uploads of hours-old data
- Undersizing Kafka partitions: Too few creates hotspots; too many adds coordination overhead
- Storing raw points in RDBMS: Row-per-point models collapse under this write load