Design a Ride-Sharing Service (Uber / Lyft)
Millions of moving objects, geospatial matching under a latency budget, and a trip state machine that must survive every kind of failure.
#1. Requirements
Functional
- Drivers broadcast their location continuously.
- A rider requests a ride from A to B; the system matches a nearby driver.
- Both parties see each other's live location during the trip.
- Trip lifecycle: requested → matched → en route → in progress → completed → paid.
- Fare estimation and calculation.
Non-functional
- Matching within a few seconds.
- Location updates at high volume with low latency.
- A trip must never be lost or double-assigned.
- Availability matters — a failure means people stranded.
Cut: pricing/surge algorithms (mention surge exists and is computed per zone), routing/ETA internals (assume a maps service), payments internals, driver onboarding.
Clarifying questions: Scale — how many concurrent drivers? Matching optimization goal: nearest driver, shortest ETA, or global efficiency? Do we support scheduled rides and pooling? (Pooling is a substantially harder matching problem — worth flagging as out of scope.)
#2. Estimation
5M active drivers, 1M concurrent trips, location updates every 4 seconds.
LOCATION WRITES — the defining number
5M drivers / 4 s = 1,250,000 writes/s
→ This CANNOT go to a disk-backed database. It's ephemeral,
high-churn data where a 4-second-old value is already
worthless. In-memory only.
Payload: driver_id 8 + lat/lng 16 + heading/speed 8 + ts 8
≈ 40 B → 50 MB/s of raw location data
Working set: 5M drivers × ~200 B (with index overhead)
= 1 GB ← trivially fits in memory ✓
Matching: ~100,000 ride requests/s at peak
Trip records: 20M trips/day × 1 KB = 20 GB/day (durable, small)What this decided:
- 1.25M writes/s of disposable data → Redis/in-memory geospatial index, never Postgres.
- 1 GB working set → it fits, so the design is about write throughput, not storage.
- Trip records are small and must be durable → a separate transactional store.
The split between ephemeral location and durable trip state is the core architectural insight. State it early.
#3. High-level design
┌─────────┐ location every 4s ┌──────────────────┐
│ driver │────────────────────► │ Location service │
│ app │ │ (WebSocket) │
└─────────┘ └────────┬─────────┘
▼
┌──────────────────┐
│ Redis GEO │ sharded
│ (sharded by │ by city/
│ geo region) │ region
└────────┬─────────┘
│ query
┌─────────┐ request ride ┌──────────▼─────────┐
│ rider │──────────────────►│ Matching service │
│ app │ └──────────┬─────────┘
└─────────┘ ▼
┌────────────────────┐ ┌─────────┐
│ Trip service │──►│Postgres │
│ (state machine) │ │ (trips) │
└─────────┬──────────┘ └─────────┘
▼
┌────────────────────┐
│ Kafka → pricing, │
│ analytics, payments│
└────────────────────┘#4. Deep dive — the location pipeline
Don't persist every update. This is the key optimization, and the one most often implemented incorrectly.
Every 4 s per driver:
1. Update the in-memory geo index ← always
2. Publish to Kafka ← for trip
replay/analytics
3. Write to a durable database ← NO. Never.The current position lives in memory. The history goes to Kafka for asynchronous processing (trip path reconstruction, fare verification, analytics). The durable database only ever sees trip-level records.
Further reductions worth naming:
- Adaptive frequency — a stationary driver doesn't need 4-second updates; a driver on a highway does. This alone can halve the write volume.
- Only update the index on cell change. The map is divided into small cells, and the index answers "who is in this cell". A driver moving a few metres is usually still in the same cell — so record their new coordinates, but skip rewriting the index, because the answer it gives hasn't changed.
- Batch updates from the connection tier rather than one write per driver per tick.
Sharding: by geographic region (city). Locations in Pune never need to be queried alongside locations in Berlin. Geographic sharding gives perfect locality here — the query and the data are both inherently local. Cross-region queries essentially don't exist, which is a rare and pleasant property.
#5. Deep dive — spatial matching
Given a rider at (lat, lng), find nearby available drivers within a latency budget.
Full mechanics in Geospatial Indexing. The practical implementation:
Redis: GEOADD drivers:pune <lng> <lat> <driver_id>
GEOSEARCH drivers:pune FROMLONLAT <lng> <lat>
BYRADIUS 3 km ASC COUNT 20
Redis GEO is geohash over a sorted set — exactly the
right structure, and it handles this workload well.A geohash turns a latitude/longitude into a single number in which nearby places usually get nearby values. Redis stores drivers in a sorted set ordered by that number, so "drivers near this point" becomes a scan of a few small numeric ranges — fast to query and cheap to update.
The matching algorithm is more than "nearest":
1. Query candidates within an expanding radius
(1 km → 3 km → 5 km; stop when enough candidates)
2. Filter: available, correct vehicle class, not already
assigned, acceptable rating, not about to end a shift
3. Rank by ETA (which needs the road network, not straight-line
distance — a driver 500 m away across a river may be
15 minutes out)
4. Offer to the best candidate; on decline or timeout (~15 s),
offer to the nextAvoiding double-assignment. Two riders must not be matched to the same driver.
The clean solution is a conditional update on the driver's state:
UPDATE drivers SET status='ASSIGNED', trip_id=:t
WHERE driver_id=:d AND status='AVAILABLE';
-- 0 rows → already taken, try the next candidateNo distributed lock needed. The update is an atomic compare-and-set ("change it only if it still has the value I expect"), and that is the mutual exclusion. It's also naturally fenced: there's no lock that can expire while a slow server still thinks it holds it — the database checks the driver's status at the very moment of the write. Combined with a short offer TTL (if the driver doesn't accept in 15 s, the assignment expires and the driver returns to available), you get the same reserve-with-TTL pattern as ticket booking.
#6. Deep dive — the trip state machine
Money and physical people are involved, so state transitions must be explicit, durable, and idempotent.
REQUESTED ──► MATCHED ──► DRIVER_ARRIVING ──► IN_PROGRESS
│ │ │
│ │ driver cancels ▼
▼ ▼ → back to REQUESTED COMPLETED
CANCELLED (rematch) │
▼
PAYMENT_PENDING
│
▼
PAIDProperties to design in, and to say out loud:
- Every transition is a conditional update guarded by the current state, so a duplicate request (from a retry or a flaky mobile network) is a no-op rather than a double transition.
- Every transition is durable before it's acknowledged. A trip must never exist only in memory.
- Transitions publish events to Kafka for pricing, notifications, and analytics — asynchronously, so a slow analytics consumer can't delay a ride starting.
- Timeouts on every waiting state. A driver who doesn't arrive, a rider who doesn't show — each needs a defined expiry and resolution.
Shard trips by trip_id (or by city). Trip state is small and transactional; keep it in a relational store where you get real transactions.
#7. Live tracking during the trip
Rider and driver each need the other's live position.
Driver's location update → pub/sub channel trip:{trip_id}
Rider's app subscribes to that channel over WebSocketThis is the real-time delivery problem, scoped narrowly: a channel per active trip, with exactly two subscribers. Simple, and it means location fanout is bounded by trip count rather than driver count.
Client-side smoothing matters: send updates every ~4 s but interpolate the marker's movement on the client, so the map animates smoothly rather than teleporting. A small detail that shows product awareness.
#8. Failure modes & follow-ups
| Failure | Behaviour |
|---|---|
| Driver app loses connectivity | Location goes stale. After ~30 s, mark unavailable and exclude from matching. If mid-trip, the trip continues — buffer locations on device and upload on reconnect. |
| Redis geo shard dies | That city loses matching until failover. Bounded blast radius by design — one city, not the platform. Drivers re-register position on reconnect, so the index rebuilds within seconds. |
| Matching service dies mid-offer | The offer TTL expires; the driver returns to available; the rider's request is retried. No state is lost because the request is durable. |
| Trip DB primary fails | New trips can't start (correct — better than losing trips). Failover with zero RPO; in-progress trips continue on the client and reconcile after. |
| Payment fails after trip | Trip stays in PAYMENT_PENDING; retry asynchronously. The ride already happened and can't be undone, so you keep pushing the trip forward until payment succeeds (forward recovery) rather than undoing earlier steps (compensation). |
Follow-ups:
- "Surge pricing?" — compute demand/supply ratios per geographic cell (H3 hexagons are well suited, since neighbours are equidistant) on a rolling window, published as a multiplier. Eventually consistent by nature and fine.
- "Ride pooling?" — a much harder matching problem: you're now planning routes for cars that keep picking up new riders on the way, while promising each rider their trip won't take too much longer than going alone (the detour constraint). Batch matching beats greedy per-request assignment: collect requests for a few seconds and match them all together, instead of locking in each rider's car the instant they ask — which might take the car a better pairing needed. Flagging the difficulty honestly is better than hand-waving.
- "Why not a database with PostGIS?" — it would handle the queries fine, but not 1.25M writes/s of ephemeral data. The read pattern suits it; the write pattern doesn't. Naming exactly which half fails is the precise answer.
- "How do you prevent a driver gaming location?" — server-side plausibility checks (speed between updates, GPS accuracy metadata), and never trust client-reported distance for fare calculation — recompute from the recorded path.
#Check yourself
What is the defining number in ride-sharing, and what does it force?Show answer
What is the core architectural split?Show answer
How do you cut location write volume?Show answer
Why shard locations by city?Show answer
How does matching work beyond "nearest"?Show answer
How do you prevent double-assigning a driver?Show answer
What properties must trip state transitions have?Show answer
Why not PostGIS for live locations?Show answer
#What to carry forward
- Separate ephemeral, high-churn location from durable trip records.
- Keep live locations in memory, sharded by city; send history to a log.
- Retrieve candidates by straight-line proximity, then rank by real ETA.
- A conditional update plus an offer TTL prevents double assignment without locks.
- Trip transitions are conditional, durable and timed; payment failures recover forwards.