Designing a Ride Matching Engine
Difficulty: Intermediate Patterns: Strategy, State, Observer Asked at: Uber, Ola, Rapido, Lyft
Functional Requirements
- Register drivers - drivers go online/offline, update their location in real-time
- Request rides - riders submit pickup and drop locations to request a ride
- Proximity matching - find nearest available drivers within a radius
💡 Proximity matching = pick the drivers whose current coordinates sit closest to the pickup point. Done naively you measure the rider against every online driver, which is why the radius filter exists. - Accept/reject - matched driver can accept or reject; if rejected, offer to next
- Trip lifecycle - states: REQUESTED → MATCHED → EN_ROUTE → IN_PROGRESS → COMPLETED / CANCELLED
💡 A finite state machine (FSM) = a fixed set of states plus the only moves allowed between them, so a trip can never jump from COMPLETED back to IN_PROGRESS. Learn more → - Fare calculation - compute fare based on distance, time, surge multiplier
💡 Surge multiplier = a number above 1.0 that scales the whole fare when demand in an area outruns the supply of drivers. Keeping it a separate multiplier keeps the fare formula to one line.
Non-Functional Requirements
- Thread-safety - concurrent ride requests and driver updates must not corrupt state
💡 Thread-safety = the code stays correct even when several threads run it at the same instant. Two riders must never walk away holding the same driver. - Low-latency matching - proximity search must be fast even with many drivers
💡 Latency = how long one operation takes end to end, as opposed to how many it handles per second. Matching latency is what the rider experiences as the “finding your driver” spinner. - Extensibility - new matching strategies (cheapest, highest-rated) without changing core
💡 This is the open–closed principle from SOLID: a cheapest-driver rule is a new class, not an edit to the matching code that already works.
Core Entities
| Entity | Description |
|---|---|
Location |
Latitude and longitude pair |
Driver |
ID, name, location, status (AVAILABLE, ON_TRIP, OFFLINE) |
Rider |
ID, name, current location |
RideRequest |
Rider + pickup + drop + timestamp |
Trip |
Links rider, driver, route, fare; tracks state |
TripState |
Enum: REQUESTED, MATCHED, DRIVER_EN_ROUTE, IN_PROGRESS, COMPLETED, CANCELLED |
MatchingStrategy |
Interface for driver selection algorithm |
FareCalculator |
Computes fare from distance + time + surge |
RideService |
Orchestrates matching, state transitions, notifications |
💡 Latitude and longitude = the two numbers that pin a point on the globe, north–south and east–west. Every distance, radius and match in this design is derived from a pair of them.
💡 Enum (enumeration) = a type whose value can only be one of a fixed named set, so a trip’s state is one of six listed values and a typo’d state cannot exist.
Class Diagram
classDiagram
class DriverStatus {
<<enumeration>>
AVAILABLE
ON_TRIP
OFFLINE
}
class TripState {
<<enumeration>>
REQUESTED
MATCHED
DRIVER_EN_ROUTE
IN_PROGRESS
COMPLETED
CANCELLED
}
class Location {
-double latitude
-double longitude
+distanceTo(Location other) double
}
class Driver {
-String id
-String name
-Location location
-DriverStatus status
-double rating
+updateLocation(Location loc)
+goOnline()
+goOffline()
}
class Rider {
-String id
-String name
-Location location
}
class RideRequest {
-String id
-Rider rider
-Location pickup
-Location drop
-long timestamp
}
class Trip {
-String id
-RideRequest request
-Driver driver
-TripState state
-double fare
+transitionTo(TripState newState)
+calculateFare()
}
class MatchingStrategy {
<<interface>>
+findDriver(RideRequest, List~Driver~) Driver
}
class NearestDriverStrategy {
+findDriver(RideRequest, List~Driver~) Driver
}
class HighestRatedStrategy {
+findDriver(RideRequest, List~Driver~) Driver
}
class FareCalculator {
-double baseFare
-double perKmRate
-double perMinRate
-double surgeMultiplier
+calculate(double distanceKm, double timeMin) double
}
class RideObserver {
<<interface>>
+onRideRequested(RideRequest)
+onDriverMatched(Trip)
+onTripStarted(Trip)
+onTripCompleted(Trip)
+onTripCancelled(Trip)
}
class RideService {
-Map~String, Driver~ drivers
-Map~String, Trip~ activeTrips
-MatchingStrategy matchingStrategy
-FareCalculator fareCalculator
-List~RideObserver~ observers
+registerDriver(Driver)
+requestRide(RideRequest) Trip
+acceptRide(String tripId)
+startTrip(String tripId)
+completeTrip(String tripId)
+cancelTrip(String tripId)
}
RideService --> MatchingStrategy
RideService --> FareCalculator
RideService --> Trip
RideService --> RideObserver
Trip --> RideRequest
Trip --> Driver
Trip --> TripState
RideRequest --> Rider
RideRequest --> Location
Driver --> Location
Driver --> DriverStatus
MatchingStrategy <|.. NearestDriverStrategy
MatchingStrategy <|.. HighestRatedStrategy
💡 In a class diagram the dashed hollow-headed arrow (<|..) means “implements this interface” and the plain arrow (-->) means “holds a reference to”; <<interface>> and <<enumeration>> label types that carry no data of their own. Learn more →
Key classes:
Location— a latitude/longitude pair plusdistanceTo. It is the one place distance maths lives, so changing the distance formula touches a single class.Driver— identity, live location, availability status and rating.goOnline/goOffline/updateLocationare the only ways that state moves, which keeps the registry honest.RideRequest— one rider’s ask: pickup, drop and the time it was made. It is an input to matching, separate from the trip that may result.Trip— the booking itself once a driver is attached: request, driver, currentTripStateand the final fare.transitionTois the gate every state change passes through.MatchingStrategy— the interface that answers “which driver gets this request?”.NearestDriverStrategyandHighestRatedStrategyare two answers;RideServicenever knows which it holds.FareCalculator— owns the pricing inputs (base fare, per-km, per-minute, surge) so pricing changes never touch trip state handling.RideObserver— the listener interface with one callback per lifecycle event, which is how notifications, logging and analytics stay out of the matching path.RideService— the orchestrator: the driver registry, the active trips, the chosen strategy, the calculator and the observer list, plus every multi-step flow from request to completion.
Design Patterns
| Pattern | Where | Why |
|---|---|---|
| Strategy | MatchingStrategy with Nearest/HighestRated implementations |
Swap matching algorithm at runtime without changing RideService |
| State | TripState enum governs valid transitions |
Prevents invalid state changes (e.g., COMPLETED → IN_PROGRESS) |
| Observer | RideObserver notified on trip lifecycle events |
Decouple notifications, logging, analytics from core logic |
💡 Strategy pattern = put each version of an algorithm behind one shared interface so the caller can swap it. RideService only calls findDriver(request, drivers), so pooling or cheapest-first matching is a new class rather than another branch in the service.
Discussion
Newest first