Design a Ride-Sharing App
Understanding the Problem
🚗 What is a ride-sharing app? A ride-sharing app connects people who need a ride with drivers nearby. The rider enters a destination, sees a price, taps "Request," and within seconds a driver is on the way, shown moving on a map. Uber, Lyft, Grab, Ola and Didi all run this loop. Behind it is a real-time matching engine fed by millions of drivers reporting their location every few seconds.
Interviewers often extend the core question with pooled rides (UberX Share, Lyft Shared: several riders going the same way share one car), carpool route matching (BlaBlaCar-style or commuter carpools, where a driver already making a trip offers empty seats to riders along the way), and surge pricing. These are all the same system: pooling and carpooling change how we match, and surge changes how we price. We'll design the core one-rider-one-driver flow first and cover each extension in the deep dives.
Functional Requirements
Core Requirements
- Riders should be able to enter a pickup and destination and get a fare estimate.
- Riders should be able to request a ride and be matched with a nearby available driver.
- Drivers should be able to go online, share their location, and accept or decline ride requests.
- Riders and drivers should be able to see the trip's status and each other's location in real time until drop-off.
Below the line (out of scope)
- Ratings, tipping and receipts.
- Driver onboarding, background checks and payouts.
- Scheduled rides booked days in advance (we'll touch on scheduling for carpools only).
- Payment processing internals; we'll authorize through a payment provider.
Non-Functional Requirements
Ask for scale. We'll assume 100M monthly riders, 20M trips a day, and 5M drivers, of whom up to 1.5M are online at the global peak.
Core Requirements
- Matching should be fast: a rider should be matched to a driver (or told no one is available) within about 10 seconds, and usually much faster.
- Matching must be consistent: a driver gets at most one ride offer at a time, and a ride is never assigned to two drivers.
- Location and trip updates should reach the other party within a couple of seconds.
- The system should be highly available and keep working through demand spikes (concerts letting out, New Year's Eve, rain), with failures in one city isolated from others.
Below the line (out of scope)
- Fraud and safety systems beyond the basics.
- Analytics and ML training pipelines.
The math. 20M trips a day is about 230 per second on average, maybe 1,000 ride requests per second at peak. That's a modest write load for the trip database.
The location stream is the big one. 1.5M online drivers sending a GPS fix every 4 seconds is 375,000 updates per second. Each update is small, maybe 100 bytes with driver ID, coordinates, heading, speed and a timestamp, so about 37MB/s of payload. Bandwidth is fine; the challenge is 375k updates per second to a structure we also need to query by location.
Most of the hard engineering is in two places: absorbing a firehose of location writes while answering "who's nearby" in milliseconds, and making sure that when many riders compete for the same few drivers, each driver is offered exactly one ride at a time. Everything else is a fairly ordinary CRUD service.
The Set Up
Planning the Approach
We'll build the four requirements in order with a simple design, then go deep on location indexing, consistent matching, surge pricing, pooled rides and carpool route matching.
Defining the Core Entities
- Rider: a user requesting rides, with a payment method on file.
- Driver: a user providing rides, with a vehicle, a status (offline, available, offered, on trip) and a current location.
- Fare: a price quote for a pickup and destination at a point in time, including any surge multiplier. It has an expiry, so a rider can't request with an old cheap quote.
- Ride (or Trip): a matched request, linking a rider, a driver and a fare, with a status that moves from requested to completed.
- Location: a driver's latest position and heading. High-volume, short-lived data.
API or System Interface
POST /fares { pickup: {lat, lng}, destination: {lat, lng}, product: "X" | "Share" }
-> { fareId, price, surgeMultiplier, etaToPickup, expiresAt }
POST /rides { fareId, idempotencyKey }
-> 202 { rideId, status: "MATCHING" }
GET /rides/{rideId} -> { status, driver, vehicle, etaToPickup }
WS /rides/{rideId}/live // status changes and the driver's position
// driver app
POST /drivers/me/status { status: "online" | "offline" }
POST /drivers/me/location { lat, lng, heading, speed, ts } // every ~4s
POST /rides/{rideId}/accept | /decline
POST /rides/{rideId}/pickup | /dropoff
The rider and driver IDs come from the auth token, not the body. The fare is referenced by ID, so the server holds the price and the client can't send its own.
High-Level Design
1) Riders should be able to get a fare estimate
A Ride Service handles the quote. It asks a Routing Service for the estimated distance and duration from pickup to destination (built on road-network data, using a routing engine like OSRM or Valhalla, or a mapping provider; see Google Maps for how routing works). It applies the pricing formula for the product:
price = (base + per_km * distance + per_min * duration) * surge_multiplier
price = max(price, minimum_fare)
The fare is saved with an expiry of a few minutes and returned with a fareId. When the rider requests a ride, they send only the fareId, so the price they agreed to is the price they pay (subject to route changes during the trip).
For now the surge multiplier is a constant 1.0. We'll make it real later.
2) Riders should be able to request a ride and be matched
The rider sends POST /rides with the fareId. The Ride Service checks the fare is still valid, writes a ride with status MATCHING, and hands it to a Matching Service. The response is 202 Accepted: matching takes seconds, so the client watches the ride's status instead of waiting on the HTTP request.
To match, the Matching Service needs available drivers near the pickup. For this first version, assume driver locations are in a table, and the matcher queries for available drivers within a few kilometers, ordered by distance. It sends the closest one an offer by push notification. The driver has around 15 seconds to accept. If they decline or time out, the matcher offers it to the next one.
When a driver accepts, the ride is updated to ACCEPTED with the driver's ID, and the rider sees "Your driver is 4 minutes away."
The table query for "drivers near here" is the first thing that will break at our scale, and there's a race: two matchers handling two riders at the same corner can both pick the same closest driver. We'll fix both.
3) Drivers should be able to share their location and accept requests
Driver apps send their location every 4 seconds to a Location Service. Writing these to a relational table with a lat/lng index won't keep up with 375k writes per second, and we don't need to keep every ping in the hot path anyway. What dispatch needs is the latest position of each available driver, queryable by area.
Redis has geospatial commands built on geohash-encoded sorted sets:
GEOADD drivers:available:nyc -73.9857 40.7484 driver:8812
GEOSEARCH drivers:available:nyc FROMLONLAT -73.99 40.75 BYRADIUS 2 km ASC COUNT 10 WITHDIST
The Location Service updates the latest position in Redis, and appends each ping to Kafka for the trip record, ETA models, fraud checks and the driver heatmap. When a driver goes offline or starts a trip, they're removed from the available set. Drivers whose last ping is too old (their phone lost signal) are dropped by a sweeper so we never offer a ride to a ghost.
The Matching Service now runs GEOSEARCH instead of a table query.
4) Riders and drivers should see the trip in real time
Once matched, the rider wants to watch the car approach, and the driver needs the pickup point and later the route to the destination.
Both apps open a WebSocket to a Live Gateway and subscribe to the ride's channel. The Location Service, when it receives a ping from a driver on an active ride, publishes it to that ride's channel (Redis Pub/Sub or a similar pub/sub layer). The Ride Service publishes status changes (ACCEPTED, ARRIVED, IN_PROGRESS, COMPLETED). The gateway forwards everything to the connected clients.
Status transitions are conditional updates on the ride row (WHERE status = 'ACCEPTED' to move to ARRIVED, and so on), so a duplicate tap from a driver on a bad connection does nothing. On reconnect, the client fetches GET /rides/{rideId} to catch up before resubscribing.
At drop-off, the Ride Service computes the final fare from the actual route (if it differs substantially from the quote), and charges the rider's authorized payment.
Potential Deep Dives
1) How do we handle 375k location updates per second and find nearby drivers fast?
The Redis version from the high-level design is a solid start. The question is how to scale it and keep queries fast as density varies wildly between a quiet suburb and Midtown Manhattan at rush hour.
Bad Solution: Lat/Lng Columns in a Relational Database
Approach
Store each driver's latest location in Postgres with a B-tree index on latitude and longitude, and update the row on every ping.
Challenges
A B-tree index on two columns can narrow by latitude, but then scans every driver in that latitude band, across the whole width of the city. 375k row updates per second also means constant index maintenance and write-ahead log volume for data that's obsolete in 4 seconds. PostGIS with a GiST index is much better at the query, but still a poor fit for this update rate.
Good Solution: Redis GEO Sharded by City
Approach
Keep one Redis sorted set of available drivers per city (or per region in a big city), using geohash-based GEOADD and GEOSEARCH. A single Redis node handles on the order of 100k writes per second, so the 375k global writes spread across a few dozen city shards with plenty of headroom. Each city's shard has a replica. The data is soft state: if a shard fails over and loses a few seconds of updates, every driver sends a fresh ping within 4 seconds, and the index rebuilds itself.
Challenges
Geohash cells are rectangles that vary in size with latitude, and a radius search near a cell boundary has to check neighbouring cells, which Redis handles internally. The bigger issue is that a fixed radius is wrong in both directions: 2km finds 300 drivers in Midtown and zero in the suburbs. And straight-line distance isn't drive time.
Great Solution: An In-Memory Index on H3 Cells, Ranked by ETA
Approach
Index drivers by H3 cell: H3 divides the world into hexagons at several resolutions, and every hexagon has neighbours at the same distance, which makes "expand the search ring by one" clean. A Location Service shard owns a set of cells and keeps, in memory, cell -> set of available drivers. Each ping moves a driver between cells if they've crossed a boundary, which is a cheap set operation.
To find candidates, start with the pickup's cell and expand rings until we have enough drivers (say 10-20), which naturally adapts to density. Then rank candidates by ETA, not distance, using the routing service: a driver 800m away across a highway may be 9 minutes out, while one 1.5km away on the same street is 3 minutes.
We also adapt the ping rate. Available drivers need fresh positions for matching, so they ping every 4 seconds. Offline drivers send nothing. Drivers on a trip can ping less often for matching purposes, though the rider watching them still wants smooth updates.
Challenges
We now own a custom in-memory index, sharded by cell, with its own replication and failover. That's real engineering. Uber built its own (and open-sourced H3), but in an interview Redis GEO per city is a perfectly defensible answer; the H3 index is the "how would you go further" version. Shard boundaries also need care: a pickup near the edge of a shard's cells has to query the neighbouring shard too.
Interviewers often ask, "how do you pick the radius?" The strong answer is: don't. Search outward in rings until you have enough candidates, then rank by ETA. That works in Manhattan and in rural Texas without tuning.
2) How do we make sure a driver gets one offer at a time and no ride is lost?
At peak we have about 1,000 requests per second, and in a busy area many of them are competing for the same few drivers. Two matchers working on two riders can both see driver 8812 as the best choice and both send an offer.
Bad Solution: Check Driver Status in the Application
Approach
The matcher reads the driver's status, sees AVAILABLE, then sends the offer and sets the status to OFFERED.
Challenges
Read-then-write is a race. Both matchers read AVAILABLE before either writes OFFERED. The driver gets two pings at once, or accepts one ride while the other rider waits for a driver who will never come.
Good Solution: Atomically Claim the Driver with a TTL
Approach
Before sending an offer, the matcher claims the driver with an atomic set-if-not-exists that expires on its own:
SET driver_lock:8812 ride:551 NX PX 15000
-- OK -> we hold the driver for 15s; send the offer
-- nil -> someone else is offering; try the next candidate
Only one matcher can succeed. If the driver accepts, the Ride Service makes it durable with a conditional update on the ride and driver records, and removes the driver from the available set. If the driver declines, we delete the lock. If they ignore it, the TTL releases them automatically, so a crashed matcher can't leave a driver locked forever.
The acceptance itself is also conditional, so a late tap on an expired offer fails cleanly:
UPDATE rides SET driver_id = :driverId, status = 'ACCEPTED'
WHERE id = :rideId AND status = 'MATCHING' AND offered_driver_id = :driverId;
Challenges
That handles the driver side. But what if the matcher process crashes halfway through a ride's matching loop? The ride sits in MATCHING with nobody working on it, and the rider waits forever.
Great Solution: Durable Matching Jobs on Top of the Lock
Approach
Treat each ride request as a durable job. When the Ride Service creates the ride, it writes a MatchRequested event through a transactional outbox to Kafka, partitioned by city. Matchers consume from the partitions they own. A matcher only commits the offset (or marks the job done) after the ride is matched or definitively fails. If a matcher dies, another takes over its partition and resumes from the uncommitted jobs. Ride state in the database tells the new matcher where things stand, and the driver locks expire on their own.
A workflow engine like Temporal fits this well too: each ride's matching is a workflow with steps "find candidates, offer to driver 1, wait 15s, offer to driver 2...", and the engine persists progress and retries after crashes. Either way, the rule is the same: matching progress lives somewhere durable, not just in a process's memory.
Partitioning by city also means one matcher sees all requests in its area, so it can make better decisions than "first come, first served," for example matching a batch of requests and drivers every second or two to minimize total pickup time.
Challenges
Duplicate processing is possible on failover (the new matcher may resend an offer the old one already sent), so offers and accepts must be idempotent, which the conditional updates give us. Hot cities need more than one partition; split by area inside the city, with the boundary caveats from the previous deep dive.
3) How do we implement surge pricing?
When demand outruns supply in an area, prices go up to bring more drivers in and to ration the available ones. We need a multiplier per area that updates every minute or so.
Measure supply and demand per cell. Divide each city into H3 cells (resolution 7 or 8 is a few square kilometers to under a square kilometer). Every minute, count:
- Demand: fare requests and ride requests whose pickup is in the cell (fare requests count even if the rider doesn't book; they show intent).
- Supply: available drivers whose latest location is in the cell, plus drivers about to finish a trip there.
The location and request streams are already in Kafka, so a Flink job computes these counts in one-minute tumbling windows per cell, the same pipeline the driver heatmap uses.
Turn the ratio into a multiplier. A simple model maps the demand/supply ratio to a multiplier with a floor of 1.0 and a cap. Smooth it over neighbouring cells and over time, so prices don't flicker every minute or jump at a street corner. In practice this is an ML model that also predicts near-term demand (a concert ending in 10 minutes), but the interview answer is the pipeline, not the model.
ratio = demand_1min / max(supply_now, 1)
raw = clamp(1 + k * (ratio - threshold), 1.0, cap)
multiplier = 0.7 * previous + 0.3 * avg(raw over cell + ring-1 neighbours)
Serve it from a cache. The job writes surge:{cellId} -> multiplier to Redis, with a short TTL. The fare quote looks up the pickup cell's multiplier and stores it in the Fare, so the rider's price is locked once quoted. Drivers see the surge in their app as a heatmap, which is what pulls them toward busy areas.
Fail safe. If the surge pipeline stalls, the TTL expires and the fare service falls back to 1.0 (or the last known value, capped). A broken pipeline should make rides cheaper, not charge 5x.
A common follow-up: "Isn't surge just supply/demand?" Mention the side effects: surge moves drivers, which changes supply in the neighbouring cells, so you need smoothing to avoid oscillation. And most regions require caps on surge during emergencies, so the cap needs to be configurable per city.
4) How do we match pooled rides?
In a pooled ride, a car follows a route with several stops: pick up A, pick up B, drop off A, drop off B. A new request should be added to a car whose route it fits with little detour, without breaking promises to riders already on board.
Bad Solution: Group Riders with Nearby Pickups and Destinations
Approach
Group requests whose pickups are within a few hundred meters and whose destinations are within a few hundred meters.
Challenges
Too strict to find matches in practice: two people rarely start and end at the same corners. It also ignores direction. Two riders with close pickups going opposite ways would be fine to reject, but two riders with pickups 1km apart along the same avenue, going the same way, are a great match and this misses them.
Great Solution: Insertion into Existing Routes, with Detour Constraints
Approach
Each pooled vehicle has an ordered list of upcoming stops. For a new request with pickup P and drop-off D:
- Find candidate vehicles: pooled vehicles near P (from the location index) with an empty seat, plus empty available drivers.
- For each candidate, try every valid insertion of P and D into its stop list (P before D, both after the car's current position). For a car with k stops, that's O(k²) insertions, and k is small (a car holds at most 3-4 parties).
- For each insertion, compute the new route's timings with the routing service and check constraints: every rider's added detour stays under a limit (say, no more than 8-10 minutes or 40% longer than a direct ride), and the new rider's pickup ETA is acceptable.
- Pick the insertion with the lowest added cost (extra driving time, plus a penalty for detours to existing riders).
Run this in short batches (a few seconds) so several new requests can be considered together, which finds better combinations than handling each alone. Pooled requests get a slightly longer matching window in exchange for the lower price.
Challenges
Every insertion needs travel times, so the routing service is called a lot. Cache travel times between H3 cells at a coarse level for candidate filtering, then compute exact times only for the top few. A vehicle's route also changes constantly, so the matcher must hold the vehicle lock while inserting, using the same atomic claim as single rides.
5) How do we match carpools whose routes overlap?
Carpool route matching is different from pooling. The driver isn't a professional waiting for jobs; they're making their own trip (a commute, or a weekend drive between cities) and offering seats along it. The question becomes: which drivers' planned routes pass near the rider's pickup and then, later on the same route, near their drop-off, at a compatible time?
Index routes, not positions. When a driver posts a trip, compute its route with the routing service and turn it into a sequence of coarse H3 cells (resolution 6 or 7, a few kilometers across), each with an estimated time and a position index along the route. Store an inverted index: cell -> [(tripId, positionInRoute, eta)]. A 300km intercity trip becomes a few hundred cells; a 20km commute a few dozen.
Match in two steps. For a rider going from P to D at time T:
- Look up the trips passing through P's cell (and its neighbours) around time T, and the trips passing through D's cell.
- Intersect them, keeping trips where P's position on the route comes before D's, and the time fits the rider's window.
Then rank the survivors by the actual detour each would need, computed with the routing service: how far off the driver's route are the exact pickup and drop-off points?
candidates_P = index[cell(P) + neighbours].filter(eta ≈ T)
candidates_D = index[cell(D) + neighbours]
matches = { t : t in both, pos_P(t) < pos_D(t) }
rank by detour_minutes(t, P, D), then by driver rating, seats left
Booking is a seat inventory problem. A trip has, say, 3 seats. Booking a seat is a conditional decrement on the trip's seat count (and, for segment-based carpools, the seat count on each leg between stops), so two riders can't both take the last seat.
This index is updated only when trips are posted or changed, so it's a read-heavy, slow-changing structure: a good fit for a sharded key-value store or Elasticsearch, not the real-time location index.
Final Design
The full flow:
- The rider asks for a fare. The Ride Service gets distance and duration from the Routing Service and the pickup cell's surge multiplier from Redis, and stores a fare with an expiry.
- The rider requests the ride. The Ride Service writes it and emits a matching job through the outbox to Kafka, partitioned by city.
- Driver apps stream locations to the Location Service, which keeps an in-memory index of available drivers by cell (or Redis GEO per city) and appends every ping to Kafka.
- The Matching Service finds candidates by expanding rings around the pickup, ranks them by ETA, atomically claims the best driver with a TTL lock, and sends the offer. A conditional update records the acceptance. Pooled requests go through route insertion instead.
- The Live Gateway pushes status changes and the driver's position to both apps over WebSockets.
- Flink aggregates requests and driver supply per H3 cell every minute and writes surge multipliers back to Redis.
What is Expected at Each Level?
Mid-level
You should design the core flow: fare estimate, request, matching to a nearby driver and live tracking. You should recognize that driver locations are a high-volume write stream that doesn't belong in the main database and propose a geospatial index like Redis GEO. With prompting, you should spot that two riders can be matched to the same driver and fix it with an atomic claim.
Senior
You should go into the location index (why B-trees don't work, geohash vs H3, sharding by city, soft state that rebuilds itself) and make matching consistent with locks that expire and conditional updates. Expect to discuss what happens when a matcher crashes and how matching progress stays durable. You should be able to sketch surge pricing as a streaming aggregation per cell, with a cache and a safe fallback.
Staff+
You should treat matching as an optimization problem: batching requests and drivers, ranking by ETA instead of distance, and searching outward in rings. Expect to design pooled matching with route insertion and detour constraints, and to explain how carpool matching indexes routes instead of positions. You should talk about city-level isolation, the feedback effects of surge on driver supply, regulatory caps, and how the system degrades when routing or surge pipelines fail.