AlgoViz

Design a ride sharing service

hard 90 min

Model riders, drivers, offers and trips as objects.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:42

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

  1. 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.

  2. 1891

    Friedrich Wilhelm Gustav Bruhn invents the modern taximeter: distance and time become a fare in front of the passenger.

  3. 1974

    Raphael Finkel and Jon Bentley describe the quadtree, a tree that splits the plane into four parts again and again.

  4. 1994

    The book Design Patterns names Strategy, State, Observer, Decorator and Facade. Five patterns of this page.

  5. 2008

    Geohash is put in the public domain: a place becomes a short text, and near places often share its beginning.

  6. 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.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 4

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.

One morning with three donkeys
FREEBiscuitCloverPepperCloverBiscuitPepper

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

AskUsual answerWhat it changes
May a driver decline?Yes, or ignore it for 15 secondsAn 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 restA quote object with a deadline
Which vehicle types?Economy, premium, XLAn enum with two facts: price factor and seats
Who may cancel, and until when?The rider, until the ride startsThe transition table
One rider, several rides?One at a timeA map from rider to the ride in progress
Shared rides, bookings, tips?Not todaySaid 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

There is no arrow from IN_PROGRESS to CANCELLED: people who are in the car arrive somewhere, and that ride is completed there.

Two lives

The life of a driver

A driver

Where the two lives meet

CallTripDriverIf one half is forgotten
requestREQUESTEDAVAILABLE to OFFEREDTwo riders are promised one car
acceptto ASSIGNEDOFFERED to ON_TRIPThe driver gets a second offer while driving
declinestays REQUESTEDback to AVAILABLEThe driver waits for ever for an offer
completeto COMPLETEDback to AVAILABLEThe driver earns nothing more today
cancelto CANCELLEDback, also from OFFEREDEveryone has a free car that cannot be found
"Back" means AVAILABLE, or OFFLINE if the driver asked to stop after this ride.

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

«abstract»User# id, name, phone# rating: double+ updateRating(stars)Driver- status, location- totalEarnings+ acceptTrip(trip): bool+ goOnline()Rider+ requestRide(a, b): Trip

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)

Python
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 ignored
Two requests run this together. Both find Alice. One accept_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

RideService- trips: Map<id, Trip>- riding: Map<rider, id>- byKey: Map<key, Trip>- lock: Lock+ quote(...): Quote+ request(...): Trip+ accept, decline(...)+ arrive, start(...)+ complete(...): Trip+ cancel(...)

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)

A question mark means that the answer may be nothing. No free driver is an ordinary result, not an error.
Python
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)
The same story as seven calls.

Roles

What each class owns

ClassOwnsDecidesDoes not know
RideServiceTrips, quotes, keys, who is ridingThe order of the stepsDistances, rates, cards
DriverPoolDrivers and their statusWho is freeTrips and money
MatchingNothingWho is best among the freeStatus, locks
FareRuleIts ratesHow muchTrips, drivers
TripIts statusWhich move is legalOther trips
QuoteThe promiseNothing, it never changesEverything 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 == AVAILABLE in accept_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
claim holds 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.

DriverPlaceDistanceRatingNearestBest rated within 30
Alice(35, 40)7.074.2chosenthird
Bob(60, 35)22.364.9thirdchosen
Charlie(50, 55)14.144.6secondsecond
The same call with two rules. Nearest keeps the wait short, best rated suits a premium service. "Best rated within five minutes" is both ideas in one.

Which rule?

Money

A fare in three rates

Standard fare, then factors

fare=(250+150⋅km+25⋅min)×type×surgecents\text{fare} = \bigl(250 + 150 \cdot km + 25 \cdot min\bigr) \times \text{type} \times \text{surge} \quad \text{cents}
5.2 km in 8.8 minutes, economy, no surge: 250 + 780 + 220 = 1250 cents. With surge 2.0: 2500. The rates are example numbers.

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