System Design: Designing Nearby Friends (Real-time Geospatial)
Designing a "Nearby Friends" feature (like Snapchat's Snap Map or Facebook's Nearby Friends) is a unique challenge. Unlike Yelp or Uber, where the entities (restaurants or cars) are relatively stable, every user in "Nearby Friends" is moving, creating a massive volume of real-time geospatial updates.
1. Core Requirements
- Real-time Updates: Users see their friends' locations moving on a map.
- Proximity Notifications: Get notified when a friend is within 1km.
- Privacy: Users can opt-out or use "Ghost Mode."
- Scalability: Handling millions of users sending GPS pings every 5-10 seconds.
2. High-Level Architecture
- Location Service: Receives GPS updates via WebSockets.
- Presence Store: Fast in-memory store for the "Latest Location."
- Pub/Sub System: To broadcast location updates to interested friends.
3. The Scaling Challenge: Fan-out
If a user has 500 friends, every time they move, 500 people need an update.
- Naive Approach: Querying the database every 5 seconds for "Who is near me?" will crash the system.
- The Solution: Geospatial Pub/Sub.
- Divide the world into Geohash cells (e.g., 5km x 5km).
- When a user moves, they publish their new location to a Redis Pub/Sub channel corresponding to their Geohash cell.
- Their friends "subscribe" to the Geohash cells where their friends are currently located.
4. Presence and Storage: Redis Geo
Redis Geospatial indexes (GEOADD, GEORADIUS) are perfect for this.
- Performance: Redis stores locations in a Sorted Set using Geohashes, providing (\log N)$ performance for updates and queries.
- Lifecycle: Use a short TTL for location data. If a user hasn't sent a ping in 10 minutes, their location is expired and they are removed from the map.
5. Reducing Bandwidth: Adaptive Pinging
Sending a GPS ping every 5 seconds drains mobile batteries and wastes server bandwidth.
- The Optimization: If a user is stationary (detected by accelerometer), stop sending pings. If they are moving fast (in a car), increase the ping frequency.
6. Privacy and Security
- Data Anonymization: Store only the Geohash, not the exact raw latitude/longitude for historical analytics.
- Permission Service: A dedicated service that checks friend relationships and privacy settings before any location data is broadcast.
Summary
Building "Nearby Friends" is about managing High-Frequency Streams. By leveraging Geospatial Pub/Sub and in-memory stores like Redis, you can build a system that connects millions of people in the real world with sub-second accuracy.
