What it is
A ride-sharing platform connects riders who want a trip with drivers who are close by. The backend has to know, at every moment, roughly where every available driver is; answer "who is near this pickup point?" in milliseconds; offer the trip to one driver; and then track the trip from pickup to payment without ever assigning a driver twice.
This case study builds that system step by step: requirements and estimates, the location write path (simulated), geospatial indexing, matching, the trip state machine and surge pricing (scripted), a shard failure, and the trade-offs.
Why it exists
The interesting part of the problem is the shape of the load. With illustrative numbers: 500,000 drivers online at peak, each phone sending its position every 4 seconds, is about 125,000 writes per second. Twenty million trips a day is about 230 ride requests per second on average (peaks a few times higher). Location writes outnumber ride requests by several hundred to one, and each write is only useful for a few seconds.
So the core design question is not "how do we store trips" (that is a modest transactional workload) but "how do we absorb a constant flood of tiny, short-lived position updates and still answer proximity queries fast".
How it works
Requirements. Functional: request a ride, see nearby cars, match to a driver, live tracking for both sides, trip lifecycle, pricing. Non-functional: matching within a few seconds, positions fresh within a few seconds, high availability in each city, and strong correctness on assignment and payment.
Location write path. Driver apps send position updates (often over a persistent connection such as a WebSocket or gRPC stream) to a stateless Location Service. It converts latitude and longitude to a cell ID and updates an in-memory geo index: remove the driver from the old cell, add it to the new one, store the latest position and a timestamp. Entries without a recent ping expire.
Geospatial cells. A proximity query ("drivers within 2 km") is a two-dimensional range query. A composite B-tree on (lat, lng) narrows only the first column well. Space-filling cell systems turn proximity into key lookups:
- Geohash encodes a position as a base-32 string; longer prefixes are smaller boxes (precision 6 is roughly 1.2 × 0.6 km, precision 7 roughly 150 × 150 m). Neighbouring boxes can have very different strings at boundaries, so searches always include the neighbours.
- H3 (open-sourced by Uber) tiles the globe with hexagons at 16 resolutions; resolution 9 averages about 0.1 km². Hexagons have six equidistant neighbours, which makes "ring of cells around the pickup" uniform. Each cell has a parent at the coarser resolution with about seven children.
- S2 (Google) uses quadrilateral cells on a cube projection with a similar hierarchy.
Redis's GEO commands, for example, store geohash-derived scores in a sorted set and search by radius.
Sharding by cell. The cell ID is also the natural shard key. A router hashes cells onto a consistent-hash ring of geo shards (or assigns cell ranges per city). All drivers of a cell are on one shard, so a nearby search touches only the shards owning the pickup cell and its ring, queried in parallel.
Hot cells. Hashing spreads cells, not traffic. A stadium exit or an airport rank puts a large share of updates into a few cells, and those cells live on one shard. More shards do not help because the hot cell still hashes to one place. The fix is to split the key: index dense areas at a finer resolution (one resolution-8 cell becomes seven resolution-9 cells, and so on), or split a hot cell's driver set across sub-keys.
Matching. The Matching Service takes the pickup point, computes the pickup cell plus a ring of neighbours (widening if too few drivers), fetches candidates, filters to available drivers with the right vehicle type, and ranks them by ETA on the road network (a routing service), not straight-line distance. It offers the trip to the best candidate with a short acceptance timeout and moves to the next on decline or timeout. Some platforms batch requests for a second or two and solve an assignment problem over all of them, trading a little latency for a better overall match.
Trip state machine. A trip moves through explicit states, for example REQUESTED → MATCHED → ARRIVING → IN_PROGRESS → COMPLETED, with CANCELLED reachable from the early states. Every transition is a conditional write in a durable store: "set MATCHED with driver 42 if the trip is REQUESTED and driver 42 is available". When two matchers race for the same driver, exactly one conditional write succeeds; the other sees the conflict and tries its next candidate. Transitions are idempotent (retrying "start trip" on an already started trip is a no-op), and each one emits an event for billing, notifications and analytics.
Surge pricing. The same cells aggregate the market. A stream carries supply (available drivers per cell) and demand (requests and app opens per cell); a streaming job computes demand versus supply per region and short window, smooths it across neighbouring cells and over time, and publishes a multiplier that matching and the rider app use. Real pricing models are proprietary and include more signals than a ratio.
When to use it
This architecture fits any system that matches mobile supply to mobile demand by proximity: ride hailing, food and grocery delivery, couriers, field-service dispatch, scooter and bike sharing. The pieces are reusable on their own: cell-keyed geo indexes for "near me" queries, soft-state location tracking, and state machines with conditional transitions for any workflow where two actors can race for one resource.
When not to
- Static or slowly changing locations (shops, restaurants, real estate): a spatial index in the database (PostGIS, a search engine's geo queries) is simpler than a streaming, in-memory geo tier.
- Small scale: a few thousand drivers and pings fit comfortably in one Redis instance or one database with a spatial index; sharding is premature.
- Matching that is not about proximity (marketplaces matched by skills or price) needs a different index entirely.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Shorter ping interval | Fresher positions, better ETAs and matches | Proportionally more writes, battery and mobile data |
| Smaller cells | Less filtering per cell, fewer hot keys | More cells per search, more cell changes per driver |
| In-memory soft state for positions | Cheap writes, fast reads, trivial recovery by re-ping | Positions can be seconds stale or briefly missing after failures |
| Greedy nearest-ETA matching | Lowest latency per request | Worse global outcome than batched assignment at peak |
| Conditional writes for assignment | No double booking, no distributed locks held across calls | Retries and conflict handling in the matcher |
| Per-city (regional) deployment | Locality, blast radius limited to a city | Cross-region trips and global features need care |
Alternatives
- Database spatial index (PostGIS GiST, a search engine's geo-point fields): good for moderate write rates and complex spatial queries; not built for six-figure updates per second of throwaway data.
- Quadtree in memory: adapts cell size to density automatically; harder to shard and rebalance than fixed cell IDs.
- City-based partitioning instead of hashing cells: each city's index on its own nodes. Simple and local, but a big city can itself be a hot partition and needs a second level of splitting.
Failure modes
- Hot shard: a dense event concentrates updates in a few cells; one shard saturates while the rest idle. Split cells adaptively; watch per-shard load, not averages.
- Shard loss: until health checks eject a failed shard, its updates and queries fail; afterwards its cells move to other shards and refill from the next pings. A short window of missing drivers in those cells, no data loss.
- Double assignment if assignment is decided in memory by several matchers without a single conditional write.
- Stale positions: congested mobile networks delay pings; matching uses a driver who has moved on. Bound staleness (drop entries older than N seconds) and re-check on accept.
- Retry storms: thousands of driver apps reconnecting at once after an outage. Jittered backoff on the client and admission control at the edge.
- Surge flicker: unsmoothed per-cell ratios make prices jump between adjacent blocks.
In production
Deploy per region or city so failures stay local. Keep the location tier stateless in front and memory-resident behind, with TTLs on every entry. Keep trips, payments and ledgers in a replicated, strongly consistent store, separate from the location path. Emit an event for every trip transition (via an outbox) for billing and analytics. Adapt ping frequency to driver state: frequent while on a trip, less often while idle. Monitor per-shard update rate and latency, matching time, offer acceptance rate and the share of stale positions.
Common misconceptions
- "Add shards when one is hot." A hot key stays on one shard. Split the key.
- "Every location update must be durably stored." The current position is soft state; only a sampled trip trace is kept for billing, safety and disputes.
- "Nearest driver means smallest straight-line distance." A driver across a river can be farther in time than one twice as far away on the same road.
- "Two matchers need a distributed lock on the driver." A conditional write on the driver or trip row resolves the race without holding a lock across network calls.
Interview angle
Start with the estimate (online drivers ÷ ping interval) and say out loud that the system is write-heavy. Then: how positions become cells (geohash or H3, neighbours), why the index is in memory and sharded by cell, what happens with a hot cell, how matching ranks by ETA and offers with a timeout, and how a state machine with conditional writes prevents double assignment. Strong answers separate soft state (positions, rebuilt by pings) from durable state (trips, payments), explain what a shard failure costs, and mention adaptive ping rates and surge as a streaming aggregation over the same cells.
Model assumptions
Only the location write path is simulated, and it is a simplified model, not a benchmark. One simulated request stands for a batch of about 1,000 real location updates. The Location Service has 128 workers with a 4 ms mean service time. The single Geo Index and each geo shard have 8 connections, a 60 ms mean write time per batch (lognormal, cv 0.3), so about 130 batches per second each, and fail a write that waits more than 300 ms for a connection. Each update carries its cell as a key drawn from a Zipf distribution: 400 cells with skew 0.6 normally, skew 1.8 for the stadium crowd; finer cells are modelled as 4,000 cells with skew 0.9, a stand-in for adaptive resolution rather than real H3 geometry. The shard router is a consistent-hash ring (64 virtual nodes per shard) with health checks every 500 ms (2 failures eject, 3 successes restore). Arrivals are Poisson; network hops take a fixed 2–40 ms. The refill of moved cells by the next pings is explained, not simulated. Cell lookups, matching, the trip state machine and surge pricing are scripted illustrations of message order: their timings are not simulated and their numbers (cell IDs, multipliers, timeouts) are illustrative.