Ride sharing
What we are building
Section titled “What we are building”A ride-sharing service shows a rider the drivers around them and matches the rider with one. Almost nothing in it is hard to describe, and one thing is hard to size: every driver who is online reports a position every few seconds, so the traffic is mostly tiny writes that go stale almost as soon as they arrive.
Functional requirements. A driver reports a position. A rider asks for a ride at a point, and the service finds the drivers near it, offers the ride to one and, if the driver accepts, creates a trip. A rider can see nearby drivers on a map. Pricing, routing, payment, ratings and scheduling ahead are real and are left out, so that the lesson stays on the core.
Non-functional requirements. These are targets we choose, not figures from a real service. A search for nearby drivers answers in under 200 ms at the 99th percentile. A driver’s position on the map is no more than about 5 seconds old. A driver is never offered two rides at once. A trip that was created is never lost.
Scale. 100,000 drivers online at the peak, each reporting every 4 seconds, in one city. About 3 ride requests for every 97 location updates.
Mental model. A ride-sharing service is a map where 100,000 pins are moved every 4 seconds, and where someone occasionally asks “which pins are near this spot?”. The pins are worthless after a few seconds, so what matters is how cheaply they can be moved and how quickly the ones near a spot can be found.
Estimate before you design
Section titled “Estimate before you design”The requests per second lesson gives the method. Here the rate comes from a count of devices and a reporting interval, not from a monthly volume.
| Quantity | Working | Result |
|---|---|---|
| Drivers online at the peak | the assumption | 100,000 |
| Location updates per second | 100,000 ÷ 4 s | 25,000 |
| Ride requests per second, at 3 for every 97 updates | 25,000 × 3 ÷ 97 | about 770 |
| Bytes in the index, at 100 bytes for a driver’s id, position and time | 100,000 × 100 bytes | 10 MB |
| Bandwidth into the service | 25,000 × 100 bytes | 2.5 MB/s, which is 20 Mbit/s |
| Rows per day if every update were stored | 25,000 × 86,400 | about 2.2 billion |
| Storage per day if every update were stored | 2.2 billion × 100 bytes | about 216 GB |
| Cells in a 40 km by 40 km city, cut into squares of 1 km | 40 × 40 | 1,600 |
| Drivers per cell, if they were spread evenly | 100,000 ÷ 1,600 | 62.5 |
| Updates per second per cell, if spread evenly | 25,000 ÷ 1,600 | about 15.6 |
| Updates per second in the busiest area, if it sends 30% of them | 25,000 × 30% | 7,500 |
The byte sizes, the 4 seconds and the 30% are assumptions. The arithmetic gives the shape of the problem whatever the exact values. The data is tiny: 10 MB for every driver’s current position fits in memory of any machine. The rate is the problem: 25,000 writes per second, constantly. Storing the history would be 216 GB a day for rows that are useless seconds after they are written, so the design keeps only the current position, and any history for analysis goes into a log or a stream, not into the serving path. And the load is not even: if one area sends 30% of the updates, it sends about 480 times what an average cell does (7,500 against 15.6), which is why the grid needs more than a fixed cell size.
The API and the data
Section titled “The API and the data”Two calls carry the traffic. Location updates travel over a connection the driver’s app keeps open (see WebSockets and server-sent events), and the request below shows the same thing as an HTTP call.
POST /drivers/d_81/location {"lat": 48.8566, "lon": 2.3522, "heading": 90, "at": "2026-10-11T08:30:04Z"}204 No Content
POST /rides Idempotency-Key: 9c2e1a7b-... {"rider": "r_17", "lat": 48.8530, "lon": 2.3499}202 Accepted {"id": "ride_5Hn", "status": "searching"}Because a rider can send a ride request twice, it carries an idempotency key, as in the payment case study. A location update does not need one: it replaces the previous position, so repeating it does no harm, and a late one is ignored when its timestamp is older than the one stored.
| Data | Where | Why there |
|---|---|---|
| Current position of every driver: id, cell, lat, lon, time, state | In-memory index | Written constantly, wrong after seconds, rebuilt as drivers report in |
| Trips: rider, driver, state, timestamps | The database | Must be durable, and written about 770 times per second |
| Driver state (available, offered, on a trip) | In the index, with the claim done as a conditional write | Matching has to change it atomically |
Five stages, each forced by a number
Section titled “Five stages, each forced by a number”The lab starts with the simplest design that works. Each stage is designed for 3 times the load of the one before it, and the slider raises the load to 3 and 10 times its own design load, which shows where it runs out. The mix in the lab is 97 location updates for every 3 ride requests. Every figure is model output with illustrative inputs, and the model notes under the lab list what it leaves out.
A service that shows riders the drivers around them and matches a rider with one. Every driver online reports a position every few seconds, so location updates are almost all of the traffic and ride requests are a small share. Step through five stages, each adding the one thing the previous stage’s numbers called for, and raise the load to see what breaks.
Start simple: positions are rows in the database
Design load of this stage: 300 req/s
- What we add
- Each driver’s latest position is a row in the database, overwritten by every location update. A rider’s request runs a query on latitude and longitude to find the drivers nearby, and then writes the trip.
- Why: the number that forced it
- At 300 requests per second (291 location updates and 9 ride requests) the database is at 28% of its 2,000 queries per second, with 570 asked. A ride request costs far more than an update: counted as 30 ordinary queries plus 1 to write the trip, the 9 per second take 279 of the 570.
- What it costs
- One system, one query language, and everything is in one place. But every update overwrites a row that will be out of date in 4 seconds, so the database pays for durability that nobody needs for positions. An ordinary index on two columns can use a range on one of them and has to filter the other, so a search reads many rows.
- What breaks next
- At 3 times the load, 900 requests per second, the database is asked for 1,710 queries per second against 2,000: 86%, saturated. At 10 times it is at 285% and 86% of the requests fail.
Each dot stands for many requests. The numbers show the real rate.
No bottleneck: every component has headroom.
Figures at this load
- Busiest component
- DatabaseHealthy29% of its capacity
- p95, whole request
- 27 ms
- p99, whole request
- 36 ms
- Requests served
- 100%300 req/s
- Requests failed
- 0%0 req/s
- Bottleneck
- none
| Component | State | Utilisation | Offered (req/s) | Served (req/s) | Rejected (req/s) | p50 | p95 | p99 |
|---|---|---|---|---|---|---|---|---|
| Riders’ and drivers’ apps | Healthy | <1% | 300 | 300 | 0 | 0 ms | 0 ms | 0 ms |
| Ride API | Healthy | 2% | 300 | 300 | 0 | 1.7 ms | 7.5 ms | 12 ms |
| Database | Healthy | 29% | 570 | 570 | 0 | 3.5 ms | 15 ms | 23 ms |
- Traffic
- 300 req/s
- Successful
- 300 req/s
- Error rate
- 0%
- Mean latency
- 13 ms
All stages at a glance
Each cell is the engine’s steady state for that stage at that load: the busiest component, how much of its capacity it uses, and the share of requests that fail.
| Stage | Design load | Design load | 3× the design load | 10× the design load |
|---|---|---|---|---|
| 1. Start simple: positions are rows in the database | 300 req/s | 300 req/sDatabase: 29%none fail | 900 req/sDatabase: 86%none fail | 3K req/sDatabase: 285%86% fail |
| 2. Keep positions in an in-memory index | 900 req/s | 900 req/sLocation index (in memory): 30%none fail | 2.7K req/sLocation index (in memory): 91%none fail | 9K req/sLocation index (in memory): 302%66% fail |
| 3. Split the index by grid cell | 2.7K req/s | 2.7K req/sBusiest cell (one shard): 27%none fail | 8.1K req/sBusiest cell (one shard): 82%none fail | 27K req/sRide API: 169%48% fail |
| 4. Make the cells smaller where the drivers are | 8.1K req/s | 8.1K req/sRide API: 51%none fail | 24K req/sRide API: 152%34% fail | 81K req/sRide API: 506%80% fail |
| 5. Take location updates through a gateway that batches them | 24K req/s | 24K req/sMatching service: 68%none fail | 73K req/sMatching service: 205%1.5% fail | 243K req/sMatching service: 683%26% fail |
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- Requests arrive at random, as a Poisson process, at a constant average rate.
- Each node is one queue, served first-come first-served by several identical slots (instances × concurrency).
- Service times are random with the stated mean; by default they are exponentially distributed.
- Each node is analysed separately, with the traffic it receives treated as Poisson.
- The mix is 97 location updates for every 3 ride requests: each driver online sends a position every 4 seconds, so a city with about 94,000 drivers online sends about 23,500 updates per second. The ratio is a teaching figure, not a measurement of a real service.
- Every number (service times, capacities, the share of updates from the busiest area, the design loads) is illustrative model output, chosen to make the limit of each stage visible. None of them is a benchmark of a real database, index or server.
Simplifications
- Above capacity there is no steady state. The model switches to a fluid approximation: the node serves at capacity, its queue grows until it reaches its limit, and further requests are rejected.
- Percentiles assume an exponential tail. A service-time variability other than exponential changes the mean wait but not the shape of the tail.
- A node frees its slot as soon as it has done its own work, before waiting on the services it calls. Real thread-per-request servers hold the slot, so a slow dependency exhausts them faster than this model shows.
- A request calls its dependencies one after another. Parallel fan-out is not modelled.
- When a caller times out and gives up, the callee still finishes the work, so abandoned requests keep consuming capacity.
- Retries add load. Their backoff and jitter decide when that load arrives, which only the per-request simulation shows.
- Retry feedback is solved from the healthy starting point, so it finds one stable outcome. Systems that stay stuck in overload after the cause is gone are not shown.
- A throughput limit (for example maximum writes per second) is modelled as slower service, not as a separate rate limiter.
- A caller’s timeout counts the mean time its dependencies take, not their full distribution.
- Latency percentiles for a whole request are estimated, over every request, including those that are rejected and fail quickly. The mean is exact, and the percentiles come from a gamma distribution that has that mean and the variance of the time spent in each component.
- Each stage is shown in a steady state: the load is held and the engine says where queues build. A burst (the end of a concert), a failover and a cold index filling up are not modelled.
- A search for the drivers near a point on a latitude and longitude table is counted as 30 ordinary queries, because it reads many rows to find a few. In the index it is counted as 5 lookups, because a search looks at the rider’s cell and its neighbours. Both are illustrative.
- 30% of the updates come from the busiest area of the city, as a fixed share. Real hot spots move during the day and a driver crossing a cell boundary must be removed from one cell and added to another, which the model does not count.
- A batch of 10 updates is counted as 3 operations on the index, not 1 and not 10. Real batching costs depend on the index and on the size of the batch.
- Matching is counted as one service of about 30 ms per ride request, which stands for ranking the nearby drivers, asking each driver and writing the trip. Routing, arrival-time estimates, pricing and the driver’s answer are not modelled.
Parameter values are illustrative. They are not benchmarks of any real product.
Stage 1, positions in the database. Each position is a row, overwritten by every update, and a search is a query on latitude and longitude. The model counts the search as 30 ordinary queries plus one to write the trip, because a query on two plain columns reads many rows to find a few. At 300 requests per second (291 updates and 9 ride requests) the database is at 28% of its 2,000 queries per second, with 570 asked, and the 9 searches are 279 of them. At 3 times the load it is at 86%, saturated, and at 10 times it is at 285% and 86% of the requests fail. The number that ends this stage is the 2,000 queries per second, against writes that nobody needs to keep.
Stage 2, an in-memory index. Positions move to an index kept in memory, and the database keeps only trips. At 900 requests per second the index takes 873 updates and 135 lookups, 1,008 operations per second, which is 30% of its 3,333 (one thread, 0.3 ms each). The database sees 27 trips per second, 1%. The price is a component that is allowed to be wrong: after a restart it is empty and fills as drivers report in. At 3 times the load it is at 91%, and at 10 times it is at 302% and two thirds of the requests fail.
Stage 3, shards by grid cell. The map is cut into fixed squares and the index into 8 shards, with the busiest area on a shard of its own. At 2,700 requests per second the 8 shards can do 26,667 operations per second and take 2,117, which is 8%. The price is that a search near an edge must ask the neighbouring squares, and a driver who crosses an edge moves shard. The busiest area’s shard takes 30% of the updates: it is at 27% at 2,700 requests per second and at 82% at 8,100, saturated, while the other shards are at 24%.
Stage 4, cells that adapt to density. Where drivers are dense, the cells are smaller and the busiest area spreads over 4 shards. At 8,100 requests per second the same 2,722 operations per second that took 82% of one shard are 20% of the 4 together. The next limit has nothing to do with the index: every update still goes through the API servers. At 3 times the load, 24,300 requests per second, they are asked for 24,300 against 16,000, 152%, and a third of the requests fail, while the index shards are at 47% and 40%.
Stage 5, a gateway that batches updates. Updates take their own door. A gateway keeps the open connections, collects updates for a short time and writes them to the index in batches of 10, and the API servers see only the 729 ride requests per second of the 24,300. The gateway is at 12% of its 200,000 per second and the API servers at 5%. The model counts a batch of 10 as 3 operations on the index, so the grid shards fall to 28% and 24%. The price is a position that waits for its batch, and a gateway that loses what it holds when it crashes. At 3 times the load, 72,900 requests per second, the matching service is the first to run out: 2,187 matches per second against 1,067, or 205%.
Finding the drivers near a point
Section titled “Finding the drivers near a point”A search asks: which available drivers are within a few kilometres of this point? A table of drivers with latitude and longitude columns can answer it, and stage 1 shows what it costs when the table is also being rewritten 25,000 times a second. Spatial indexes for databases exist and are good at the search; the stage 2 move is about the update rate, not about the search alone.
A grid index turns the question into a lookup. The map is cut into cells, each cell has a name, a driver is filed under the cell that holds their position, and a search reads the rider’s cell and the cells around it. There are several ways to cut the map.
| Method | How it works | What you gain | What you pay | When to choose otherwise |
|---|---|---|---|---|
| Geohash | Interleave the bits of latitude and longitude into a string; a longer string is a smaller cell | A cell is a text prefix, so it fits any key-value store or sorted set, and a prefix search finds a cell and everything inside it | Cells at the same length have the same size everywhere, nearby points can have different prefixes across a cell edge, and the cells get distorted near the poles | When density varies a lot (one size does not fit a city centre and its suburbs) |
| Quadtree | Split a square in four when it holds too many drivers, and repeat | Cells are small where drivers are dense and large where they are not | A tree to keep and to rebalance as drivers move; every server must see the same tree | When a flat grid is enough and the density is even |
| S2 | Cut the sphere into a hierarchy of cells, each with an id | Cells at many levels, so one point has an id at every size, and the grid is a real hierarchy | A library to adopt, and cells that are not simple rectangles on the map | When the data is small or the area is a plain rectangle |
| H3 | A hierarchy of hexagonal cells | A hexagon’s neighbours are all at the same distance, which suits “within a radius” | Hexagons do not nest exactly into larger ones, and a library to adopt | When you need exact nesting of squares |
All of them share one rule. The nearest driver can be a few metres away on the other side of a cell edge, so a search reads the rider’s cell and its neighbours, and the model counts it as 5 lookups instead of 1. The cell size is a trade: a cell that is too big holds many drivers to filter through, and one that is too small makes a search read many cells. A search radius of a few kilometres suggests cells of about the same size, so that a search reads the nine cells around the rider and then sorts the drivers it found by true distance.
A fixed grid has a built-in weakness, which stage 3 shows: the load follows people, not the map. A stadium emptying fills one cell with drivers and riders, and the shard that holds it gets a share of the updates out of proportion to its area. Cells that adapt to density (a quadtree, or the finer levels of a hierarchy like S2 or H3) split that area over several shards. An in-memory store that offers radius search over a geohash-ordered set, such as the one in the Redis documentation, is a simple way to get a single index running before sharding it.
High-rate location updates
Section titled “High-rate location updates”25,000 updates per second need three ideas, and none of them needs a stronger database.
Keep only the latest. An update replaces the previous one. A driver that stops reporting expires from the index after a few intervals, for example 12 seconds, so a dead phone does not stay on the map.
Report less when nothing changes. A driver who has not moved, or who is on a trip and not searchable, can report every 15 seconds instead of every 4. That driver sends 1 ÷ 15 = 0.067 updates per second instead of 0.25, a saving of 73%. If a quarter of the 100,000 drivers are in that state, updates fall from 25,000 to about 20,400 per second.
Batch at a gateway. Stage 5 does this. The gateway holds the long-lived connections, so the API servers are not spent on keeping them. It gathers updates for a short window, for example 100 ms, and writes a group at once. The model’s assumption, that 10 updates cost the index as much as 3, is illustrative: real batching depends on the index. The cost is freshness. A position waits for its window, which is small against a position that is already 4 seconds old.
The same idea applies when the load exceeds capacity. A location update is the most expendable request in the system: dropping one costs a driver’s position a few seconds of age, while dropping a ride request loses a rider. Shed updates first (see load shedding).
Matching
Section titled “Matching”Matching takes a ride request and ends with one driver who has said yes. The steps are: find the drivers near the rider; rank them (distance, estimated arrival time, rating); offer the ride to the best one with a time limit; if the driver declines or the time runs out, offer it to the next. The model gives this about 30 ms per ride request, which stands for ranking, asking and writing the trip.
The part that needs care is the claim. Two riders asking at the same moment can both rank the same driver first. If both offers go out, the driver gets two rides at once. The fix is to make the claim atomic: the offer is made by a conditional write that changes the driver’s state from available to offered only if it is still available. One write succeeds, the other sees the new state and moves on to the next driver. The driver’s state goes back to available if the offer expires or is declined, and a timer must guarantee it, or a crashed matcher leaves a driver offered for ever.
Matching also scales differently from the rest. A rider in one city never needs the drivers of another, so the matching service, and with it the index, can be split by region, with no coordination across regions. That is what the “next” of stage 5 points to.
What happens if the index restarts empty
Section titled “What happens if the index restarts empty”The index holds only positions that are a few seconds old, so it has nothing to restore. After a restart it fills as drivers report in: with a 4-second interval every online driver has sent a position within 4 seconds, and in the meantime searches find few or no drivers. Riders see an empty map for about that long. What shortens it: keep a standby that is fed the same updates, so that it is already filled, or have the gateway replay its last batch. What matters is that the trips, which are durable, are in the database and are not lost.
What happens if one area gets most of the updates
Section titled “What happens if one area gets most of the updates”The lab’s stage 3 is this case. The busiest cell’s shard is at 82% at 8,100 requests per second while the others are at 24%, and at 10 times its design load it is at 161%. Adding shards does nothing for it, because the cell is the unit. What helps is a smaller unit: split the busy cell’s area into smaller cells, as stage 4 does, so that its 30% of the updates is spread over 4 shards and is 20% of each. A hot area is also temporary (a stadium empties), so the split should be undone, or the cells should adapt without anyone changing them by hand.
What happens if a driver is offered two rides
Section titled “What happens if a driver is offered two rides”Two matchers rank the same driver first and both send the offer. The driver’s phone shows two rides, accepts one, and the other rider waits for an answer that never comes. The fix is the atomic claim above, and a second guard: when a driver accepts, the trip is created with a conditional write that only succeeds if the driver is still in the offered state for that ride. A rider whose offer lost the race is offered the next driver immediately. A rider’s repeated request with the same idempotency key finds the ride already searching and does not start another search.
Trade-offs
Section titled “Trade-offs”| Decision | What you gain | What you pay | When to choose otherwise |
|---|---|---|---|
| Positions in memory, not in the database | Writes at 25,000 per second without paying for durability, and nothing to back up | Empty after a restart, so searches miss drivers for a few seconds | When the history of positions is needed for products such as trip replay: write it to a log, not to the serving path |
| Fixed grid cells | Simple, and the cell of a point is a calculation | A hot cell where people gather, and cells that are too big or too small somewhere | When density is even, or the city is small |
| Cells that adapt to density | Even load across shards | A tree or table of cells that every server must agree on, and splits to run while updates arrive | When a fixed grid already keeps every shard below about 60% |
| Search the rider’s cell and its neighbours | The nearest driver is not missed at an edge | Several lookups for each search (5 in the model) | A single lookup is enough when cells are large against the search radius |
| Batch updates at a gateway | The index sees a fraction of the operations; the API servers are freed | A position waits for its batch, and a crash loses what the gateway holds | When positions must reach the index within milliseconds |
| Atomic claim of a driver | A driver is never offered two rides | A conditional write on every offer, and a timer to release offers | Never skip it for matching; only the way of doing it varies |
Defend your design
Section titled “Defend your design”An interviewer asks for this system in 45 minutes. A good answer starts with the arithmetic (25,000 writes per second of data nobody needs to keep), puts the positions in memory, builds the grid and finds the hot cell before the interviewer does, and ends with the claim that stops a double offer. Write your answer before you read the strong one.
Interview question
Writing and reviewing an answer needs JavaScript.
The interviewer asks
Design the part of a ride-sharing service that shows a rider the nearby drivers and matches the rider with one. Drivers report their position every few seconds. Where do you keep positions, how do you find the drivers near a point, and what breaks first?
Assume 100,000 drivers online at the peak, each reporting every 4 seconds, and about 3 ride requests for every 97 location updates.
Write your answer first. The strong answer unlocks once you have written a real attempt.
0 of 80 characters written to unlock the strong answer
- 100,000 drivers reporting every 4 seconds make 25,000 location updates per second and about 770 ride requests. The positions are 10 MB: the rate, not the size, is the problem.
- Positions in a database hit 86% of 2,000 queries per second at 900 requests per second. An in-memory index takes the same load at 30% of 3,333 operations per second, and the database is left with 27 trips per second.
- 8 shards by grid cell give 26,667 operations per second, but a search must read the neighbouring cells, and the busiest area, with 30% of the updates, is at 82% of its shard at 8,100 requests per second.
- Cells that adapt to density spread the busiest area over 4 shards, which brings it to 20%. The API servers then run out at 24,300 requests per second (152%), and a gateway that batches updates takes the 23,571 updates away from them.
- Geohash, a quadtree, S2 and H3 are ways to cut the map. Whatever the method, a search reads the neighbours, and the nearest driver is not always in the rider’s own cell.
- Matching claims a driver with a conditional write so that two riders cannot be offered the same one, and the matching service scales by region.
Next: Video platform, which stores and converts uploaded videos and serves them from the edge.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.