Real-Time Location Aggregation System with Consensus Protocols
System DesignModel answerLast updated
Build a system that aggregates streaming location data into grid cells, surfaces high-activity regions, and compare distributed consensus approaches.
You need to design a system that processes real-time location updates from millions of mobile users, aggregates them into geographic grid cells, and identifies the most active regions.
Part 1: System Design
Your system should:
- Accept continuous location streams (latitude, longitude, timestamp, availability status) from mobile clients via persistent connections
- Divide the geographic area into a grid and track which cells have the most active, available users
- Provide an API to retrieve the K cells with the highest user counts, either globally or filtered by geographic region
- Push live updates to monitoring dashboards and client applications
Part 2: Consensus Algorithms
Explain how Paxos and Raft solve the distributed consensus problem. What are the fundamental differences in their approach, and when would you choose one over the other?
Context:
- This is an analytics use case where approximate counts are acceptable
- Availability is more important than perfect consistency
- The system should handle network partitions and server failures gracefully
Design the architecture, data model, APIs, and key algorithmic choices. Discuss trade-offs, scalability bottlenecks, and how consensus fits into the overall system.
Hints
Hint 1
Consider how to avoid counting the same user multiple times when they send frequent location updates, and what happens when they move between cells
Hint 2
Partitioning strategy matters: should you shard by user ID or by geographic region? Each choice affects how you compute rankings
Hint 3
For consensus algorithms, focus on the sequence of message exchanges and how each protocol handles leader election and log replication differently
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Real-Time Location Aggregation System
This problem tests your ability to design a streaming data pipeline, make partitioning decisions, and understand distributed systems fundamentals. I'll walk through both parts systematically.
Part 1: System Design
Requirements and Assumptions
First, let me clarify the functional and operational requirements:
Functional scope:
- Mobile apps send location updates (lat/lng, status, timestamp) periodically, roughly every 3-5 seconds
- The system divides the world into grid cells and maintains a count of active, available users per cell
- Clients can query for the top K cells with the most users, either worldwide or within a specific metropolitan area
- Dashboards receive live updates showing how cell counts change over time
Scale estimates:
- 4 million concurrent active users at peak, each updating every 4 seconds = ~1 million writes/second
- Each update is approximately 100 bytes, yielding ~100 MB/s of ingestion bandwidth
- Using a geospatial grid system at appropriate resolution gives us roughly 1-2 million active cells globally
- Perhaps 300,000 concurrent dashboard viewers need real-time updates
Quality attributes:
- Latency: cell counts should reflect reality within 3-5 seconds
- Consistency: approximate counts are fine; brief double-counting during cell transitions is acceptable
- Availability: the system should remain operational during partial failures since this supports operational dashboards
API Design
// Client -> Server (persistent WebSocket)
{
"type": "location_update",
"user_id": "u456",
"latitude": 40.7589,
"longitude": -73.9851,
"status": "AVAILABLE",
"timestamp": 1700000000000
}
// Query API
GET /api/v1/heatmap/top-cells?k=50®ion=nyc&resolution=8
Response: [
{ "cell_id": "882a1072c3fffff", "user_count": 287 },
{ "cell_id": "882a1072c7fffff", "user_count": 251 },
...
]
// Server -> Dashboard (WebSocket push, batched every 2 seconds)
{
"type": "cell_updates",
"timestamp": 1700000002000,
"changes": [
{ "cell_id": "882a1072c3fffff", "count": 289, "delta": +2 },
...
]
}
Data Model and Grid Choice
Grid system: I recommend using Uber's H3 hexagonal grid system. Hexagons provide uniform distance to all neighbors (unlike squares with diagonal issues) and support hierarchical aggregation. Alternative approaches like S2 cells or geohash work but have different trade-offs.
Core data structures:
-
User state table (in-memory, partitioned):
- Key: user_id
- Value: { current_cell_id, status, last_update_timestamp }
- Purpose: track which cell each user occupies to enable proper counting
-
Cell counters (in-memory per partition):
- Key: cell_id
- Value: active_user_count
- Purpose: maintain the current count for each cell
-
Regional top-K indexes (Redis sorted sets):
- Key: "topk:{region}:{resolution}"
- Members: cell_id with score = count
- Purpose: serve queries quickly without scanning all cells
Architecture
Mobile Clients (WebSocket)
↓
Location Ingestion Gateway (load balanced, stateless)
↓
Message Queue (Kafka, partitioned by region)
↓
Stream Processing Layer (Flink or similar)
• Converts lat/lng → cell_id
• Maintains per-user state
• Computes per-cell counts
• Identifies local top-K cells
↓
┌───┴───┐
↓ ↓
Redis Pub/Sub Channels
(top-K) (cell updates)
↓ ↓
Query Fanout
Service Servers
↓ ↓
REST Dashboard
Clients WebSocket
The metadata layer (partition assignments, configuration) runs on a consensus system like etcd (Raft-based).
Critical Design Decisions
1. Counting distinct users, not events
A user sending 15 updates per minute should count as one user, not fifteen. Each stream processor maintains user state:
On update for user U at location L:
1. Compute new_cell = h3_from_latlng(L)
2. Retrieve old_cell from state[U]
3. If old_cell != new_cell:
decrement counter[old_cell]
increment counter[new_cell]
4. Update state[U] = {new_cell, timestamp}
5. Set TTL timer for U (e.g., 30 seconds)
When the TTL expires without a refresh, decrement that user's cell. This handles app crashes and network dropouts.
2. Partitioning strategy
Two options:
-
Partition by user_id: Keeps all updates for one user on the same processor, ensuring consistent state transitions. However, a cell's count is now split across many partitions, requiring a scatter-gather to compute top-K.
-
Partition by coarse geographic region: Each cell is owned by exactly one partition. The global top-K is simply a merge of each partition's local top-K, which is mathematically exact.
I recommend geographic partitioning using parent cells (e.g., H3 resolution 4 covers ~1,290 km² per cell). When a user crosses partition boundaries, the old partition sees a TTL expiry while the new partition sees a fresh arrival. Brief double-counting is acceptable given our consistency requirements.
3. Top-K computation
Per partition, maintain a min-heap of size K or use a Redis sorted set:
- On each cell count change, update the structure
- Every 1-2 seconds, extract the top-K snapshot
- Use
ZINCRBYfor updates andZREVRANGE 0 K-1for retrieval
For the global view, merge S regional top-K lists (each with K entries) in O(SK log K) time, which is trivial even for hundreds of regions.
4. Real-time updates to dashboards
Dashboard servers subscribe to pub/sub channels organized by coarse geographic tiles. They:
- Batch updates over 1-2 second windows to limit bandwidth
- Send only deltas, not full snapshots
- Use sticky sessions so reconnects fetch the current state from Redis
With 30,000 connections per server, 300K viewers need 10 servers.
5. Handling hot spots
Major cities like New York or airports can create skew. Mitigation:
- Split hot regions into finer-grained partitions
- Use dynamic rebalancing based on partition load metrics
- Store partition assignments in the consensus layer (etcd) so all processors see consistent topology
Trade-offs
| Decision | Advantage | Disadvantage |
|---|---|---|
| H3 hexagons | Uniform geometry, hierarchical | Requires external library |
| Geographic partitioning | Exact top-K merge, no scatter | Regional hot spots possible |
| Batched push updates | Bounded bandwidth | 1-2s update latency |
| In-memory state with checkpoints | Low latency | Recovery replays recent data |
| AP consistency model | High availability | Cross-boundary inconsistency possible |
Failure Handling
The stream processors checkpoint state (user map, cell counts) to distributed storage every 10-30 seconds. On failure:
- Restore state from the last checkpoint
- Replay messages from Kafka starting at the checkpointed offset
- Within 10-15 seconds, the system recovers and self-heals as fresh updates arrive
Part 2: Consensus Algorithms
Both Paxos and Raft solve distributed consensus: getting multiple replicas to agree on a sequence of log entries despite crashes and message delays. Both guarantee safety (never returning inconsistent results) and guarantee liveness under partial synchrony (messages eventually delivered).
Paxos
Paxos separates the system into three roles: proposers (who suggest values), acceptors (who vote), and learners (who learn the chosen value).
The protocol in two phases:
Phase 1 - Prepare:
- A proposer selects a unique, monotonically increasing ballot number N
- Sends PREPARE(N) to a majority of acceptors
- Each acceptor responds with PROMISE(N) if N is higher than any ballot it has seen, and includes any value it has already accepted
Phase 2 - Accept:
- If the proposer receives promises from a majority, it sends ACCEPT(N, V) where V is either the highest-ballot value returned in promises, or its own value if no promises contained a value
- Acceptors that promised N now accept this proposal and notify learners
- Once a majority accepts, the value is chosen
Key characteristics:
- Handles multiple concurrent proposers through the ballot number mechanism
- Can have dueling proposers that interfere with each other, requiring exponential backoff
- The protocol is modular: Multi-Paxos adds a stable leader and batching to achieve practical performance
- Notoriously difficult to understand and implement correctly
Raft
Raft was designed explicitly for understandability. It solves the same problem but structures it around a strong leader and explicit leader election.
Core components:
Leader election:
- All replicas start as followers
- If a follower doesn't hear from a leader within a randomized timeout, it becomes a candidate
- The candidate increments its term number and requests votes
- A candidate that receives votes from a majority becomes leader
- Randomized timeouts prevent split votes
Log replication:
- All writes go through the leader
- The leader appends entries to its log and sends APPEND_ENTRIES RPCs to followers
- An entry is committed once stored on a majority of replicas
- Followers with stale logs catch up by following the leader's log
Safety:
- A candidate cannot win an election unless its log is at least as up-to-date as a majority's logs
- This ensures committed entries persist across leader changes
Key characteristics:
- Strong leader model simplifies the design: all decisions flow through one node
- Leader election is explicit and term-based
- More understandable and easier to implement correctly than Paxos
- Widely deployed in production systems (etcd, Consul)
Comparison
| Aspect | Paxos | Raft |
|---|---|---|
| Leadership | No required leader; Multi-Paxos adds one | Strong leader required |
| Understandability | Complex, requires significant study | Designed for clarity |
| Dueling leaders | Possible without care | Prevented by randomized timeouts |
| Election process | Implicit in ballot numbers | Explicit election phase |
| Log structure | Can have gaps (Basic Paxos) | Continuous, no gaps |
| Industry adoption | Google Chubby, Spanner variants | etcd, Consul, Raft-based systems |
Integration with the Location System
Consensus algorithms belong in the control plane, not the data plane:
- Use Raft (via etcd or ZooKeeper) to store partition assignments, cluster membership, and configuration
- Stream processors read partition topology from the consensus layer
- When partitions rebalance, the consensus layer coordinates the handoff
- The consensus layer itself has 3-5 nodes, far fewer than the processing fleet
The hot path (location updates, counting) runs on the stream processors without coordination, achieving high throughput. Consensus provides the foundation for cluster management, not per-request coordination.
Common Mistakes
- Using consensus for every write: This serializes everything through the leader. For analytics, eventual consistency suffices.
- Confusing consensus with replication: Consensus is about agreeing on state; replication is about copying data. You can replicate without consensus.
- Ignoring the CAP theorem: During partitions, you must choose availability or consistency. This system chooses availability.
- Over-engineering the grid: Using sub-meter precision creates billions of cells. Match resolution to the use case.
This design handles millions of updates per second, provides low-latency aggregation, survives failures, and scales horizontally while using consensus only where it's truly needed.