Courses / System Design Interview / Chapter 30
Module 7 · Design Problems II: Rides and Social Feeds · Chapter 30 of 49
Design a Ride-Hailing Service like Uber
Builds on Core Concepts: RPCs, Consistency, Failures and Time, Back-of-the-Envelope Estimates, Distributed Message Queues, Distributed Task Schedulers, Design a Maps and Navigation Service like Google Maps and Design a Nearby Places Service like Yelp. Next up: Design a Microblogging Service like Twitter.
Part 1 · Requirements and estimates
What the service must do
A ride-hailing app matches a rider who wants a car with a nearby driver who is free, within seconds. This chapter designs that matching for a large city, with the focus on finding nearby drivers, never giving one driver to two riders, and tracking the trip through its stages.
The functional requirements are: a rider asks for a ride from a pickup point to a destination and sees a fare estimate; the system finds nearby available drivers and offers them the trip; a driver accepts or declines; the rider sees the match; and the trip moves through pickup, travel and drop-off, after which the fare is computed and paid. Ratings, driver onboarding, ride sharing, scheduled rides and the maps that draw routes are out of scope. The maps chapter covers routes and ETAs.
The non-functional requirements are about time and correctness. A match should take seconds, so the rider does not give up. Driver positions must be fresh to within a few seconds. A driver must never be assigned to two trips at once, and a trip must never be assigned to two drivers, because both mistakes strand a person. The service must also keep working through a data centre failure, and a phone that loses signal for a minute should not break a trip.
| Question to ask | Answer we assume |
|---|---|
| How large is the city? | 2 lakh drivers online at the peak |
| How often do drivers report position? | Every 4 seconds |
| How many trips? | 20 lakh a day, 10 percent in the peak hour |
| How is a driver chosen? | Nearby and free, offered one at a time |
| How long does a driver have to answer? | 10 seconds |
| What about live tracking during the trip? |
Sizing the stream and the requests
The estimate separates two very different loads. The location stream is every online driver reporting its position, and it never stops. The ride requests are rare by comparison, but each one triggers a search and a chain of offers. The script names its assumptions at the top, as in the estimates chapter, and prints each result on its own line.
# Inputs are assumptions for one large city. drivers_online = 2_00_000 # drivers with the app on, at the busy hour update_every_s = 4 # seconds between location updates update_bytes = 50 # driver id, position, heading, time trips_per_day = 20_00_000 # completed trips in the city peak_share = 0.10 # share of a day's trips in the peak hour offers_per_trip = 3 # drivers asked before one accepts updates_per_s = drivers_online / update_every_s mbps = updates_per_s * update_bytes * 8 / 1e6 trip_requests_per_s = trips_per_day * peak_share / 3600 offers_per_s = trip_requests_per_s * offers_per_trip print(f"location updates per second: {updates_per_s:,.0f}") print(f"update bandwidth: {mbps:,.0f} Mbps") print(f"updates per day if kept (16 busy hours): " f"{updates_per_s * 3600 * 16:,.0f}") print(f"trip requests per second at peak: {trip_requests_per_s:,.0f}") print(f"offers per second at peak: {offers_per_s:,.0f}") print(f"updates per trip request: " f"{updates_per_s / trip_requests_per_s:,.0f}")
Python 3.12.10. All inputs are assumptions.
location updates per second: 50,000 update bandwidth: 20 Mbps updates per day if kept (16 busy hours): 2,880,000,000 trip requests per second at peak: 56 offers per second at peak: 167 updates per trip request: 900
Output of the estimate.
The city receives 50,000 location updates a second, about 20 Mbps, so the bytes are small and the count is large. If every update were stored for a 16-hour day, that would be 288 crore rows a day, which tells us not to store them all. Ride requests arrive at about 56 a second at the peak, and with three offers per trip the matcher sends about 167 offers a second.
The ratio is the main fact. For every ride request the service takes in about 900 location updates. Updates need a very fast, in-memory place to land, and requests need a careful, correct decision. The two jobs get different components.
What the numbers decide
Updates for every ride request: ≈ 900 (50,000 divided by 56)
Read it as steps
Two lakh drivers reporting every four seconds is 50,000 writes a second, about 900 for each ride request.
The scene gives the same arithmetic in the order a person would say it. It shows that the write load is the location stream and not the rides. At 50,000 updates a second, a database row per update is not an option, so positions go into an in-memory index that holds only the latest position of each driver, and old positions are dropped or sampled to a trip log.
It also shows that the matching path is small. At 56 requests and 167 offers a second, one well-built service can run it, and the difficulty is correctness: two matchers working at once must not give the same driver to two riders. That is a concurrency problem on a few thousand rows, not a throughput problem, and the fifth lesson solves it with one conditional update.
Why are drivers' location updates not written to a database row each?
- At 50,000 a second the count is too high, and only the latest position matters. An in-memory index keeps the newest position per driver.
From the estimate, how many location updates arrive for each ride request?
- About 900. The stream is far larger than the request load, so they need different components.
Part 2 · API and data model
The calls
The rider app and the driver app use different calls, so the API splits into two small groups. The rider side creates and watches a trip. The driver side sends positions, sets availability and answers offers. The sketch is a design sketch and it is not run.
POST /v1/trips (rider)
Idempotency-Key: 6f1c-example
{ "pickup": {"lat": 12.9716, "lon": 77.5946},
"dropoff": {"lat": 12.9352, "lon": 77.6245} }
201 Created { "trip_id": 5521, "status": "requested",
"fare_estimate_paise": 24500 }
GET /v1/trips/5521 status, driver, ETA
DELETE /v1/trips/5521 cancel
PUT /v1/drivers/me/location (driver) batched points
PUT /v1/drivers/me/status available | offline
POST /v1/offers/{id}/accept (driver)
POST /v1/offers/{id}/declineAPI sketch, not run.
Two details matter. Creating a trip carries an idempotency key, as in the core concepts chapter: if the rider's phone retries after a timeout, the service returns the trip it already created and does not request a second ride. And the fare is a whole number of paise, never a floating-point number of rupees, because money must add up exactly.
The location call carries a batch. The driver app collects a few positions and sends them together, so a phone with a weak signal makes fewer requests, and the service keeps only the newest point of each batch for the index. Each point has its own timestamp, so a batch that arrives late, after a newer one, is recognised as old and ignored. Without that check, a delayed message could move a driver backwards on the map.
Offers are a separate resource with their own id. A driver answers an offer and not a trip, because the same trip may be offered to several drivers in turn, and an answer to an old offer must not change the trip's present state.
The offers table in the next section has the pair of trip and driver as its primary key, so a driver can be offered a given trip only once. If the first offer to a driver expires, that driver is not asked again for the same trip. Positions and statuses also live in two places on purpose. The index holds where a driver is and answers 'who is near'. The database holds whether a driver may be given a trip, and only a database row can be changed conditionally in one atomic step, which the fifth lesson relies on.
The tables
The relational tables hold what must be correct: drivers with their status, trips with their status, and offers. Statuses are limited by CHECK constraints, so the database refuses a value the code never meant to write. The trip has a version column for the optimistic updates described later, and a driver's cell is the grid cell of its last known position.
import sqlite3 import textwrap db = sqlite3.connect(":memory:") db.executescript(""" CREATE TABLE drivers ( id TEXT PRIMARY KEY, status TEXT NOT NULL CHECK (status IN ('offline','available','busy')), lat REAL, lon REAL, cell TEXT, seen_at REAL ); CREATE TABLE trips ( id INTEGER PRIMARY KEY, rider_id TEXT NOT NULL, driver_id TEXT REFERENCES drivers(id), status TEXT NOT NULL CHECK (status IN ('requested','matched', 'arriving','on_trip','completed','cancelled')), pickup_lat REAL, pickup_lon REAL, fare_paise INTEGER, version INTEGER NOT NULL DEFAULT 0 ); CREATE TABLE offers ( trip_id INTEGER REFERENCES trips(id), driver_id TEXT REFERENCES drivers(id), state TEXT NOT NULL, -- sent, accepted, declined, expired expires_at REAL, PRIMARY KEY (trip_id, driver_id) ); """)
Python 3.12.10. Save this block and the next as schema.py.
tables = db.execute("SELECT name FROM sqlite_master WHERE type='table'") for (t,) in tables.fetchall(): cols = [c[1] for c in db.execute(f"PRAGMA table_info({t})")] print(textwrap.fill(t + ": " + ", ".join(cols), 68, subsequent_indent=" ")) try: db.execute("INSERT INTO drivers (id, status) " "VALUES ('d1', 'flying')") except sqlite3.IntegrityError as e: print("rejected:") print(" " + str(e))
Continues schema.py: list the columns, then try a bad status.
drivers: id, status, lat, lon, cell, seen_at
trips: id, rider_id, driver_id, status, pickup_lat, pickup_lon,
fare_paise, version
offers: trip_id, driver_id, state, expires_at
rejected:
CHECK constraint failed: status IN ('offline','available','busy')Output of the script.
The last lines show the constraint at work: a driver status of flying is rejected by the database itself. A constraint like this is cheap insurance. The state machine in the sixth lesson is the main guard, but a bug elsewhere cannot write a value outside the list.
Where each piece of data lives
Not everything belongs in the same store. The latest position of every driver is hot, small and disposable, and the trip record is cold, small and precious. Putting both in one database would force the slowest requirement on the fastest data.
| Data | Where | Why |
|---|---|---|
| Latest driver position | In-memory index, sharded by area | 50,000 writes a second; only the newest matters |
| Driver status and offers | Relational database | Must change atomically; read by the matcher |
| Trips and their state | Relational database | A record of money and promises |
| Position trail of a trip | Log or object storage | Append-only; used for fare and disputes |
| Surge multipliers | Cache with a short TTL | Recomputed every minute |
A snapshot of positions may be written to the driver table at a low rate, say once a minute, so that a restarted index can warm up. The matcher always reads positions from the index and statuses from the database, and it treats the status as the authority: a driver the index shows nearby but the database shows busy is skipped.
Why does creating a trip carry an idempotency key?
- If the rider's phone retries after a timeout, the service returns the trip it already created instead of requesting a second ride.
Why is the fare stored as paise in an integer?
- Money must add up exactly, and floating-point rupees can round differently. An integer count of paise does not.
Part 3 · High-level design
The parts and what each owns
Ride-hailing divides into a few services, split along the lines of the estimate. The location service takes the firehose of driver positions and answers 'who is near this point'. The trip service owns the trip record and its state, and it is the only writer of trip status. The matcher, also called the dispatcher, chooses which drivers to offer a trip, in what order, and reserves each driver it offers to. A pricing service computes the fare estimate and the surge multiplier. A notification path delivers offers and status changes to phones.
The gateway authenticates every call and routes it. Driver apps keep a long-lived connection or poll, so an offer can reach a driver within a second or two. Push notifications wake a phone whose app is in the background. How long-lived connections to very many phones are managed is covered in a later chapter. This chapter assumes only that an offer reaches a driver within a second or two.
Each service scales on its own measure. The location service grows with the number of online drivers, the matcher with ride requests, and the trip service with active trips. Splitting them also isolates failure: if pricing is slow, matching can fall back to the last multiplier, and if the location service loses a shard, only the drivers in that area vanish from search until it recovers.
One request through the system
Watch for driver positions flowing in beside the ride request
Read it as steps
The trip service asks the matcher, the matcher asks the location index, and the offer goes to a driver.
The scene follows a request while the location stream runs beside it. The two never share a path until the matcher asks the location service for nearby drivers. The trip service records the request first, so a crash after that point cannot lose it, and the matcher works from the stored trip.
The matcher claims a driver in the database before it sends the offer. That order is deliberate: a claim made after the offer would let the driver accept two offers sent close together. The claim is a single conditional update, described in the fifth lesson, and the offer goes out only after it succeeds.
What the design leaves open
Three decisions are left to the deep dives. How the location index is built so a nearest-driver search is quick and an update is cheap is the subject of the fourth lesson. How the matcher claims a driver safely when several matchers run at once is the fifth lesson. And how a trip moves through its stages, and what happens when a driver goes offline in the middle, is the sixth lesson.
It is also worth naming what is deliberately simple. The matcher offers a trip to one driver at a time, nearest first, and waits for an answer or a timeout before trying the next. Offering to many drivers at once finds a match sooner, but it wastes the time of the drivers who lose the race. We start with one at a time and measure.
The matcher itself is stateless, because everything it needs is in the trip database and the location index. Any matcher instance can handle any trip, and if one crashes, a trip stuck in the requested state is picked up again by another instance after a short delay. This is the same idea as the leases in the task scheduler chapter, applied to one narrow job.
The in-memory location index can be lost, and the design lets it recover without a special procedure. A restarted shard starts empty and fills as drivers report. With updates every 4 seconds, every driver that is still online has reported within a few seconds, so the shard is close to complete almost at once. For that short time the matcher sees fewer drivers than exist and widens its search, and the snapshot written once a minute can seed the index sooner if the gap matters. This is the reason the index holds only the latest position and nothing else.
Why does the trip service alone write trip status?
- One writer keeps the rules of the state machine in one place, so no other service can move a trip to a state the rules forbid.
Why does the matcher claim a driver before sending the offer?
- Claiming after the offer would let a driver accept two offers sent close together. The claim must succeed first.
What makes the matcher easy to scale and to recover?
Part 4 · Deep dive: the driver location index
A grid of cells
The matcher's question is 'which free drivers are nearest to this pickup point'. The answer comes from a spatial index, as in the previous chapter, with one difference: here every point moves every few seconds, so the index must take cheap updates. A grid index suits this well. It cuts the city into equal squares, keeps a small table of drivers for each square, and finds neighbours by looking in the square and the ones around it.
The code uses squares measured in metres. put records a driver's position and reports whether the driver changed cell, so the grid moves the driver between two small tables only when it has to.
import math from collections import defaultdict class Grid: def __init__(self, size_m): self.size = size_m self.cells = defaultdict(dict) # (cx, cy) -> {driver: (x, y)} self.where = {} # driver -> (cx, cy) def key(self, x, y): return (int(x // self.size), int(y // self.size)) def put(self, d, x, y): k = self.key(x, y) old = self.where.get(d) if old is not None and old != k: del self.cells[old][d] # the driver changed cell self.cells[k][d] = (x, y) self.where[d] = k return old is not None and old != k
Python 3.12.10. Save this block and the next together as grid.py.
To find the nearest drivers, nearest reads the cell of the pickup point, then the ring of cells around it, then the next ring, and stops when it holds enough drivers and the k-th closest is nearer than anything an unread ring could contain. A point in a ring further out is at least r cell widths away, which gives the stopping rule.
Searching and updating
import math def nearest(grid, x, y, k): """k nearest drivers by ring search: (hits, cells, examined).""" cx, cy = grid.key(x, y) found, cells, r = [], 0, 0 while True: ring = [(cx + dx, cy + dy) for dx in range(-r, r + 1) for dy in range(-r, r + 1) if max(abs(dx), abs(dy)) == r] for c in ring: cells += 1 for d, (px, py) in grid.cells.get(c, {}).items(): found.append((math.hypot(px - x, py - y), d)) found.sort() # anything in a ring beyond r is at least r * size away if len(found) >= k and found[k - 1][0] <= r * grid.size: return found[:k], cells, len(found) r += 1 if r > 200: return found[:k], cells, len(found)
Continues grid.py: a ring search for the k nearest drivers.
The next script places 20,000 invented drivers in a 20 km square, uses 500 metre cells, and checks 200 random pickups against a brute-force sort of all drivers. It then moves every driver by 32 metres in a random direction, the distance of a 4-second step at about 8 metres a second, and counts how many moves change cell for three cell sizes.
import math, random from grid import Grid, nearest rnd = random.Random(3) W = 20_000 # a 20 km x 20 km city pos = {f"d{i}": (rnd.uniform(0, W), rnd.uniform(0, W)) for i in range(20_000)} g = Grid(500) for d, (x, y) in pos.items(): g.put(d, x, y) ok, cells_seen, checked = 0, 0, 0 for _ in range(200): x, y = rnd.uniform(2000, 18000), rnd.uniform(2000, 18000) got, cells, n = nearest(g, x, y, 5) want = sorted((math.hypot(px - x, py - y), d) for d, (px, py) in pos.items())[:5] ok += got == want cells_seen += cells checked += n print(f"same as brute force: {ok} of 200 searches") print(f"cells read per search: {cells_seen / 200:.1f}") print(f"drivers examined per search: {checked / 200:.1f} of {len(pos)}")
Save this block and the next together as grid_run.py.
# How often does a 4-second move cross a cell border? for size in (100, 500, 2000): h = Grid(size) for d, (x, y) in pos.items(): h.put(d, x, y) moved = 0 for d, (x, y) in pos.items(): a = rnd.uniform(0, 2 * math.pi) moved += h.put(d, x + 32 * math.cos(a), y + 32 * math.sin(a)) share = moved / len(pos) print(f"cell {size:>4} m: {share:.1%} of updates change cell")
Continues grid_run.py: count how often a move changes cell.
same as brute force: 200 of 200 searches cells read per search: 9.0 drivers examined per search: 111.3 of 20000 cell 100 m: 37.8% of updates change cell cell 500 m: 7.8% of updates change cell cell 2000 m: 2.0% of updates change cell
Output. Seeded, so the numbers repeat.
Cell size, hexagons and freshness
The last three lines show the trade in choosing a cell size. With 100 metre cells, 37.8 percent of 4-second moves cross a border, so the index does more moves between tables. With 2,000 metre cells only 2.0 percent do, but each cell holds many more drivers, so every search examines more. The 500 metre cells at 7.8 percent are a middle choice. A real service would tune the size against its driver density.
Square cells have a flaw: a diagonal neighbour is further from the centre than a side neighbour. Hexagonal grids such as H3, described in the proximity search chapter, remove this flaw, and the ring search works the same on hexagons with six neighbours in each step. The code here uses squares because they are easy to read, and the ring search works the same on hexagons with six neighbours in each step.
A moving index also needs a rule for stale positions. A driver whose last update is older than three intervals, here 12 seconds, is treated as offline and removed, since a car in a tunnel is not a good offer. And the index is sharded by area, with cells assigned to shards in blocks, so that one shard handles a few thousand updates a second. A search near a shard border reads the neighbouring shard too, the same border rule as in the previous chapter.
Why does the ring search stop when the k-th best distance is at most r times the cell width?
- A driver in any ring beyond r is at least r cell widths away, so nobody unread can beat the drivers already found.
From the run, what fraction of 4-second moves cross a border with 500 metre cells?
- 7.8 percent. With 100 metre cells it is 37.8 percent, so smaller cells mean more updates that move a driver between cells.
Why remove a driver whose position is older than 12 seconds?
- Its position may be wrong by hundreds of metres, and the driver may be out of signal. Offering such a driver wastes the rider's time.
Part 5 · Deep dive: matching without double assignment
The race
Suppose two ride requests arrive at the same moment, handled by two matcher instances, and both find the same nearest driver. Each reads the driver's status, sees available, and sets it to busy and assigns the trip. If the read and the write are separate steps, both reads can happen before either write, and the driver ends up promised to two riders. This is a race condition, and it is the main correctness risk in the whole design.
The first script reproduces it. Two threads each use their own database connection. Each reads the driver's status, then waits at a barrier so that both have read before either writes, then updates. The barrier makes the bad interleaving certain, which is how a race is tested without waiting for bad luck.
import os, sqlite3, threading PATH = "race.db" GIVE = "UPDATE trips SET driver_id='d1' WHERE id=?" def setup(): if os.path.exists(PATH): os.remove(PATH) db = sqlite3.connect(PATH) db.executescript(""" CREATE TABLE drivers (id TEXT PRIMARY KEY, status TEXT); CREATE TABLE trips (id TEXT PRIMARY KEY, driver_id TEXT); INSERT INTO drivers VALUES ('d1', 'available'); INSERT INTO trips VALUES ('t1', NULL), ('t2', NULL); """) db.commit() db.close() def naive(trip, gate, log): db = sqlite3.connect(PATH, isolation_level=None, timeout=5) status = db.execute( "SELECT status FROM drivers WHERE id='d1'").fetchone()[0] gate.wait() # both have now read 'available' if status == "available": db.execute("UPDATE drivers SET status='busy' WHERE id='d1'") db.execute(GIVE, (trip,)) log.append(f"{trip}: got d1") db.close()
Python 3.12.10. Save this block and the next two together as race_run.py.
The naive function checks the status and then acts on a value that may already be out of date. Nothing in the database stops the second thread, because its own update is perfectly valid on its own.
One conditional update
The fix is to let the database decide, in one statement. The update sets the driver to busy only where the status is still available, and it reports how many rows it changed. If the count is 1, this matcher won the driver. If it is 0, another matcher got there first, and this one tries the next driver. The check and the write are one atomic step, so nothing can fall between them.
def conditional(trip, gate, log): db = sqlite3.connect(PATH, isolation_level=None, timeout=5) gate.wait() cur = db.execute("UPDATE drivers SET status='busy' " "WHERE id='d1' AND status='available'") if cur.rowcount == 1: # we changed the row: we own d1 db.execute(GIVE, (trip,)) log.append(f"{trip}: got d1") else: log.append(f"{trip}: d1 was taken, try the next driver") db.close()
Continues race_run.py: the same race with one conditional update.
def run(fn): setup() gate, log = threading.Barrier(2), [] ts = [threading.Thread(target=fn, args=(t, gate, log)) for t in ("t1", "t2")] for t in ts: t.start() for t in ts: t.join() db = sqlite3.connect(PATH) print(sorted(log)) rows = db.execute("SELECT id, driver_id FROM trips").fetchall() print("trips:", rows) db.close() print("read, then write:") run(naive) print("conditional update:") run(conditional) os.remove(PATH)
Continues race_run.py: a runner that prints both results.
read, then write: ['t1: got d1', 't2: got d1'] trips: [('t1', 'd1'), ('t2', 'd1')] conditional update: ['t1: d1 was taken, try the next driver', 't2: got d1'] trips: [('t1', None), ('t2', 'd1')]
Output. Which trip wins can differ between runs; exactly one always does.
In the first run both trips got d1. In the second, one trip got the driver and the other was told the driver was taken. The same pattern protects the trip too, with WHERE status = 'requested' on its update, and a version column does the same job for any row read and changed later. The idea is optimistic concurrency: do not lock, state what you expect to find, and let the update fail if it is wrong.
This is stronger than a cache or an in-memory lock held by one instance, because it still works when matchers run on many machines and when one of them crashes after claiming a driver. A claim that is never turned into an accepted offer is released by a timer, as in the next page.
Offers, timeouts and what a model says
Watch for the matcher moving on when driver A stays silent
Read it as steps
The first driver ignores the offer; the matcher moves to the next driver after ten seconds.
The scene shows an offer to the nearest driver that nobody answers. While an offer is open the driver is marked busy, a short reservation, so no second matcher can offer that driver another trip. The offer carries an expiry, and when it passes, the matcher marks the offer expired, releases the claim on driver A, and moves to driver B. A late accept from driver A after the expiry is refused, because the offer's state is no longer sent. The offer row has its own conditional update for exactly this reason.
How long does a rider wait? The script below is a model, not a measurement. Each driver accepts with probability 0.5 after 2 to 6 seconds, declines with probability 0.3 after 1 to 4 seconds, or ignores the offer for the full 10 seconds. The probabilities are invented to show the shape. The matcher gives up after five offers.
import random, statistics TIMEOUT_S = 10 # an offer the driver ignores expires after this MAX_OFFERS = 5 # then the rider is told nobody is free def one_trip(rnd): """Offer to drivers one at a time, nearest first.""" t = 0.0 for n in range(1, MAX_OFFERS + 1): u = rnd.random() if u < 0.50: # accepts after 2-6 s return n, t + rnd.uniform(2, 6) if u < 0.80: # declines after 1-4 s t += rnd.uniform(1, 4) else: # ignores it t += TIMEOUT_S return None, t rnd = random.Random(21) runs = [one_trip(rnd) for _ in range(20_000)] done = [(n, t) for n, t in runs if n] times = sorted(t for _, t in done) share = len(done) / len(runs) print(f"matched within {MAX_OFFERS} offers: {share:.1%}") mean_offers = statistics.mean(n for n, _ in done) print(f"offers per matched trip: {mean_offers:.2f}") print(f"seconds to match, median: {statistics.median(times):.1f}") print(f"seconds to match, 95th percentile: " f"{times[int(len(times) * 0.95)]:.1f}")
Python 3.12.10. A model with invented probabilities, seeded.
Part 6 · Trip lifecycle, pricing and failures
The trip state machine
A trip is always in exactly one state, and an event moves it to another. The rules are a table of allowed pairs of state and event, and anything else is refused. The trip service is the only writer, so this table is the single place where the rules live.
Watch for each event moving the trip along an allowed arrow
Read it as steps
A trip only moves along allowed transitions; a cancel after pickup is refused.
The scene walks a normal trip and then tries to cancel after pickup, which the table does not allow. A real service might allow a cancel with a fee, and that would be one more row in the table, not a change in the code that applies it.
TRANSITIONS = {
("requested", "driver_accepts"): "matched",
("requested", "no_driver"): "cancelled",
("requested", "rider_cancels"): "cancelled",
("matched", "driver_nearby"): "arriving",
("matched", "rider_cancels"): "cancelled",
("matched", "driver_cancels"): "requested", # re-match
("arriving", "pickup"): "on_trip",
("arriving", "rider_cancels"): "cancelled",
("on_trip", "dropoff"): "completed",
}
class BadTransition(Exception):
pass
class Trip:
def __init__(self):
self.state, self.history = "requested", []
def apply(self, event):
nxt = TRANSITIONS.get((self.state, event))
if nxt is None:
raise BadTransition(
f"{event} is not allowed in {self.state}")
self.history.append((self.state, event, nxt))
self.state = nxtPython 3.12.10. Save as trip.py: the transition table and a trip.
Running it
from trip import Trip, BadTransition t = Trip() for ev in ("driver_accepts", "driver_nearby", "pickup", "dropoff"): t.apply(ev) print("path:", " -> ".join(["requested"] + [h[2] for h in t.history])) bad_runs = (["rider_cancels", "dropoff"], ["driver_accepts", "pickup"], ["driver_accepts", "driver_nearby", "pickup", "rider_cancels"]) for steps in bad_runs: t = Trip() try: for ev in steps: t.apply(ev) except BadTransition as e: print(f"state {t.state}: rejected, {e}")
Save as trip_run.py, next to trip.py.
path: requested -> matched -> arriving -> on_trip -> completed state cancelled: rejected, dropoff is not allowed in cancelled state matched: rejected, pickup is not allowed in matched state on_trip: rejected, rider_cancels is not allowed in on_trip
Output of the script.
The normal path ends in completed. The three bad runs are all refused. A cancelled trip cannot be dropped off, a matched trip cannot jump to pickup without the driver arriving first, and a trip that has started cannot be cancelled by the rider. In a database, each transition is a conditional update, UPDATE trips SET status = 'arriving', version = version + 1 WHERE id = ? AND status = 'matched' AND version = ?, so a duplicate or delayed event finds the state has moved on and changes nothing.
One transition runs backwards: a matched driver who cancels sends the trip back to requested, and the matcher picks it up again, with the cancelled driver excluded. Keeping every transition as an appended event row also gives a history for support and disputes, and it makes it possible to rebuild a trip's state from its events.
Pricing and payment, at a high level
The fare estimate comes from the distance and time of the route, a base fare and a per-kilometre rate, computed by the pricing service from the route the maps service returns. The final fare uses the distance and time actually travelled, from the position trail kept during the trip. The fare is stored in paise.
Surge pricing raises the multiplier where requests outnumber free drivers. Uber's H3 blog post says it measures supply and demand in hexagons across each city to calculate surge. The script below is our own rule and not that company's: no surge until requests exceed free drivers, then half a point for each unit by which the ratio exceeds 1, capped at 3. A second part smooths the multiplier over minutes so it does not flicker.
def multiplier(demand, supply): """Our own rule: no surge until requests outnumber free drivers.""" ratio = demand / max(supply, 1) return round(min(3.0, 1 + 0.5 * max(0.0, ratio - 1)), 1) cells = {"station": (120, 40), "tech park": (60, 50), "old town": (30, 45), "airport": (90, 20)} print("cell requests free drivers multiplier") for name, (demand, supply) in cells.items(): print(f"{name:<11} {demand:>8} {supply:>13} " f"{multiplier(demand, supply):>10}x") # Smoothing: the price follows demand, but not every wobble. shown, prev = [], 1.0 for demand in (40, 80, 45, 90, 50, 85): # one cell, each minute raw = multiplier(demand, 40) prev = round(0.6 * prev + 0.4 * raw, 2) # exponential smoothing shown.append((raw, prev)) print("raw :", " ".join(f"{r:.1f}" for r, _ in shown)) print("shown :", " ".join(f"{s:.2f}" for _, s in shown))
Python 3.12.10. An invented rule, with invented demand and supply.
cell requests free drivers multiplier station 120 40 2.0x tech park 60 50 1.1x old town 30 45 1.0x airport 90 20 2.8x raw : 1.0 1.5 1.1 1.6 1.1 1.6 shown : 1.00 1.20 1.16 1.34 1.24 1.38
Output of the script.
The airport has 90 requests and 20 free drivers, a ratio of 4.5, so its multiplier is 2.8. The old town has more drivers than requests and stays at 1.0. The raw multiplier for one cell jumps between 1.0 and 1.6 each minute, while the smoothed value moves between 1.16 and 1.38. Payment is taken when the trip completes. The payment call carries an idempotency key, so a retry cannot charge twice, as the message queue chapter shows for an idempotent consumer.
When a driver goes offline
Drivers lose signal, run out of battery or close the app. The index handles the first case by treating a driver with no update for 12 seconds as gone. For a trip in progress the rule is gentler: the trip stays alive, the rider sees the last known position, and a longer silence raises an alert to support. For a trip in the matched state, a driver who stops answering is treated as cancelling, and the trip returns to requested.
Other failures follow the same pattern. If the matcher crashes after claiming a driver and before the offer, a timer releases claims older than the offer timeout. If the trip database fails over, the conditional updates still protect the rules, because they run against whichever copy is the leader. If the location service loses a shard, riders in that area see fewer drivers, so the matcher widens its search to nearby cells and shards.
The trade-offs here are: one offer at a time against many at once, small cells against large ones, a short offer timeout against a driver's time to read the screen, and smooth surge against a quick response to demand. Natural extensions are shared rides, scheduled rides and batching several requests so the matcher can choose pairs that minimise total wait, which turns the one-at-a-time rule into an assignment problem.
Why is a late accept after an offer expired refused?
- The offer's state is no longer
sent, and the update that accepts it is conditional on that state. It finds nothing to change.
From the surge run, why does the airport get 2.8 and the old town 1.0?
- The airport has 90 requests for 20 drivers, a ratio of 4.5. The old town has fewer requests than drivers, so no surge applies.
What happens to a matched trip when its driver stops answering?
- The driver is treated as cancelling, the trip returns to
requested, and the matcher offers it to other drivers.
All chapters · Previous: Design a Nearby Places Service like Yelp