Design Uber/Lyft
hard 55 minBuild a service like Uber or Lyft: a rider asks, a nearby driver comes, both watch the map, and the fare is paid.
See it run
Ride hailing, one hop at a time: requesting, reporting positions, choosing a driver, following the trip, paying and pricing.
Operations
Request a ride
Save, answer at once, then find, claim and offer.
Step 1 of 13
Tap request
quote
q-51
key
k-1
The app sends the quote ID and a key. Why: a retry after a lost signal must not make a second ride.
Step 1: Tap request
def request(rider, quote_id, key): quote = quotes.valid(quote_id) hold(rider, quote) # reserve money ride = db.insert_once(key, quote, "matching") return 202, ride.id # matching continuesdef match(ride): for driver in best(candidates(ride)): if not db.claim(driver, ride, seconds=12): continue # someone else was first if offer(driver, ride) == "accept": return db.assign(ride, driver) # checks offer and time return retry_wider(ride)- Latency
- first offer < 3 s
- Load
- 231/s
- Peak
- 694/s
- Offer
- 12 s
The claim changes a row only if the driver is free. Everything before it is a suggestion.
In the real world
The same design uber/lyft doing real jobs. Pick one and step through it.
One zone after a concert. Requests are counted over five minutes.
Step 1 of 5
A normal evening
| Minute | Requests | Free | Ratio | Target | Price |
|---|---|---|---|---|---|
| 0 | 40 | 50 | 0.8 | 1.0 | 1.00 |
1.00
Fewer requests than drivers.
Step 1: A normal evening
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Read, check, write
criticalTwo matchers read free and both assign the driver.
Wrongif driver.state == "free": driver.state = "offered" save(driver)Rightrows = db.execute("""UPDATE drivers SET state='offered' WHERE id=%s AND state='free'""", id)if rows == 0: next_driver()A claim without an end
criticalA crash leaves the driver taken for ever.
Wrongclaim(driver)Rightclaim(driver, ends=now() + 12)# a sweeper frees offers past their endCounting on expiry inside a set
majorEXPIRE removes a key, not one member of a geo set.
WrongGEOADD city lon lat d1EXPIRE d1 60RightGEOADD city lon lat d1ZADD seen:city now d1 # and sweepA new key on a retry
criticalThe provider sees a different payment and charges again.
Wrongprovider.capture(fare, key=uuid4())Rightprovider.capture(fare, key=payment.id)Headings without a circle
minor350 and 10 degrees are 20 apart, not 340.
Wronggap = abs(a - b)Rightgap = min((a - b) % 360, (b - a) % 360)
Interview tips
Split the data first
- Positions may be lost.
- Rides may not.
- Say it in the first minute.
Bring numbers
- 694 rides a second at peak.
- 500,000 positions a second.
- Four offers in a minute.
Plan for silence
- Dead phone, dead server, dead region.
- Every claim has an end.
- The rider's safety comes first.
Know where to stop
- One town needs one database.
- Positions force memory.
- Cities force homes.