Design a ride sharing service
hard 90 minModel riders, drivers, offers and trips as objects.
Video lesson · Chapter 1 of 6
Make a prediction
Theory
Read or listen first. About 2 min.
What it is
A ride sharing service in a low-level design round is the program between a person who wants to go somewhere and a person with a car. It names a price, finds a free driver, asks them, follows the ride and collects the money.
Underneath it is a matching problem with refusals: a limited set of moving resources, a rule for the best one, an offer that can be declined, and a resource that must come back after every ending. Couriers, repair services and support chats have the same shape.
Two objects have a life of their own, the trip and the driver. Most bugs of this problem are places where one of them moves and the other does not.
Why it exists
It mixes the classic themes of an object design round in one story: a state machine, two strategies, observers and a race that is easy to explain and easy to get wrong.
It punishes copying. The well known class diagram with twenty boxes does not say who may change a driver's status, and that is the question that matters.
It grows in honest steps. First one lock and a list, then a spatial index, then several processes. At each step you can say which number forces it.
A short history
1835
James Inman coins the word haversine, for a function that navigators used to find distances on a globe. Tables of it were printed decades earlier.
1891
Friedrich Wilhelm Gustav Bruhn invents the modern taximeter: distance and time become a fare in front of the passenger.
1974
Raphael Finkel and Jon Bentley describe the quadtree, a tree that splits the plane into four parts again and again.
1994
The book Design Patterns names Strategy, State, Observer, Decorator and Facade. Five patterns of this page.
2008
Geohash is put in the public domain: a place becomes a short text, and near places often share its beginning.
2009
Uber is founded, first named Ubercab.
Words to know
- Quote
- A price with everything it depends on and a deadline. Never changed.
- Claim
- Find the best free driver and mark them in one step.
- Offer
- A question to one driver with a time limit. Not yet an assignment.
- Surge
- A factor on the fare when many ask and few are free.
- Haversine
- A formula for the distance between two points on a sphere.
- Geo index
- A structure that answers "who is near here" without looking at everyone.
- Compare and set
- Change a value only if it is still what you expect, as one step.
- Idempotent
- Doing it twice has the same result as doing it once.
- Conflation
- Keeping only the newest of several waiting updates.
- Outbox
- Events saved together with the change, sent afterwards.
- Invariant
- A sentence that is true after every operation.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
Solve it like an interview
New to it? Start with Approach. Revising? Go straight to the mock.
- 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
- 2ScopeAsk what changes the design, then commit to a short list.
- 3API and dataThe contract first, then the data that serves it.
- 4DesignStart with the smallest system that works. Change it only when something breaks.
- 5Deep divesCompare the options before you open them, then say which you would pick.
- 6Explain your choicesAnswer first. Then compare your reasoning.
- 7By levelThe same question is judged differently for mid, senior and staff.
- 8MockAnswer against the clock, then score yourself.
How it works
Step through the idea, or press Play.
Quote. Route, surge and price are fixed for two minutes
Understand it
Start here
Donkey rides at Little Cove
Before any class, spend a day on a beach. Every rule of the design is already there: a board that says who is free, a price said before the ride, and one tag for each animal.
The whole design in eight pictures: quote, claim, ride, release, and one tag for each donkey.
What an interviewer looks for here
Do they find the two lives?
A trip has states, a driver has states. They change together in four places. Miss one and a driver is lost.
Do they claim in one step?
"Find a free driver, then assign" is two steps. Two riders meet in the gap.
Do they separate the rules?
Who is best and how much it costs change for different reasons. Two small interfaces.
Do they ask what a driver may do?
May a driver say no? Then a request is not an assignment. It is an offer, with a deadline.
How to spend the round
Questions
Six questions, and what each answer changes
| Ask | Usual answer | What it changes |
|---|---|---|
| May a driver decline? | Yes, or ignore it for 15 seconds | An offer is a state of its own. Decline tries the next driver |
| Is the price fixed before the ride? | The surge is fixed, the meter decides the rest | A quote object with a deadline |
| Which vehicle types? | Economy, premium, XL | An enum with two facts: price factor and seats |
| Who may cancel, and until when? | The rider, until the ride starts | The transition table |
| One rider, several rides? | One at a time | A map from rider to the ride in progress |
| Shared rides, bookings, tips? | Not today | Said aloud, then left out |
Two lives
The life of a trip
Six states. Every arrow is a method call, and every arrow that is not drawn is a bug if it happens.
A trip
Two lives
The life of a driver
A driver
Where the two lives meet
| Call | Trip | Driver | If one half is forgotten |
|---|---|---|---|
request | REQUESTED | AVAILABLE to OFFERED | Two riders are promised one car |
accept | to ASSIGNED | OFFERED to ON_TRIP | The driver gets a second offer while driving |
decline | stays REQUESTED | back to AVAILABLE | The driver waits for ever for an offer |
complete | to COMPLETED | back to AVAILABLE | The driver earns nothing more today |
cancel | to CANCELLED | back, also from OFFERED | Everyone has a free car that cannot be found |
First try
The design most people draw first
It is not a silly design. It has the right nouns. It fails at the seams: what happens between two calls.
The design to avoid: everything asks a Singleton
1/4People first
Riders and drivers share a name and a phone number, so they get a parent. Nothing in the program ever treats them alike. A driver has a place and a status, a rider has neither.
extends (is a)usesdepends onowns (dies together)
def create_trip_request(self, rider, pickup, destination, vehicle_type): trip = Trip(rider, pickup, destination, vehicle_type) driver = self.matching.find_best_driver(pickup, vehicle_type) # looks if driver: driver.accept_trip(trip) # takes, maybe return trip # result ignoredaccept_trip returns False, nobody reads it, and that rider waits for nobody.Better
The design to reach
The design to reach: one coordinator, one owner of drivers, rules passed in
1/7Start from the verbs
Quote, request, accept, decline, arrive, start, complete, cancel. Eight sentences from the requirements, eight public methods on one coordinator.
owns (dies together)depends onimplementsuseshas (lives on)
quote = service.quote("noor", office, home, VehicleType.ECONOMY)trip = service.request("noor", quote.id, "tap-1") # claims a driver, or noneservice.decline(trip.id, "d1") # the next one is offeredservice.accept(trip.id, "d3")service.arrive(trip.id, "d3")service.start(trip.id, "d3")service.complete(trip.id, "d3", meters=5200, seconds=528)Roles
What each class owns
| Class | Owns | Decides | Does not know |
|---|---|---|---|
RideService | Trips, quotes, keys, who is riding | The order of the steps | Distances, rates, cards |
DriverPool | Drivers and their status | Who is free | Trips and money |
Matching | Nothing | Who is best among the free | Status, locks |
FareRule | Its rates | How much | Trips, drivers |
Trip | Its status | Which move is legal | Other trips |
Quote | The promise | Nothing, it never changes | Everything after it |
The hard part
Two riders, one driver
Find, then assign
Claim in one step
How do you make sure that a driver is offered to one rider only?
BreaksCheck the status in accept
- How
if driver.status == AVAILABLEinaccept_trip, then set it.- Limit
- Two threads pass the check together. Also the loser has already shown a driver to its rider.
- Choose when
- Only in one thread.
WorksOne lock around search and mark
- How
claimholds the pool's lock, ranks the free drivers, marks one OFFERED.- Limit
- The search runs under the lock. With 10,000 drivers that is milliseconds.
- Choose when
- One process and up to some thousands of drivers. Start here.
StrongSearch without a lock, take with compare and set
- How
- Ask a geo index for candidates. Walk down the ranking and try AVAILABLE to OFFERED atomically on each.
- Limit
- The list can be a little old, so some tries fail. The next candidate is taken.
- Choose when
- Many requests at once, or drivers in a shared store.
Choosing
Nearest or best rated?
Three free drivers, all economy. The pickup is at (40, 45) on a flat town plan with a side of 100.
| Driver | Place | Distance | Rating | Nearest | Best rated within 30 |
|---|---|---|---|---|---|
| Alice | (35, 40) | 7.07 | 4.2 | chosen | third |
| Bob | (60, 35) | 22.36 | 4.9 | third | chosen |
| Charlie | (50, 55) | 14.14 | 4.6 | second | second |
Which rule?
Money
A fare in three rates
Standard fare, then factors
Do
- Say the price before the ride and keep the surge in the quote
- Count money in whole cents and round once
- Give the driver back in every ending
- Collect after the ride is over, with a key
Do not
- Make one global surge number
- Let a trip send push messages
- Measure degrees and call them kilometers
- Hold a lock while a map or a bank answers
Is it a class at all?
Summary
The whole topic in one minute.
Two lives: a trip with six states and a driver with four. One pool changes drivers and claims in one step. A quote freezes price facts, an offer may be refused, and matching and fares are rules from outside.
Complete writes the fare, frees the driver and then charges with the trip as key. Cancel frees a driver who was only offered too. Finding may be old, taking may not.
- A trip and a driver each have a life. Draw both, and list where they change together.
- Search and take are one step, in one place: the pool.
- A request leads to an offer. Only an accepted offer is an assignment.
- The quote is a promise: it keeps the surge and never changes.
- Every ending gives the driver back. Money comes after that, with a key.
Sources
- Wikipedia: Haversine formula
- Wikipedia: Taximeter
- Wikipedia: Quadtree
- Wikipedia: Geohash
- Wikipedia: Uber
- H3 documentation
- S2 Geometry
- Redis: GEOSEARCH
- PostGIS: nearest neighbour operator
- OSRM API: table service
- Valhalla
- Stripe: idempotent requests
- Stripe: authorize and capture separately
- Java SE 21 API: LongAdder
- microservices.io: Transactional outbox