r/LowLevelDesign • u/Prashant_MockGym • Oct 24 '26
Amazon LLD: Design Ride-Hailing System Like Uber, Ola
Design ride sharing app like uber has been asked frequently in Amazon low level design rounds in 2026. Discussions included everything from driver matching, ride booking and till payment processing.
Tricky bit in this question is how to find nearest drivers efficiently. I have started with brute force, going through all drivers and comparing locations. It is inefficient but will help you understand the whole thing. There were multiple ways to improve this solution, and I have gone with quad tree because it adapts automatically with real world traffic.
This tutorial is in Java.
You can find the python version here: https://github.com/prsnt558908/CodeZymSolutions/tree/main/301-500/458-ride-hailing-system-like-uber/q-458-python-tutorial.md
You can practice this and other Amazon Low Level Design and DS & Algo round questions on CodeZym.
PS: I also take LLD Mock interviews https://topmate.io/prashant_priyadarshi
Problem Statement
Build an in-memory RideHailingSystem class that handles trip booking, driver matching, tracking, cancellation, fares and payments.
Trip flow: REQUESTED → ACCEPTED → IN_PROGRESS → COMPLETED. Any non-final state can also go to CANCELLED. A rider or driver can have only one active trip at a time.
Key Methods
addRideradds a rider and fails on a duplicate ID.updateDriverLocation/setDriverAvailabilitytrack drivers and toggle availability. Availability can't be changed during a trip.updateSurgePricingsets a zone's multiplier:- 100 if there's no demand or requests ≤ drivers
- 150 if requests ≤ 2× drivers
- 200 if requests are higher than that
- 300 if there are requests but no drivers
estimateFare/completeTripuseceil((base + distance × perUnit) × surge / 100). A trip keeps the surge in effect when it was requested.requestTripassigns the nearest available driver by squared distance. Ties go to the smallestdriverId.acceptTrip/startTrip/cancelTriphandle state changes with driver and rider checks. A cancelled trip costs 0 and frees the driver.processPaymentonly works on completed trips and allows up tomaxPaymentAttempts. Resending the samepaymentRequestIdreturns the original result. It returnsSUCCEEDED,RETRY_PENDING,FAILEDorINVALID_REQUEST.getTripDetailsreturns a comma-separated snapshot of the trip.
Core Idea
We model the system with three small classes, Rider, Driver and Trip, each kept in a HashMap by id so every lookup is instant. A simple enum guards the fixed trip states. The only hard part is finding the nearest free driver quickly, so we give that job its own small class. We start with a version that checks every driver, then replace it with a fast quadtree. No design pattern is needed here: Strategy and State sound useful, but with one fixed matching rule and a few fixed trip states, they would only add extra classes.
For the fast matcher, we compare two common spatial indexes: a grid and a quadtree. We code the quadtree, because it adapts on its own to crowded city centers and empty outskirts, which is exactly how real cities look.
Payments are made safe to retry by remembering the answer we gave for every payment request id.
Building Blocks
Driver
Keeps the location, an available flag and activeTripId.
availablesays whether the driver can get a new request.activeTripIdsays whether the driver is on a trip.setDriverAvailabilitymust fail while it is set.
It also has isBetterThan(), the matching rule in one place: the closer driver wins, and on a tie the smaller id wins.
Distances are long. A squared distance can reach 8 × 10¹², which does not fit in an int.
Rider
Keeps activeTripId. A rider who already has an active trip cannot request another one.
Trip
Keeps the booking details, the state, the fare and the payment details.
It also copies the zone's surge percentage at request time. Later surge updates must not change this trip's fare, so we never look the zone up again for this trip.
paymentResults remembers the first answer given for each payment request id.
Maps in RideHailingSystem
| Map | Why we need it |
|---|---|
drivers, riders, trips | O(1) lookup by id |
surgeByZone | Current surge of each zone. A missing zone means 100 |
paymentRequestOwner | Which trip used each payment request id, so no other trip can reuse it |
How the Main Operations Work
Trip lifecycle
REQUESTED → ACCEPTED → IN_PROGRESS → COMPLETED, and any of the first three can move to CANCELLED.
acceptTrip, startTrip and completeTrip each check two things: the trip is in the one allowed state, and the caller is the assigned driver. If a check fails, nothing changes.
requestTrip reserves the chosen driver. It removes the driver from the matcher, marks it unavailable and links the rider and the driver to the trip.
When a trip ends, releasePeople() does the reverse. It clears both links, marks the driver available and gives it back to the matcher. On completion, we first move the driver to the destination.
Fares
subtotal = baseFare + distance × farePerUnit
fare = ceil(subtotal × surge / 100)
Adding 99 before dividing by 100 rounds up, using plain integer math with no floating point. For example, (601 + 99) / 100 = 7, while (600 + 99) / 100 = 6.
estimateFare uses the zone's current surge. completeTrip uses the surge saved inside the trip.
Payments that are safe to retry
Think of a payment request id as a receipt number. If the app sends the same request twice, for example after a network glitch, we must not create a second attempt.
processPayment checks things in this order:
- The trip is missing or not
COMPLETED: returnINVALID_REQUEST. - The id was already used by another trip: return
INVALID_REQUEST. - The id was already used by this trip: return the old answer. The new
gatewaySuccessfulvalue is ignored. - The payment is already
SUCCEEDEDorFAILED: return that status, with no new attempt. - Otherwise, count one attempt. Success gives
SUCCEEDED. A failure givesRETRY_PENDINGwhile attempts remain, andFAILEDon the last allowed attempt.
After steps 4 and 5, we save the id together with its answer.
Step 3 runs before step 4 on purpose. If an old failed request id is sent again, it still returns RETRY_PENDING, even when a later request has already succeeded.
Solution 1: Check Every Available Driver
LinearDriverMatcher keeps every available driver in a HashSet. To find the nearest one, it checks them all.
It has the same three methods as the quadtree matcher in Solution 2: addDriver, removeDriver and findNearestDriver. So every other class is the same as in the Solution 2 code below.
To run this version, use this class in place of QuadNode and QuadTreeDriverMatcher, and change the matcher line in RideHailingSystem to LinearDriverMatcher matcher = new LinearDriverMatcher();.
/**
*/
The Problem With Solution 1
Every requestTrip looks at every available driver. That is O(D) work for each request.
With 100,000 drivers and tens of thousands of requests, that is billions of distance checks. Yet a rider never needs a driver from the far side of the map. We only need to look nearby.
Solution 2: Spatial Index With a Quadtree
A spatial index groups drivers by where they are, so a request only looks near the pickup. Two common choices are a grid and a quadtree.
Option 1: Grid
Cut the map into equal square cells, like a chessboard. A HashMap maps each cell to the drivers inside it, and a driver's cell is found with one division.
To search, check the pickup's cell, then the ring of 8 cells around it, then the next ring of 16, and so on, until no unseen cell can hold a closer driver.
2 2 2 2 2
2 1 1 1 2
2 1 0 1 2
2 1 1 1 2
2 2 2 2 2
Pros
- Very simple: one map from cell to drivers.
- Adding, removing or moving a driver is O(1).
- Very fast when drivers are spread evenly and the cell size fits.
Cons
- One cell size for the whole map. A busy downtown packs hundreds of drivers into one cell, while empty outskirts make the search walk through ring after ring of empty cells.
- The right cell size is a guess. Drivers keep moving, so a size that fits in the morning can be wrong by evening.
Option 2: Quadtree
Start with one big square that covers the whole map. When a square holds more than 10 drivers, split it into 4 equal smaller squares. Busy areas end up with many small squares, and quiet areas stay as one big square.
+-------+-------+
| | . |. .|
| . +---+---+
| |. .|. .|
+-------+---+---+
| | |
| . | . |
| | |
+-------+-------+
Here each dot stands for a few drivers. The busy top-right quarter has split into 4 smaller squares, while the quiet quarters stay whole.
Pros
- Adapts by itself: small squares where drivers are crowded, big squares where they are few.
- Nothing to tune except the leaf size, and any small number like 10 works.
- One check can skip a whole square, however big: when it has no drivers, or when it is too far away.
Cons
- A little more code: a node class, splitting, and a search that calls itself (recursion).
- Adding, removing or moving a driver walks down the tree, so it costs O(depth) instead of O(1). Here the depth is at most 21, so it stays cheap.
Why We Pick the Quadtree
Real cities are uneven. The center is crowded, the outskirts are thin, and drivers move between them all day. A grid has to pick one cell size for all of that. A quadtree reshapes itself as drivers move, so it stays fast without any tuning.
| Feature | Grid | Quadtree |
|---|---|---|
| Shape | One layer of equal cells | Squares that split when crowded |
| Add, remove, move a driver | O(1) | O(depth), at most 21 steps |
| Drivers spread evenly | Fast | Fast |
| Crowded center, empty outskirts | Slow | Fast |
| Tuning | Needs a good cell size | Just a leaf size, like 10 |
How the Quadtree Works
Nodes. Each node is a square. A leaf keeps up to 10 drivers in a plain list. Every node also keeps count, the number of drivers anywhere inside its square.
The root square. Coordinates go from -1,000,000 to 1,000,000. The root square starts at -1,048,576 and has side 2,097,152, which is 2²¹. A power of two can be halved evenly all the way down to a 1 × 1 square.
Adding a driver. Walk down from the root to the leaf whose square holds the driver, adding 1 to count on the way. Put the driver in the leaf's list. If the list now has more than 10 drivers, split the leaf into 4 squares and move each driver into the square it stands in. A new square that is still too crowded splits again.
Removing a driver. Do the same walk, subtracting 1 from count, and take the driver out of the leaf's list.
We never merge squares back together. An empty square just stays, and the search skips it because its count is 0. This keeps removing as simple as adding.
Moving a driver is a remove at the old spot plus an add at the new spot.
Finding the Nearest Driver
The search starts at the root and carries the best driver found so far:
- Skip a square whose
countis 0. - Skip a square if even its nearest point is farther than our best driver. Nothing inside it can win or tie.
- In a leaf, check every driver one by one.
- In a split square, search the child on the pickup's side first, then the other three.
The child on the pickup's side is the closest one. A good driver found there early lets step 2 skip more squares later.
To measure the distance from the pickup to a square, we use the square's nearest point. On each axis, that is how far the pickup sits outside the square, or 0 when it is inside: dx = max(0, left - x, x - right), and the same for dy. The squared distance is then dx² + dy², as usual.
Ties are safe. Step 2 skips a square only when it is strictly farther than the best driver. A square at exactly the same distance is still searched, so a driver at the same distance with a smaller id can still win.
Corner Case: Drivers on the Same Point
Real cars have length and breadth, so two cars never stand on the exact same point. The tests, though, use plain integer points, so many drivers can share one. A 1 × 1 square cannot split any further, so it simply keeps all of them. That is the node.size > 1 check in insert.
Code
QuadNode and QuadTreeDriverMatcher replace LinearDriverMatcher, and one line in RideHailingSystem changes. Everything else is the same as Solution 1.
/** States of a trip. COMPLETED and CANCELLED are terminal. */
2
u/SaiKenat63 Oct 25 '26
This is being asked in SDE1 interviews as well?
1
u/Red-Panda-Is-Here Oct 24 '26
Helpful
1
u/nian2326076 Oct 27 '26
Finding the nearest drivers efficiently can be complex. You've made a good start with the quad tree approach. As you prepare, practicing with real interview questions can help clarify your understanding and improve your response. For Amazon-specific questions, check out Amazon Interview Questions.
If you're also looking for job opportunities in tech roles, LandOffer offers features like job alerts and resume-based matching to help streamline your search. You can learn more at LandOffer.