Course contents

17. Real-World System Design Lesson 13 of 20

Ride-Sharing Platform

Design a ride-sharing backend: location writes at scale, geohash/H3 cells, a sharded geo index, hot cells, matching, trip state machines and surge.

25 minAdvanced11 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Location updates (≈ online drivers ÷ ping interval) outnumber ride requests by hundreds to one: design the write path first.
  • Map positions to geohash or H3 cells; the index is cell → drivers, and nearby search reads a cell and its neighbours.
  • Shard the index by cell. Hashing spreads cells, not load: split hot cells with a finer resolution.
  • Matching ranks nearby available drivers by road ETA and offers the trip with a timeout.
  • Trips are a state machine with compare-and-set transitions in a durable store; positions are soft state rebuilt by the next ping.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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.

The lesson as textEvery step of the simulation, written out.
  1. 1. Requirements and the numbers that matter

    A rider asks for a car; the system finds a nearby available driver within a few seconds, both see each other move, and the trip is tracked until payment. Non-functional: matching in seconds, positions fresh within a few seconds, and no driver ever assigned to two trips.

    The estimate that shapes everything (illustrative numbers): 500,000 drivers online at peak, each phone sending its position every 4 seconds, is about 125,000 writes per second. Ride requests are tiny next to that: 20 million trips a day is roughly 230 per second on average. This is a write-heavy system.

    The first design is simple: driver apps → Location Service → one Geo Index. In the simulation one request stands for about 1,000 real updates. At night (60 batches/s) the index is under half busy.

    Scene: Driver apps send location updates to the Location Service, which writes them to a single Geo Index at 60 batches per second. The index is under half busy and nothing fails. Rider apps are idle.

    Key idea: Start from the dominant load: location writes outnumber ride requests by several hundred to one.

  2. 2. Rush hour: the single index saturates

    Evening rush: 160 batches per second (160k updates/s). One Geo Index finishes about 130 batches per second with its 8 connections, so every connection stays busy and writes queue for the pool.

    A write that waits more than 300 ms gives up with a pool timeout (red packets). Drivers’ positions go stale exactly when demand is highest. Read replicas would not help: this load is writes, and every replica has to apply all of them.

    Scene: At 160 batches per second the Geo Index has all 8 connections busy, writes queue, and some fail with pool timeouts.

    Key idea: A write-heavy workload outgrows one node no matter how many replicas it has: the writes must be split.

  3. 3. Index the map as cells

    Before splitting, decide what the index is keyed by. “Drivers within 2 km” is a two-dimensional range query, and an ordinary B-tree on latitude and longitude only narrows one dimension at a time.

    Instead the map is cut into cells: a geohash string (precision 6 is roughly 1.2 × 0.6 km) or a hexagonal H3 cell (resolution 9 averages about 0.1 km²). The index is simply cell → set of drivers. An update is “remove driver 42 from cell A, add it to cell B”; a nearby search reads the pickup cell and its ring of neighbours.

    This step is a scripted illustration: watch one update travel and the index move the driver between cells. (In the background the single index is still overloaded; we fix that next.)

    Scene: Scripted: driver 42 sends its position. The Location Service converts it to an H3 cell, and the Geo Index removes the driver from its old cell and adds it to the new one, then acknowledges.

    Key idea: Turning positions into cell IDs turns a 2-D range search into a handful of key lookups.

  4. 4. Shard the index by cell

    Now split the index: a shard router hashes each update’s cell ID onto a consistent-hash ring with three geo shards. All drivers of one cell live on one shard, so a nearby search touches only the shards that own the pickup cell and its neighbours.

    The 160 batches per second spread over three shards, about a third each. Every shard is well under half busy and the pool timeouts stop.

    Scene: A shard router sends each update to one of three geo shards by its cell. Each shard receives about a third of the 160 batches per second, is under half busy, and nothing fails.

    Key idea: Shard the location index by cell: writes spread out and a nearby query stays on a few shards.

  5. 5. A stadium empties: one hot cell

    A concert ends. Tens of thousands of phones, and hundreds of drivers waiting for them, crowd into a few cells downtown, and traffic rises to 220 batches per second.

    The ring spreads cells, not load. The hottest cell belongs to one shard, which now gets well over half of all updates: it saturates and times out, while the other two shards have plenty of spare capacity. Adding a fourth shard would not move that cell: it still hashes to one place.

    Scene: Traffic rises to 220 batches per second and most updates come from a few cells. The shard that owns the hottest cell gets most of the updates, is saturated and times out some of them; the other two shards have spare capacity.

    Key idea: Hashing by cell spreads keys, not traffic. A single hot cell is a hot shard.

  6. 6. Finer cells where it is dense

    The fix is in the keys, not the servers: index dense areas at a finer resolution. H3 is hierarchical, so one hot resolution-8 cell becomes seven resolution-9 children (and those can split again). The stadium crowd now spans dozens of cells, and the ring spreads them over all shards.

    In the simulation this is modelled as the same 220 batches per second spread over ten times as many cells with much less skew. No shard gets much more than 40% any more, and the timeouts stop.

    Scene: Dense areas use smaller cells, so the same 220 batches per second are spread over many more cells. All three shards carry a similar share and nothing times out.

    Key idea: Fix a hot key by making it several keys: adaptive cell resolution, not more shards.

  7. 7. Matching a rider to a driver

    A rider requests a car. The Matching Service turns the pickup point into a cell plus its ring of neighbours and asks the shard router; here those cells live on two shards, which are queried in parallel. It filters to available drivers and ranks the candidates by ETA on the road network, not straight-line distance.

    Then it offers the trip to the best driver, who has a few seconds to accept. Only after the accept does the rider hear “driver on the way”. This step is a scripted illustration; location updates keep flowing in the background.

    Scene: Scripted: the rider app asks the Matching Service for a car. Matching queries the shard router, which asks Geo shards 1 and 2 in parallel for drivers in the pickup cells. Matching ranks them by ETA, offers the trip to the best driver, waits for the accept, then confirms to the rider.

    Key idea: Matching = nearby cells → available drivers → rank by ETA → offer with a timeout.

  8. 8. A trip is a state machine

    Every trip moves through explicit states: REQUESTED → MATCHED → ARRIVING → IN_PROGRESS → COMPLETED (or CANCELLED). Each transition is a conditional write in the Trips store: “set MATCHED with driver 42 only if the trip is REQUESTED and driver 42 is available”.

    Watch two matching instances race for the same driver. The first write wins; the second fails the condition (red) and moves on to its next candidate. No locks held across the network, no double assignment. Then the driver’s app drives the trip forward one transition at a time. Scripted illustration.

    Scene: Scripted: two matching instances try to assign the same driver at once. The Trips store accepts the first conditional write and rejects the second, which retries with another driver and succeeds. Then the driver app sends arriving, started and completed transitions.

    Key idea: Model the trip as a state machine with compare-and-set transitions: races resolve in the database, not in the matcher.

  9. 9. A geo shard crashes

    One second in, Geo shard 2 crashes. Until the router’s health checks notice (two failed probes, 500 ms apart), updates for its cells are refused: red packets for about a third of the traffic.

    Then the ring skips shard 2 and its cells move to the next shards. Errors stop and shards 1 and 3 carry the full 220 batches per second. The moved cells start out empty on their new owners, but location data is ephemeral: every driver re-sends its position within 4 seconds, so the index refills itself without any recovery job (that refill is explained here, not simulated).

    Scene: Geo shard 2 crashes. Updates for its cells fail until the router’s health checks eject it, about one second later; then its cells move to shards 1 and 3, which carry all the traffic, and errors stop.

    Key idea: Location state is soft state: losing a shard costs a detection gap and a few seconds of stale cells, not data loss.

  10. 10. Surge regions from supply and demand

    Shard 2 is back. The same cells that index drivers also aggregate the market: a stream carries supply (available drivers per cell, from the geo shards) and demand (ride requests per cell, from matching). A Surge Service computes, per cell group and per short window, the ratio of demand to supply and publishes a price multiplier back to matching and the rider app.

    Regions are smoothed across neighbouring cells and over time, so prices do not flicker between adjacent blocks. Scripted illustration; real surge models are proprietary and more involved than a ratio.

    Scene: Scripted: the geo shards publish available drivers per cell and matching publishes ride requests per cell to a market stream. The Surge Service aggregates them per region and window and sends a price multiplier to matching, which shows it to riders.

    Key idea: Surge is a streaming aggregation over the same cells: demand ÷ supply per region per window.

  11. 11. Trade-offs of this design

    Freshness vs cost: a 4-second ping is 125k writes/s; 8 seconds halves it but matches on staler positions. Many apps adapt the rate (fast while on a trip, slow while idle).

    Cell size: small cells mean more lookups per search, big cells mean hot keys and more filtering; adaptive resolution balances both. Soft vs durable state: positions live in memory and are rebuilt by the next ping; trips and payments go to a durable, strongly consistent store. Matching scope: greedy nearest-ETA is fast; batching requests for a second or two and solving an assignment improves the total but adds delay.

    Scene: The full design: driver apps update sharded geo cells through the Location Service; matching queries nearby cells and records trips in a durable Trips store; a market stream feeds surge pricing.

    Key idea: Keep the hot path (locations) cheap and disposable; keep the money path (trips) small, durable and transactional.