"Design Uber" in a low-level design round is not about maps. A weak answer draws a Rider, a Driver, a Car and a Trip, writes findNearestDriver(), and stops. The names are right, and the hard parts have not been touched.
The interviewer is checking a few specific things. Two riders who ask at the same moment must never get the same driver. A trip moves through fixed steps, and each side may cancel only at some of them. A fare with surge must come out exact to the cent. And the ride ends before the card is charged, so a declined card must not leave the driver stuck or the money lost.
This article follows a 45 minute interview. We ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.
Ask before you design
The question is vague on purpose. Each question below changes the code, and the right-hand column says how.
| Question | What we assume | What it changes |
|---|---|---|
| One rider per car, or shared rides? | One rider per trip | A Trip has one rider and one driver |
| How are places given? | x and y in km on a flat map, with straight-line distance | A Location record with distanceTo |
| Which driver gets the ride? | The nearest free driver of the right type within 5 km. The business may change the rule | A MatchingStrategy interface |
| Can a driver turn a ride down? | No. The app assigns the ride directly | No offer and no timeout: claiming the driver is the whole assignment |
| What kinds of car? | Economy and Premium, with different rates | A RideType enum, used by matching and by pricing |
| How is the fare calculated? | A base fare, a rate per km and a rate per minute, with a minimum fare | A FareStrategy, and money in exact cents |
| Is there surge pricing? | Yes. Another team sets a multiplier per zone, up to 3x | A SurgePolicy interface, read when the ride is requested |
| Who can cancel, and what does it cost? | Both sides, before pickup. A rider pays $5 after 2 minutes, or at once if the driver has arrived | The trip's states, and a CancellationPolicy |
| How does the rider pay? | A card on file, charged after the ride by an outside card processor | A PaymentGateway interface, and a plan for a declined card |
| How many requests at once? | Many, from many threads | Matching must be safe when two requests want one driver |
The question that matters most is "can a driver turn a ride down?" If drivers can decline, a trip waits in a REQUESTED state while the app offers it to one driver after another, each with a timeout. If they cannot, the app picks and claims a driver while the rider waits on the request screen. We take the simpler answer and come back to offers at the end. The other answer adds states and a timer, but it does not change how a driver is claimed.
Requirements
Functional:
- A driver goes online at a location, reports new locations, and goes offline. Only an online driver who is not on a trip can be matched.
- A rider requests a ride of one type from a pickup to a drop-off. The service assigns the nearest free driver of that type within 5 km, or refuses the request.
- A driver is never on two trips at once, and a rider has at most one trip at a time.
- A trip moves from driver assigned to driver arrived, in progress and completed. The rider or the driver can cancel before pickup, with the fees in the table further down.
- The fare is the base fare plus distance and time, times the surge fixed at request, and never below the minimum fare. Every amount is exact to the cent.
- After the trip, or after a cancellation with a fee, the rider's card is charged. If the charge fails, the trip still ends and the driver is free, but the rider cannot book again until the amount is paid.
Out of scope: maps and road distances, arrival times, a real geographic index, drivers accepting or declining, shared rides, ratings, tips and driver payouts. We come back to these at the end, because each is a likely follow-up.
Everything lives in memory, as is normal for a low-level design interview.
What the code itself must handle:
- Many requests at once.
requestRideis called from many threads, and two of them can pick the same driver. - Rules that change. Matching, fares, surge and cancellation fees each sit behind an interface.
- Outside systems that fail. The card processor can decline, or not answer at all.
- Testable time. Fares and fees depend on time, so the service takes a
Clock.
Finding the classes
Picking the nouns out of the requirements gives a first list. Two of them, driver and trip, carry state that changes and that several threads touch, so they become classes. The rules in the requirements become interfaces, because the business will change them.
Should a rider be a class?
A Rider class with a name, a card and a current trip
It mirrors the app's screens. But the name and the card belong to sign-in and to the card processor, and no rule here reads them. The current trip would be a second copy of something the service already knows.
No: a rider is an id, and RideService keeps two maps keyed by itOur pick
The service needs two facts about a rider: their active trip and any unpaid trip. Two ConcurrentHashMaps keyed by rider id hold them, and each gives one atomic step: claim the active slot, record a debt. If riders gain behaviour of their own, such as saved places, a class can come then.
Data or behaviour?
Some classes only carry values and never change: a location, an amount of money, the lines of a fare, a snapshot of a free driver. In Java these are records. A record's fields are fixed when it is created, and it gets equals, hashCode and toString for free. Driver and Trip are ordinary classes, because their status changes and their methods guard those changes.
The class diagram
The classes fall into three groups:
- Data: the records
Location,Money,FareandDriverSnapshot, and the enumsRideType,DriverStatus,TripStatus,PaymentStatusandParty. - The core:
RideService,DriverandTrip.RideServicecoordinates.DriverandTripeach guard their own state with their own lock, and the methods that change them are package-private, so onlyRideServicecan call them. - Rules and outside systems:
MatchingStrategy,FareStrategy,SurgePolicy,CancellationPolicyandPaymentGateway. All five are interfaces.
Building it
Money
A location is two numbers, kilometres east and north of a fixed corner, and distanceTo is a straight line. Money needs more care. A fare is a sum of parts, surge multiplies it, and the receipt and the card charge must agree to the cent. Money is a record that holds a whole number of cents in a long:
public record Money(long cents) implements Comparable<Money> { public static final Money ZERO = new Money(0); public Money { if (cents < 0) { throw new IllegalArgumentException("Money cannot be negative: " + cents + " cents"); } } public static Money dollars(long dollars, long cents) { return new Money(Math.addExact(Math.multiplyExact(dollars, 100), cents)); } public Money plus(Money other) { return new Money(Math.addExact(cents, other.cents)); } public Money minus(Money other) { return new Money(Math.subtractExact(cents, other.cents)); } /** This amount times numerator / denominator, rounded half up to the nearest cent. */ public Money times(long numerator, long denominator) { if (numerator < 0 || denominator <= 0) { throw new IllegalArgumentException("Cannot scale money by " + numerator + "/" + denominator); } long product = Math.multiplyExact(cents, numerator); return new Money(Math.addExact(product, denominator / 2) / denominator); }Three things to notice. Negative money is refused when it is created. plus and times use Math.addExact and Math.multiplyExact, so an overflow throws instead of wrapping round to a wrong amount. And times is the only place that divides. It multiplies first, then divides once, rounding half up. At $1.20 per km, 8,400 metres is 120 × 8,400 / 1,000 = 1,008 cents, and no fraction is lost on the way.
How is money stored?
A double of dollars
It reads naturally. But 0.1 + 0.2 is not exactly 0.3 in binary floating point, so sums drift by fractions of a cent, and the receipt can disagree with the charge.
BigDecimal
It is exact and handles any rounding rule. But every division needs a scale and a rounding mode, and a US fare never needs less than a cent.
A Money record holding a long of centsOur pick
It is exact and cheap, and it is hard to misuse, because the only way to divide is times, which rounds in one stated way. The cost is that a currency with a different smallest unit needs a currency field or a record of its own.
Drivers
A Driver has a status (OFFLINE, AVAILABLE or ON_TRIP), a location, the time it became free, and its current trip. Every method that reads or changes these is synchronized, so each driver is its own lock. Two methods matter for matching:
synchronized Optional<DriverSnapshot> snapshotIfFree() { if (status != DriverStatus.AVAILABLE) { return Optional.empty(); } return Optional.of(new DriverSnapshot(id, location, idleSince)); } /** Takes this driver for a trip if they are still free. Check and change happen under one lock. */ synchronized boolean claim(String newTripId) { if (status != DriverStatus.AVAILABLE) { return false; } status = DriverStatus.ON_TRIP; tripId = newTripId; return true; }snapshotIfFree copies a free driver's id, location and idle time into a DriverSnapshot record. claim checks that the driver is still AVAILABLE and marks them ON_TRIP in the same synchronized method. goOffline takes the same lock and refuses a driver who is ON_TRIP, so a driver can never be offline and on a trip at once.
Choosing a driver
Which free driver should get the ride? Nearest first is one good answer, and the business will want others.
public interface MatchingStrategy { /** The free drivers worth trying for this pickup, best first. Drivers too far away are left out. */ List<DriverSnapshot> rank(Location pickup, List<DriverSnapshot> freeDrivers);}A strategy gets the pickup and the free drivers, and returns the ones worth trying, best first. It only ranks. It never claims, so no strategy can give one driver to two riders, whatever it does. NearestDriver drops drivers more than 5 km away and sorts the rest by distance, then by id, so equal distances always come out in the same order:
public List<DriverSnapshot> rank(Location pickup, List<DriverSnapshot> freeDrivers) { return freeDrivers.stream() .filter(d -> d.location().distanceTo(pickup) <= maxKm) .sorted(Comparator.comparingDouble((DriverSnapshot d) -> d.location().distanceTo(pickup)) .thenComparing(DriverSnapshot::driverId)) .toList(); }Line 21 keeps a driver whose distance is less than or equal to 5 km, so a driver exactly 5 km away is in range. LongestIdleDriver keeps the same radius but puts the driver who has waited longest first. That shares work more fairly, at the cost of a slightly longer pickup.
Requesting a ride
requestRide puts these pieces together:
public Trip requestRide(String riderId, RideType type, Location pickup, Location dropoff) { Objects.requireNonNull(riderId, "riderId"); Objects.requireNonNull(type, "type"); Objects.requireNonNull(pickup, "pickup"); Objects.requireNonNull(dropoff, "dropoff"); String tripId = "T-" + tripCounter.incrementAndGet(); // Claiming the rider first means a double tap on Request cannot book two cars. if (activeTripByRider.putIfAbsent(riderId, tripId) != null) { throw new ActionNotAllowedException(riderId + " already has a trip"); } try { Trip owed = unpaidTripByRider.get(riderId); if (owed != null) { throw new UnpaidTripException(owed.id(), owed.amountDue()); } int surgePercent = checkedSurge(surge.percentAt(pickup)); Instant now = clock.instant(); Driver driver = claimDriver(tripId, type, pickup); Trip trip = new Trip(tripId, riderId, driver.id(), type, pickup, dropoff, surgePercent, now); trips.put(tripId, trip); return trip; } catch (RuntimeException e) { activeTripByRider.remove(riderId, tripId); throw e; } }- Claim the rider's slot with
putIfAbsentonactiveTripByRider(line 78). A double tap on Request finds the slot taken and is refused, so it cannot book two cars. - Refuse a rider who owes money (lines 82 to 85). This check comes after the slot claim on purpose. A trip that is ending records its debt before it frees the slot, so a new request always sees the debt.
- Read the surge at the pickup, once, and check that it is between 100% and 300%.
- Claim a driver, in
claimDriver. - Clean up on failure. If anything throws, the
catchblock frees the rider's slot, so a refused rider can ask again.
private Driver claimDriver(String tripId, RideType type, Location pickup) { List<DriverSnapshot> free = new ArrayList<>(); Map<String, Driver> freeById = new HashMap<>(); for (Driver driver : drivers.values()) { if (driver.rideType() == type) { driver.snapshotIfFree().ifPresent(snapshot -> { free.add(snapshot); freeById.put(driver.id(), driver); }); } } for (DriverSnapshot candidate : matching.rank(pickup, free)) { Driver driver = freeById.get(candidate.driverId()); // The snapshot can be out of date, so claim() checks again under the driver's lock. if (driver != null && driver.claim(tripId)) { return driver; } } throw new NoDriverAvailableException(type, pickup); }claimDriver takes a snapshot of every free driver of the right type and asks the strategy to rank them. The ranking holds no driver's lock, so by the time we claim, the first driver may already be gone. claim checks again under that driver's lock. If it says no, the loop tries the next driver in the list.
What if the best driver is taken by the time we claim?
Refuse the request
It is simple. But at a busy pickup, most requests would fail while free drivers sit one place down the list.
Rank again from scratch
Each retry sees fresh data. But it rebuilds the snapshot and sorts again for every lost race, and under heavy load a request can lose many times in a row.
Try the next driver in the ranked listOur pick
The list is already sorted, so the next driver is the next best choice, and each attempt is one short lock on one driver. The cost is that the list may be a moment old, so a driver who has just moved could be claimed from slightly outside the radius.
Two requests, one driver
When a concert ends, hundreds of riders at one gate ask at the same moment, and every ranking puts the same nearest driver first.
The design keeps this safe in one place. Driver.claim is synchronized, so checking that a driver is free and marking them ON_TRIP happen as one step. In requestRide, that is the only lock held while anything changes. snapshotIfFree takes each driver's lock for a moment to read it, the maps are ConcurrentHashMaps, trip ids come from an AtomicLong, and each call to rank works on its own list.
The project includes a check, demo/RaceCheck.java. It sends 2,000 riders at 200 drivers from the same gate, through 16 threads that a latch releases together:
2,000 riders, 200 drivers, 16 threads Trips assigned: 200. Refused, no driver free: 1,800 Drivers given two trips: 0
Exactly 200 trips were assigned, one per driver, and the other 1,800 riders were refused. We also ran it in a scratch copy with synchronized removed from claim. Some runs gave a few drivers two trips, and others gave none, so a quick test can pass with the bug in place. With the status check removed instead, so that claim trusted the snapshot, every run we tried gave well over a hundred drivers two trips or more. The exact numbers change from run to run and from machine to machine.
Where do the locks go?
One lock around the whole of requestRide
It is correct and easy to explain. But every request in the city waits while one request builds its snapshot and sorts it, and the sort is the slowest step.
A lock per area of the map
Requests in different areas never wait for each other. But a pickup near an edge needs drivers from two areas, so a request may need two locks, always taken in the same order to avoid deadlock.
One lock per driver, held only to claimOur pick
The only shared change is a driver going from AVAILABLE to ON_TRIP, so that is the only step under a lock. Ranking runs with no lock at all. Each driver's lock is held for one check and two field writes in claim, or a few reads while the snapshot is copied, so requests wait for each other only for moments.
The trip's lifecycle
A trip has five states, and each action is allowed in only some of them.
| State | arrive | start | complete | rider cancels | driver cancels |
|---|---|---|---|---|---|
DRIVER_ASSIGNED | to DRIVER_ARRIVED | refused | refused | to CANCELLED: free for 2 minutes, then $5 | to CANCELLED, no fee |
DRIVER_ARRIVED | refused | to IN_PROGRESS | refused | to CANCELLED, $5 | to CANCELLED, no fee |
IN_PROGRESS | refused | refused | to COMPLETED | refused | refused |
COMPLETED | refused | refused | refused | refused | refused |
CANCELLED | refused | refused | refused | refused | refused |
Each move is a synchronized method on Trip that checks the current state first:
synchronized void arrive() { require(TripStatus.DRIVER_ASSIGNED, "mark the driver as arrived"); status = TripStatus.DRIVER_ARRIVED; } synchronized void start(Instant now) { require(TripStatus.DRIVER_ARRIVED, "start"); status = TripStatus.IN_PROGRESS; startedAt = now; } synchronized void complete(Instant now, long meters, FareStrategy fares) { require(TripStatus.IN_PROGRESS, "complete"); fare = fares.fareFor(rideType, meters, Duration.between(startedAt, now), surgePercent); status = TripStatus.COMPLETED; owe(fare.total()); } synchronized void cancel(Party by, Instant now, CancellationPolicy policy) { Objects.requireNonNull(by, "by"); if (status != TripStatus.DRIVER_ASSIGNED && status != TripStatus.DRIVER_ARRIVED) { throw new ActionNotAllowedException("Cannot cancel trip " + id + ": it is " + status); } Money fee = Money.ZERO; if (by == Party.RIDER) { Duration sinceAssigned = Duration.between(assignedAt, now); fee = policy.riderFee(status == TripStatus.DRIVER_ARRIVED, sinceAssigned); } status = TripStatus.CANCELLED; cancelledBy = by; owe(fee); }The rider's phone and the driver's phone call into the same trip from different threads. If the rider taps Cancel just as the driver taps Start, the trip's lock puts the two calls in order. The second one finds the new state and is refused with an ActionNotAllowedException, whose message the app can show to the person. A bad argument, such as a negative distance, is a programmer's mistake and throws IllegalArgumentException instead.
complete calls the fare strategy while it holds the trip's lock. That is safe because pricing is plain arithmetic on its inputs, and the lock covers only this one trip. GracePeriodCancellation decides the rider's fee: nothing before 2 minutes, $5 from exactly 2 minutes, and $5 at once if the driver has arrived.
When a driver cancels, does the trip end or find another driver?
Find another driver for the same trip
The rider does not have to ask again. But the trip would move back to a waiting state, remember the drivers who already cancelled, and could still fail to find anyone after the rider has waited.
End the trip with no fee, and let the rider ask againOur pick
Every state still moves forward only, and requestRide already does the matching. The rider's app can send the new request at once. Moving the trip back to matching is a follow-up.
Fares and surge
public Fare fareFor(RideType type, long meters, Duration rideTime, int surgePercent) { if (meters < 0 || rideTime.isNegative() || surgePercent < 100) { throw new IllegalArgumentException( "Bad trip: " + meters + " m, " + rideTime + ", surge " + surgePercent + "%"); } Rates r = rates.get(Objects.requireNonNull(type, "type")); Money distance = r.perKm().times(meters, 1000); Money time = r.perMinute().times(rideTime.toSeconds(), 60); Money metered = r.base().plus(distance).plus(time); Money surged = metered.times(surgePercent, 100); Money topUp = surged.max(r.minimum()).minus(surged); return new Fare(r.base(), distance, time, surged.minus(metered), topUp); }MeteredFare holds a Rates record for each ride type. Car types differ only in their numbers, so they are data in a map, not a subclass per car, which is the choice the Composition over inheritance page makes for cab fares. The distance charge is the rate per km times the metres over 1,000. The time charge is the rate per minute times the seconds over 60. Surge multiplies the metered amount. If the result is below the minimum fare, a top-up line lifts it to the minimum, so the receipt's lines always add up to the total.
Asha's 8.4 km, 18 minute ride costs $2.50 + $10.08 + $5.40 = $17.98 before surge. At 150%, surge adds $8.99, for $26.97. The order of surge and the minimum is a choice. With surge first, a $6.40 ride at 150% costs $9.60. With the minimum first, the same ride would cost $10.50, because the surge would multiply the $7.00 floor.
When is the surge multiplier fixed?
When the trip ends
The fare uses the latest demand. But a rider who agreed to 1.5x could be charged 3x for a surge that started mid-ride, which they could not see or avoid.
At request, stored in the tripOur pick
requestRide reads SurgePolicy once, and Trip keeps surgePercent in a final field. complete passes it to the fare strategy, so a later change in surge cannot touch a trip already made. The cost is that a ride requested just before surge rises is cheaper, which the business accepts.
Paying after the trip
The ride is over before the card is charged. completeTrip does four things, in this order:
public Trip completeTrip(String tripId, long meters) { if (meters < 0) { throw new IllegalArgumentException("Distance cannot be negative: " + meters); } Trip trip = trip(tripId); Instant now = clock.instant(); trip.complete(now, meters, fares); Driver driver = driver(trip.driverId()); driver.moveTo(trip.dropoff()); driver.release(trip.id(), now); settle(trip); return trip; } // The debt is recorded before the rider is free to book, and cleared only once the charge succeeds. private void settle(Trip trip) { boolean owes = trip.payment() == PaymentStatus.UNPAID; if (owes) { unpaidTripByRider.put(trip.riderId(), trip); } activeTripByRider.remove(trip.riderId(), trip.id()); if (owes && charge(trip)) { trip.markPaid(); unpaidTripByRider.remove(trip.riderId(), trip); } } private boolean charge(Trip trip) { try { return payments.charge(trip.riderId(), trip.amountDue(), trip.id()); } catch (RuntimeException e) { // No answer: the card may have been charged, so the debt stays and a retry reuses the same key. LOG.log(System.Logger.Level.WARNING, "Charge for " + trip.id() + " got no answer", e); return false; } }- Fix the fare.
Trip.completecalculates the fare under the trip's lock and marks the tripUNPAID. - Free the driver. The driver moves to the drop-off and is released, so they can take the next ride straight away.
- Record the debt.
settleputs the trip inunpaidTripByRider, and only then frees the rider's active slot. So there is no moment when the rider can book and the debt is missing. - Charge the card, with no lock held. If the charge goes through, the trip is
PAIDand the debt is cleared.
If the card is declined, the debt stays. The trip is still COMPLETED and the driver is still free. The rider's next requestRide throws an UnpaidTripException that names the trip and the amount. The rider adds a card, and the app calls payUnpaid, which charges again.
An exception from the card processor is different from a decline. A timeout can arrive after the money was taken, so we do not know what happened. charge logs it and treats the trip as unpaid, and completeTrip still returns, because the driver's job is done. The trip id is the idempotency key. The gateway promises that a key that was charged is never charged again, and that a declined key may be tried again. So payUnpaid reuses the key after a timeout, and the card is charged at most once. After a definite decline, the same key is tried again with the new card.
When is the driver freed: at drop-off or after payment?
After the payment succeeds
In the Parking Lot, the spot is freed only after payment, because the car is still in it. Copying that here would keep a driver idle while a bank answers, and for ever if the card is never fixed.
At drop-off, before the chargeOur pick
The driver's work is done when the rider gets out, so the driver goes back to AVAILABLE straight away. The money is between the rider and us, so it is recorded as a debt on the rider, not as a hold on the driver.
The card fails after the trip. What happens?
Keep the trip open until it is paid
Everything about the trip stays in one place. But the trip would wait on the rider's bank, and a trip that never closes would block the rider's active slot for ever.
Write the amount off
The rider and the driver both carry on. But every declined card becomes a free ride.
Complete the trip, record a debt, and refuse the next request until it is paidOur pick
The ride is finished and the driver is free. The amount is not lost, and the rider meets it at the moment they want something: the next request. The cost is a second way to pay, payUnpaid, and a rider who is turned away until they fix their card.
The final design
RideService is the core. It owns the drivers, the trips and the two maps keyed by rider id, and it reaches matching, fares, surge, cancellation fees and the card processor only through interfaces. Driver and Trip each guard their own state with their own lock.
| S.No. | The question | What we chose | Why |
|---|---|---|---|
| 1 | Should a rider be a class? | No: a rider is an id, and RideService keeps two maps keyed by it | The service needs only the active trip and the debt |
| 2 | How is money stored? | A Money record holding a long of cents | It is exact, and times is the only place that divides |
| 3 | What if the best driver is taken by the time we claim? | Try the next driver in the ranked list | The list is already sorted, so the next driver is the next best |
| 4 | Where do the locks go? | One lock per driver, held only to claim | Only the move to ON_TRIP needs a lock |
| 5 | When a driver cancels, does the trip end or find another driver? | End the trip with no fee, and let the rider ask again | States only move forward |
| 6 | When is the surge multiplier fixed? | At request, stored in the trip | The rider pays the surge they saw |
| 7 | When is the driver freed: at drop-off or after payment? | At drop-off, before the charge | A bank never holds up a driver |
| 8 | The card fails after the trip. What happens? | Complete the trip, record a debt, and refuse the next request until it is paid | Nothing is lost and no one is stuck |
Here is Asha's ride from the demo, end to end:
- Asha's phone calls
RideService.requestRide.activeTripByRider.putIfAbsentclaims her slot, andunpaidTripByRidershows no debt. SurgePolicy.percentAtreturns 150 for the stadium zone.claimDrivertakessnapshotIfFreefrom each ECONOMY driver and passes the list toMatchingStrategy.rank.Driver.claimtakes Omar's lock, finds himAVAILABLEand marks himON_TRIP. This is the only lock held while anything changes.requestRidestores a newTripwithsurgePercent150.- Omar's phone calls
driverArrived,startTripandcompleteTrip, each under the trip's lock.Trip.completecallsFareStrategy.fareFor, which fixes the fare at $26.97. Driver.releasefrees Omar at the drop-off.settlerecords the debt, frees Asha's slot, and callsPaymentGateway.chargewith the keyT-1. This is the outside call, and no lock is held during it.
The complete code
Here is the whole project. Click any class name to jump to its file, or use Find a file to search. Badges in the tree show what each file is: a class, an interface, an enum or a record.
package ride; import java.time.Clock;import java.time.Instant;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicLong; import exception.ActionNotAllowedException;import exception.NoDriverAvailableException;import exception.UnpaidTripException;import geo.Location;import matching.DriverSnapshot;import matching.MatchingStrategy;import payment.PaymentGateway;import pricing.CancellationPolicy;import pricing.FareStrategy;import pricing.SurgePolicy;import vehicle.RideType; public class RideService { private static final System.Logger LOG = System.getLogger(RideService.class.getName()); private final MatchingStrategy matching; private final FareStrategy fares; private final SurgePolicy surge; private final CancellationPolicy cancellation; private final PaymentGateway payments; private final Clock clock; private final Map<String, Driver> drivers = new ConcurrentHashMap<>(); private final Map<String, Trip> trips = new ConcurrentHashMap<>(); private final Map<String, String> activeTripByRider = new ConcurrentHashMap<>(); private final Map<String, Trip> unpaidTripByRider = new ConcurrentHashMap<>(); private final AtomicLong tripCounter = new AtomicLong(); public RideService(MatchingStrategy matching, FareStrategy fares, SurgePolicy surge, CancellationPolicy cancellation, PaymentGateway payments, Clock clock) { this.matching = Objects.requireNonNull(matching, "matching"); this.fares = Objects.requireNonNull(fares, "fares"); this.surge = Objects.requireNonNull(surge, "surge"); this.cancellation = Objects.requireNonNull(cancellation, "cancellation"); this.payments = Objects.requireNonNull(payments, "payments"); this.clock = Objects.requireNonNull(clock, "clock"); } public Driver registerDriver(String driverId, String name, RideType rideType) { Driver driver = new Driver(driverId, name, rideType); if (drivers.putIfAbsent(driverId, driver) != null) { throw new IllegalArgumentException("Driver " + driverId + " is already registered"); } return driver; } public void goOnline(String driverId, Location at) { driver(driverId).goOnline(at, clock.instant()); } public void goOffline(String driverId) { driver(driverId).goOffline(); } public void updateLocation(String driverId, Location at) { driver(driverId).moveTo(at); } public Trip requestRide(String riderId, RideType type, Location pickup, Location dropoff) { Objects.requireNonNull(riderId, "riderId"); Objects.requireNonNull(type, "type"); Objects.requireNonNull(pickup, "pickup"); Objects.requireNonNull(dropoff, "dropoff"); String tripId = "T-" + tripCounter.incrementAndGet(); // Claiming the rider first means a double tap on Request cannot book two cars. if (activeTripByRider.putIfAbsent(riderId, tripId) != null) { throw new ActionNotAllowedException(riderId + " already has a trip"); } try { Trip owed = unpaidTripByRider.get(riderId); if (owed != null) { throw new UnpaidTripException(owed.id(), owed.amountDue()); } int surgePercent = checkedSurge(surge.percentAt(pickup)); Instant now = clock.instant(); Driver driver = claimDriver(tripId, type, pickup); Trip trip = new Trip(tripId, riderId, driver.id(), type, pickup, dropoff, surgePercent, now); trips.put(tripId, trip); return trip; } catch (RuntimeException e) { activeTripByRider.remove(riderId, tripId); throw e; } } private Driver claimDriver(String tripId, RideType type, Location pickup) { List<DriverSnapshot> free = new ArrayList<>(); Map<String, Driver> freeById = new HashMap<>(); for (Driver driver : drivers.values()) { if (driver.rideType() == type) { driver.snapshotIfFree().ifPresent(snapshot -> { free.add(snapshot); freeById.put(driver.id(), driver); }); } } for (DriverSnapshot candidate : matching.rank(pickup, free)) { Driver driver = freeById.get(candidate.driverId()); // The snapshot can be out of date, so claim() checks again under the driver's lock. if (driver != null && driver.claim(tripId)) { return driver; } } throw new NoDriverAvailableException(type, pickup); } public Trip driverArrived(String tripId) { Trip trip = trip(tripId); trip.arrive(); return trip; } public Trip startTrip(String tripId) { Trip trip = trip(tripId); trip.start(clock.instant()); return trip; } public Trip completeTrip(String tripId, long meters) { if (meters < 0) { throw new IllegalArgumentException("Distance cannot be negative: " + meters); } Trip trip = trip(tripId); Instant now = clock.instant(); trip.complete(now, meters, fares); Driver driver = driver(trip.driverId()); driver.moveTo(trip.dropoff()); driver.release(trip.id(), now); settle(trip); return trip; } public Trip cancelTrip(String tripId, Party by) { Trip trip = trip(tripId); Instant now = clock.instant(); trip.cancel(by, now, cancellation); driver(trip.driverId()).release(trip.id(), now); settle(trip); return trip; } /** Charges again for the rider's unpaid trip. Returns true if the rider now owes nothing. */ public boolean payUnpaid(String riderId) { Trip trip = unpaidTripByRider.get(riderId); if (trip == null) { return true; } if (!charge(trip)) { return false; } trip.markPaid(); unpaidTripByRider.remove(riderId, trip); return true; } // The debt is recorded before the rider is free to book, and cleared only once the charge succeeds. private void settle(Trip trip) { boolean owes = trip.payment() == PaymentStatus.UNPAID; if (owes) { unpaidTripByRider.put(trip.riderId(), trip); } activeTripByRider.remove(trip.riderId(), trip.id()); if (owes && charge(trip)) { trip.markPaid(); unpaidTripByRider.remove(trip.riderId(), trip); } } private boolean charge(Trip trip) { try { return payments.charge(trip.riderId(), trip.amountDue(), trip.id()); } catch (RuntimeException e) { // No answer: the card may have been charged, so the debt stays and a retry reuses the same key. LOG.log(System.Logger.Level.WARNING, "Charge for " + trip.id() + " got no answer", e); return false; } } private int checkedSurge(int percent) { if (percent < 100 || percent > SurgePolicy.MAX_PERCENT) { throw new IllegalStateException("The surge policy returned " + percent + "%"); } return percent; } public Trip trip(String tripId) { Trip trip = trips.get(tripId); if (trip == null) { throw new IllegalArgumentException("No trip " + tripId); } return trip; } public Driver driver(String driverId) { Driver driver = drivers.get(driverId); if (driver == null) { throw new IllegalArgumentException("No driver " + driverId); } return driver; }}demo/Main.java runs one evening at a stadium. Three riders ask for ECONOMY rides near the gate, and one of them cancels. Asha rides 8.4 km. Then Dev takes a PREMIUM ride with a card that is declined, pays later, and cancels a second ride after Lena has arrived:
18:00 Maya and Omar drive ECONOMY, Lena drives PREMIUM. The stadium zone has 150% surge.
18:00 Asha asks for ECONOMY at (0.0, 0.0)
T-1: Omar (D-2) is coming, surge 150%
18:00 Ben asks for ECONOMY at (0.5, 0.5)
T-2: Maya (D-1) is coming, surge 150%
18:00 Chen asks for ECONOMY at (0.0, 0.0)
refused: No ECONOMY driver is free near (0.0, 0.0)
18:01 Ben cancels T-2 after 1 minute: fee $0.00. Maya is AVAILABLE
18:04 Omar picks up Asha. T-1 is IN_PROGRESS
18:04 Asha tries to cancel T-1
refused: Cannot cancel trip T-1: it is IN_PROGRESS
18:22 Omar drops Asha after 8.4 km and 18 minutes
card: Asha charged $26.97 for T-1
base $2.50 + distance $10.08 + time $5.40 + surge $8.99 = $26.97
18:22 Dev asks for PREMIUM at (6.0, 6.0)
T-4: Lena (D-3) is coming, surge 100%
18:26 Lena drops Dev after 1.2 km and 4 minutes
card: Dev declined for $12.00
base $5.00 + distance $2.88 + time $2.40 + surge $0.00 + minimum fare top-up $1.72 = $12.00
18:26 T-4 is COMPLETED, payment UNPAID. Lena is AVAILABLE
18:26 Dev asks for PREMIUM at (6.0, 7.2)
refused: Pay $12.00 for trip T-4 before booking again
card: Dev charged $12.00 for T-4
18:26 Dev adds a new card. Paid in full: true
18:26 Dev asks for PREMIUM at (6.0, 7.2)
T-6: Lena (D-3) is coming, surge 100%
18:26 Lena tries to go offline
refused: Lena cannot go offline during trip T-6
card: Dev charged $5.00 for T-6
18:26 Dev cancels T-6 after Lena arrived: fee $5.00, payment PAIDNotice three things in the output. Ben's request went to Maya because Omar was already on T-1, and Chen was refused because no ECONOMY driver was left. After Dev's card was declined, T-4 was COMPLETED and Lena was AVAILABLE, but Dev's next request was refused until he paid. His receipt shows a $1.72 top-up line, because $10.28 of base, distance and time is below the $12.00 minimum. And a refused request still uses up a trip number, which is why the ids skip T-3 and T-5.
Follow-up questions
After the core design, the interviewer adds a requirement to see how the design bends. For each one, say which class changes and which do not.
| The interviewer asks | What changes | What does not |
|---|---|---|
| "Let drivers accept or decline." | TripStatus gains REQUESTED and OFFERED. The service claims one driver, offers the ride, and releases them on a decline or a timeout, then tries the next. | Driver.claim, the strategies, pricing and payment. |
| "Find another driver when one cancels." | A driver's cancel moves the trip back to matching, leaving out drivers who cancelled. TripStatus gains a waiting state. | Driver.claim, pricing and payment. |
| "Use real roads and arrival times." | A new MatchingStrategy that ranks by arrival time from a routing service. The driver app reports the measured distance, as it already does. | RideService, Driver.claim, the trip's states. |
| "Make matching fast with a million drivers." | RideService keeps free drivers in a grid of cells and snapshots only the cells near the pickup. goOnline, updateLocation, claims and releases keep the grid current. | Driver.claim under its own lock, the strategies, and everything after matching. |
| "Shared rides." | A large change. A trip holds several riders with their own pickups, a driver is claimed by a pool, and the fare is split, so Trip, Driver.claim and MeteredFare all change. | Money, SurgePolicy, CancellationPolicy, PaymentGateway, and the MatchingStrategy interface, with a new pooling rule behind it. |
| "Show the price before the rider confirms." | A quote record with the estimated fare and the surge, valid for a few minutes. requestRide takes the quote and uses its surge. | Matching, claiming, the trip's states. |
| "Tell the rider's phone when the driver arrives." | A listener list on Trip, called after the trip's lock is released. | Matching, pricing and payment. |
| "Ratings after the trip." | A Rating record kept by trip id, accepted only for a COMPLETED trip. A new matching rule can use the averages. | The trip's states and pricing. |
| "Let riders tip." | A second charge on the same trip with its own key, such as T-4-tip. A Trip holds one amountDue and one PaymentStatus, and unpaidTripByRider holds one debt per rider, so a declined tip needs its own debt record. | Fares, matching and the trip's states. |
In most rows the change lands in a strategy, a new record or a new state, and Driver.claim stays as it is. Two rows are bigger: offers and shared rides change the trip's states and what a claim means.
What the interviewer looks for
Mid-level
A mid-level candidate shows clear classes for drivers and trips, enums for the states, a nearest-driver search, and fares in integer cents. They say that two requests could pick the same driver and that some locking is needed, even if the lock covers more than it has to.
Senior
A senior candidate shows everything above and gives the reasons. They separate ranking from claiming, put the check under each driver's lock, and fall back to the next driver. They draw the trip's states with who may cancel when, fix the surge at request, and free the driver before the charge. They say what happens when the card is declined.
Staff+
A staff candidate leads the conversation through the trade-offs without being asked. They point out what this design does not handle: a ranking that is a moment old, a timeout after the money was taken, and a scan over every driver for each request. They say how each would be handled at scale, such as a grid of cells for free drivers, and a job that retries debts for riders who never come back to pay.
Common mistakes
- Finding the nearest free driver, then assigning them in a separate step. Two requests can both see the same driver free. The check must happen again under the driver's lock.
- One lock around all of matching. It is correct, but every request in the city waits for the slowest sort.
- Failing a request when the first choice is taken. The next driver in the list is free and close.
doublefor money. Sums drift by fractions of a cent, and the receipt disagrees with the charge.- Reading the surge at the end of the trip. The rider pays a price they never saw.
- Holding the driver until the card is charged. A slow or declined card keeps a driver idle.
- Retrying a charge that timed out with a new key. The rider can be charged twice.
Summary
- Ask first whether drivers can decline, how fares work and who may cancel. Each answer changes the code.
- A rider is an id.
DriverandTripare classes, and each guards its own state with its own lock. - Rank a snapshot with no lock, then claim drivers in that order.
claimchecks again under the driver's lock, and a lost race moves on to the next driver. - Trip states are an enum, and each move checks the state under the trip's lock.
- Keep money as a
longof cents, multiply before dividing, and round once per line. - Fix the surge when the ride is requested.
- Free the driver at drop-off, record the debt before the charge, and reuse the trip id as the payment key.