Ride-sharing service
Design location tracking, geospatial matching and trip state.
By Invicly Tech, , in System Design Deep Dive. About 11 minutes to read.
In short
A ride-sharing service tracks millions of moving drivers, matches riders to nearby available drivers and manages each trip's lifecycle. Location writes are huge and ephemeral, so they live in memory with a geospatial index.
Explained simply
A ride-sharing app like Uber or Lyft connects people who need a ride with drivers nearby. The rider asks for a ride, the system finds a good driver close by, the driver accepts, and both apps follow the trip on a map until it ends and the rider pays.
The hard part is that drivers move all the time. Each driver's phone sends its GPS position every few seconds. With millions of drivers, that is over a million updates every second. Most of these positions are only useful for a few seconds, so they are kept in fast memory, not written forever to a normal database.
To find drivers near a rider quickly, the map is cut into small squares, and each driver is filed under the square they are in. Finding nearby drivers then means looking in the rider's square and the squares around it, instead of checking every driver in the city.
A trip moves through clear steps: requested, accepted, driver arrived, in progress, completed, or cancelled. The system must make sure one driver is never given two riders at the same time, and that money is charged exactly once.
Press Play on a diagram to walk through it one step at a time.
- 1Rider and driver apps
Drivers send GPS every 4 seconds
- 2API gateway and WebSockets
Requests in, live updates out
- 3Location service
In-memory geohash index of available drivers
- 4Matching service
Finds nearby drivers, sends offers
- 5Trip service
Trip state machine in a transactional DB
- 6Payments and history
Charges, receipts and analytics
- Rider to Matching svc: Request ride (pickup lat/lng)1Request ride (pickup lat/lng)
- Matching svc to Location svc: Nearby available drivers?2Nearby available drivers?
- Location svc to Matching svc: Drivers in geohash cell and neighbours3Drivers in geohash cell and neighbours
- Matching svc to Driver: Offer trip (15 s to accept)4Offer trip (15 s to accept)
- Driver to Matching svc: Accept5Accept
- Matching svc to Rider: Driver assigned, ETA 4 min6Driver assigned, ETA 4 min
- 1Driver app
Sends lat, lng, heading every ~4 s
- 2Location gateway
Validates, routes by city or cell
- 3In-memory geo index
Updates the driver's current cell
- 4Live trip push
If on a trip, forward to the rider
- 5Stream to storage
Kafka to cheap storage for history
In depth
Requirements and location volume
Clarify scope: riders request rides and see the driver approach; drivers go online, get offers and accept; we show an ETA (estimated time of arrival) and a fare estimate; payments happen at the end. Surge pricing, pooling and scheduled rides are usually out of scope unless asked.
The big number is location updates. With 5 million drivers online sending a position every 4 seconds, that is 1.25 million writes per second. Each update is small, about 50 to 100 bytes, so bandwidth is modest (around 100 MB/s), but the write rate rules out a normal relational database for live positions. Ride requests are far fewer: 20 million trips a day is about 230 per second on average. So the design splits into a huge, simple, in-memory location path and a small, careful, transactional trip path.
- Location path: very high write rate, short-lived, in memory
- Trip path: low rate, must be correct and durable
- Keep the last position, stream history to cheap storage
Geohash, quadtrees and cells
A geohash turns a latitude and longitude into a short string by repeatedly halving the world's longitude and latitude ranges and interleaving the bits. Each extra character makes the cell smaller: 5 characters is about 4.9 km by 4.9 km, 6 characters about 1.2 km by 0.6 km. Points with the same prefix are in the same cell, so nearby search becomes a lookup by prefix. Because two close points can sit on opposite sides of a cell edge, always search the cell plus its 8 neighbours.
A quadtree splits a region into four children whenever it holds too many drivers, so dense downtown areas get small cells and empty countryside gets big ones. It adapts to density but is harder to update with millions of moving points. Uber built and open-sourced H3, a grid of hexagons; hexagons have neighbours at equal distance, which makes rings of cells around a point cleaner. In practice, Redis GEO commands (which use geohash internally) are a fine interview answer.
- Fixed grid, string prefixes
- Easy to shard by prefix
- Search cell plus 8 neighbours
- Built into Redis GEO
- Splits busy areas into smaller cells
- Adapts to density
- Costly to rebalance with moving points
- Good for mostly static places
- Hexagon cells at many resolutions
- All neighbours at equal distance
- Clean rings around a point
- Open-sourced by Uber
Matching a rider to a driver
Matching starts with candidate search: available drivers within a few kilometres, nearest first. Straight-line distance is only a first filter, because a driver 500 m away across a river may be 10 minutes by road. So the matcher asks a routing service for real ETAs for the top 10 or so candidates and ranks by ETA, plus other factors like driver rating or acceptance rate.
Then it sends an offer to the best driver with a short timeout, for example 15 seconds. Before sending, it reserves the driver atomically so no other request can grab them, for example a Redis SET with NX and an expiry, or a conditional database update. If the driver declines or the timer expires, the reservation is released and the next candidate gets the offer. Busy systems can batch requests every second or two and solve the assignment for many riders at once, which beats greedy first-come matching.
- Filter by distance, rank by road ETA
- Reserve the driver atomically with a TTL
- Timeout and fall back to the next candidate
Trip state and consistency
The trip is the part that must be correct. Store it in a transactional database and allow only valid transitions: REQUESTED to ACCEPTED, ACCEPTED to ARRIVED, ARRIVED to IN_PROGRESS, IN_PROGRESS to COMPLETED, and CANCELLED from the early states. Enforce this with a conditional update, such as UPDATE trips SET state = 'ACCEPTED' WHERE id = ? AND state = 'REQUESTED'. If zero rows change, someone else got there first.
Each transition emits an event onto a queue so other services react: notifications, live tracking, pricing, and payments. Payment requests carry an idempotency key (a unique ID for that one charge) so a retry never charges twice. During the trip, the driver's location is pushed to the rider over a WebSocket, and the GPS trail is streamed to cheap storage for fare calculation, disputes and analytics.
Learn it in 6 short steps
About 40m each. Track them with a timer in your plan.
- 1Clarify rider and driver requirements~40m
- 2Estimate location update volume~40m
- 3Design the API and trip data model~40m
- 4Index locations with geohash or quadtree~40m
- 5Match riders to drivers~40m
- 6Model trip state transitions~40m
Key points
- Location updates are write-heavy and short-lived, so keep them in memory.
- Geohash or quadtree cells turn nearby searches into small key lookups.
- Search the rider's cell plus neighbours to avoid edge misses.
- Lock a driver while an offer is pending to prevent double booking.
- Model trips as a state machine with strongly consistent transitions.
Key terms
Tap a card to flip it. 0/5 known
Examples
Scale: 5M active drivers, update every 4 s
-> 1.25M location writes/s, kept in memory
Redis: GEOADD drivers:available lng lat driverId
GEOSEARCH drivers:available FROMLONLAT lng lat
BYRADIUS 2 km ASC COUNT 10
trips(trip_id, rider_id, driver_id, state,
pickup, dropoff, fare, updated_at)
REQUESTED -> ACCEPTED -> ARRIVED -> IN_PROGRESS -> COMPLETEDLocation volume, geo queries and trip states.
Nearby search with Redis GEO
Keep one geo set per city for available drivers. When a driver pings, GEOADD updates their position (it overwrites the old one). When a driver accepts a trip, remove them with ZREM, since a geo set is a sorted set underneath. A ride request runs GEOSEARCH for the 10 closest drivers within 3 km. Note that GEOADD takes longitude first, then latitude, which is a common bug.
GEOADD drivers:blr 77.5946 12.9716 d101
GEOADD drivers:blr 77.6012 12.9752 d102
GEOSEARCH drivers:blr FROMLONLAT 77.5960 12.9720 \
BYRADIUS 3 km ASC COUNT 10 WITHDIST
# 1) d101 0.17 km
# 2) d102 0.78 km
SET reserve:d101 trip88 NX EX 15 # lock driver for the offer
ZREM drivers:blr d101 # after acceptTwo riders, one driver
Two requests arrive in the same second and both pick driver d101 as best. Step 1: matcher A runs SET reserve:d101 tripA NX EX 15 and gets OK. Step 2: matcher B runs the same with tripB and gets nil, because the key already exists. Step 3: B moves to its next candidate. Step 4: d101 accepts trip A; the trip row moves to ACCEPTED with a conditional update. If d101 had ignored the offer, the key would expire after 15 seconds and d101 would become available again.
Quick reference
- 5M drivers every 4 s = 1.25M location writes/s: keep them in memory
- Geohash length 5 ≈ 4.9 km cells; length 6 ≈ 1.2 x 0.6 km
- Always search the rider's cell plus its 8 neighbours
- Rank candidates by road ETA, not straight-line distance
- Reserve a driver atomically (SET NX EX) before sending an offer
- Trip transitions use conditional updates: WHERE state = expected
- Redis GEOADD takes longitude first, then latitude
- Use idempotency keys on payment calls
Common mistakes
- Writing every GPS ping to a relational database.
- Searching only the rider's own geohash cell.
- Offering one driver to two riders at once.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
List the trip states and the valid transitions between them, including cancellation.
- Exercise 2medium
Estimate memory to hold the current position of 5 million drivers, then say how you would shard it.
- Exercise 3hard
A driver drives from one city shard into another during a trip. How do you keep tracking and matching correct?
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is a geohash in simple terms?
- It is a short string that names a box on the map. Longer strings mean smaller boxes, and places with the same starting letters are close together.
- How does the app show the driver moving smoothly?
- The server pushes new positions every few seconds over a WebSocket, and the app animates the car between points so it looks smooth.
- How is ETA calculated?
- A routing service finds the best road path on a map graph and adds expected travel time per road segment, often adjusted with live and historical traffic data.