Skip to content
Commitwise
Menu
System Design

Design a ride-sharing app

Design the location and matching core of a ride-sharing app, with requirements and estimates, drivers streaming positions that are kept in memory and indexed with geospatial cells (geohash, S2, H3), finding nearby drivers, ranking by ETA, offering rides with timeouts, assigning each driver atomically, and the trip state machine, with code in Kotlin, Java, Swift and TypeScript.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

A rider opens the app and expects to see cars moving on the map around them, and a driver assigned within seconds of tapping “Request”. Behind that: a million drivers sending their position every few seconds, a search for the closest available ones among them, an offer that the driver can accept or ignore, and a guarantee that two riders are never matched to the same car. The first design wrote every GPS update into a SQL table and searched it with where lat between … and lng between …; it fell over on the first rainy Friday evening.

“Design Uber” is one of the most common senior interview questions. The parts that matter are the write-heavy, short-lived location data, the geospatial index that makes “who’s nearby?” fast, and the matching that must be quick and never double-book a driver.

New to some of these? Open what you need, or skip ahead.

Basics:Latitude and longitude

Every point on Earth has a latitude (north–south, −90° to 90°) and a longitude (east–west, −180° to 180°). Phones get them from GPS, with an accuracy of a few meters to tens of meters, and every update costs battery. Distance on a sphere isn’t simple subtraction: one degree of longitude is about 111 km at the equator and about 78 km in Belgrade.

Basics:What is a WebSocket?

A WebSocket is a connection between an app and a server that stays open, so either side can send messages at any time, without a new HTTP request each time. Apps use it for live updates like chat messages or a car moving on a map. See WebSocketWebSocketA long-lived, two-way connection between an app and a server, so the server can push data the moment it has it.Open in glossary →.

Part Not started

Step 1: Requirements and estimates

Functional requirements:

  • Drivers go online, share their location every few seconds, receive ride offers, accept or decline them.
  • Riders see nearby cars, request a ride, see the assigned driver approaching, and pay at the end.
  • The system matches a request with a good nearby driver.

Non-functional requirements:

  • Fast matching: a few seconds from request to assigned driver.
  • Never double-book a driver.
  • Fresh positions: cars on the map are at most a few seconds old.
  • Battery and data friendly on phones.

An important observation: the system holds two very different kinds of data:

  • Driver locations: enormous numbers of updates, but only the latest one matters. Losing one update is fine; the next arrives in seconds.
  • Trips and payments: far fewer, but each one must be stored safely and never lost.

They need different storage.

Clarify scope: matching and location (the usual focus), versus pricing, surge, routing and payments (mention, don’t design). Key properties: location updates are high-frequency overwrites with short value (seconds), so they belong in memory with replication, not in a transactional database; trips are a durable state machine; matching is latency-sensitive and needs a consistency guarantee on driver assignment, not on positions. Traffic is geographically partitioned: a ride in Belgrade never needs drivers in Lisbon, so shard by city or region (and design for cross-boundary areas near borders). ETA comes from a routing service with live traffic; straight-line distance is only a pre-filter.

Active drivers (peak):       1 million worldwide, update every 4 s
Location writes:             1e6 / 4 s = 250,000 / s   (mostly overwrites of the latest position)
Payload:                     ~100 B (driver id, lat, lng, heading, speed, timestamp) → 25 MB / s inbound

Ride requests:               20 million / day → ~230 / s average, ~2,000 / s peak (rain, events)
Nearby-driver queries:       requests × a few lookups, plus riders' map views (cached, coarse)

Trip storage:                20e6 × ~2 KB ≈ 40 GB / day (durable, kept for years)
Location history for trips:  sampled every few seconds during trips only, batched to cheap storage
  • 250,000 writes per second of positions would overwhelm a normal SQL database, and keeping every point forever is pointless. The latest position per driver is what matching needs.
  • 2,000 ride requests per second at peak is modest; each one must be handled carefully, but the volume is easy.
  • Positions during a trip are kept (for the receipt and disputes), but written in batches to cheap storage.
  • Location: ~250k writes/s of overwrites, value lasts seconds → in-memory, replicated, sharded by region; not a transactional DB.
  • Trips: low volume (~2k/s peak requests), durable state machine; payments handed off.
  • Matching in seconds, ranked by ETA (routing service), with exactly-one assignment per driver.
  • Partition by city/region; handle borders; trip location samples batched to cold storage.

Check this part

  1. Why not write every driver location update to the main SQL database?

  2. Which property needs strong consistency in ride matching?

Riders request rides and see nearby cars; drivers stream positions and accept offers. Location updates are a huge, write-heavy, ephemeral stream (latest position only), while trips and payments are low-volume and durable. Matching must take seconds, rank by ETA, and never assign one driver to two rides. Plan per city: traffic is local.

Part Not started

Step 2: Tracking drivers and finding nearby ones

Location and matching

Driver appConnection gatewaysLocation servicein memory, per regionRider appMatching / dispatchRouting / ETATrip service

Tap a box to see what it does.

Finding “drivers near me” by checking the distance to every driver in the city is far too slow when thousands of drivers move every few seconds. Instead, the map is divided into a grid of cells, and each cell keeps a list of the available drivers inside it.

When a driver sends a new position, the location service updates their latest position, and if they crossed into another cell, moves them from the old cell’s list to the new one.

To find drivers near a rider: look up the rider’s cell and the cells around it, collect the available drivers there, and if there aren’t enough, look one ring further out.

Spatial indexes reduce “nearby” to set lookups. Geohash interleaves latitude and longitude bits into a base-32 string (prefix length sets cell size; neighbors can have different prefixes at cell borders, so always query neighbor cells). S2 maps the sphere onto a cube with a Hilbert curve (cells with good locality and roughly equal area); H3 uses hexagons, whose neighbors are all equidistant, which simplifies ring searches (gridDisk) and aggregations like supply and demand per cell for surge pricing. The location service keeps driverId → (position, cell, status, updatedAt) and cell → set of available drivers in memory per region (or Redis with GEOADD/GEOSEARCH, which uses geohash-ordered sorted sets), drops stale drivers whose last update is older than ~30 s, and replicates state (a lost node is rebuilt from the next updates within seconds). Cell size trades candidate count against ring expansions; choose by density (smaller cells downtown). Rider map views get coarse, throttled positions, often precomputed per cell, rather than per-driver streams to every viewer.

data class DriverPosition(val driverId: String, val lat: Double, val lng: Double, val at: Instant)

class NearbyDrivers(private val grid: GeoGrid) {                 // GeoGrid wraps geohash, S2 or H3
    private val positions = ConcurrentHashMap<String, Pair<DriverPosition, CellId>>()
    private val availableByCell = ConcurrentHashMap<CellId, MutableSet<String>>()

    fun update(p: DriverPosition, available: Boolean) {
        val cell = grid.cellOf(p.lat, p.lng)
        val previous = positions.put(p.driverId, p to cell)?.second
        if (previous != null && previous != cell) availableByCell[previous]?.remove(p.driverId)
        val set = availableByCell.computeIfAbsent(cell) { ConcurrentHashMap.newKeySet() }
        if (available) set.add(p.driverId) else set.remove(p.driverId)
    }

    /** Rings of cells around the rider until enough candidates are found (or the search radius is exhausted). */
    fun candidates(lat: Double, lng: Double, wanted: Int = 20, maxRings: Int = 3): List<DriverPosition> {
        val origin = grid.cellOf(lat, lng)
        val freshAfter = Instant.now().minusSeconds(30)
        val found = mutableListOf<DriverPosition>()
        for (ring in 0..maxRings) {
            for (cell in grid.ring(origin, ring)) {
                availableByCell[cell]?.forEach { id ->
                    positions[id]?.first?.takeIf { it.at.isAfter(freshAfter) }?.let(found::add)
                }
            }
            if (found.size >= wanted) break
        }
        return found.sortedBy { haversineMeters(lat, lng, it.lat, it.lng) }.take(wanted)
    }
}
final class NearbyDrivers {
    record Entry(DriverPosition position, CellId cell) {}

    private final GeoGrid grid;                                 // wraps geohash, S2 or H3
    private final ConcurrentHashMap<String, Entry> positions = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<CellId, Set<String>> availableByCell = new ConcurrentHashMap<>();

    NearbyDrivers(GeoGrid grid) { this.grid = grid; }

    void update(DriverPosition p, boolean available) {
        CellId cell = grid.cellOf(p.lat(), p.lng());
        Entry previous = positions.put(p.driverId(), new Entry(p, cell));
        if (previous != null && !previous.cell().equals(cell)) {
            Set<String> old = availableByCell.get(previous.cell());
            if (old != null) old.remove(p.driverId());
        }
        Set<String> set = availableByCell.computeIfAbsent(cell, c -> ConcurrentHashMap.newKeySet());
        if (available) set.add(p.driverId()); else set.remove(p.driverId());
    }

    List<DriverPosition> candidates(double lat, double lng, int wanted, int maxRings) {
        CellId origin = grid.cellOf(lat, lng);
        Instant freshAfter = Instant.now().minusSeconds(30);
        List<DriverPosition> found = new ArrayList<>();
        for (int ring = 0; ring <= maxRings && found.size() < wanted; ring++) {
            for (CellId cell : grid.ring(origin, ring)) {
                for (String id : availableByCell.getOrDefault(cell, Set.of())) {
                    Entry e = positions.get(id);
                    if (e != null && e.position().at().isAfter(freshAfter)) found.add(e.position());
                }
            }
        }
        found.sort(Comparator.comparingDouble(d -> haversineMeters(lat, lng, d.lat(), d.lng())));
        return found.subList(0, Math.min(wanted, found.size()));
    }
}
  • update keeps the latest position per driver and moves the driver between cell lists when they cross a cell boundary. Drivers on a trip are removed from the “available” lists.
  • candidates looks at the rider’s cell first (ring 0), then the ring of cells around it, and so on, until it has enough drivers.
  • Stale drivers (no update for 30 seconds: app closed, tunnel, dead battery) are skipped, so riders aren’t matched with ghosts.
  • The final sort uses straight-line distance only as a rough order; the next step ranks by real driving time.

Predict the output

A rider stands right at the edge of geohash cell sp3e9q. The closest driver is 80 m away, just across the border, in cell sp3e9w. The code only searches the rider's own cell. What happens?

Spot the bugA driver app that drains the battery

Tap the line with the bug.

final class LocationReporter: NSObject, CLLocationManagerDelegate {
    let manager = CLLocationManager()

    func start() {
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
        manager.distanceFilter = kCLDistanceFilterNone
        manager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        for location in locations { api.sendPosition(location) }    // one HTTP request each
    }
}
class LocationReporter(private val client: FusedLocationProviderClient) {
    fun start() {
        val request = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 0L).build()
        client.requestLocationUpdates(request, { location ->
            api.sendPosition(location)                         // one HTTP request each
        }, Looper.getMainLooper())
    }
}

Choosing the cell system

GeohashS2H3
ShapeRectangles, size varies with latitudeQuadrilaterals on a cube projection, roughly equal areaHexagons (plus 12 pentagons), roughly equal area
NeighborsPrefix breaks at borders; compute with a libraryHilbert-curve locality; cell unions for regionsAll 6 neighbors equidistant; simple rings
Typical useRedis GEO, simple storesGoogle Maps, many databasesUber: dispatch, surge, analytics
  • Persistent streams (WebSocket/gRPC) to gateways; registry driver → gateway for pushing offers.
  • Location service per region: latest position + cell → available drivers in memory (or Redis GEO); stale after ~30 s; replicated, rebuilt from fresh updates.
  • Cells: geohash (simple, border quirks), S2 (Hilbert locality), H3 (hexagons, uniform rings, surge aggregation). Size by density.
  • Nearby: rider cell + neighbor rings until enough candidates; straight-line pre-filter, ETA ranking next.
  • Rider maps: coarse, throttled, smoothed positions; driver apps: adaptive frequency, batching, battery-aware accuracy.

Check this part

  1. How does the system find drivers near a rider quickly?

  2. Why skip drivers whose last update is older than 30 seconds?

  3. Why must nearby searches include neighboring cells?

  4. What makes H3 attractive for dispatch and surge?

Drivers stream positions over a persistent connection to gateway servers. A location service keeps only the latest position per driver in memory, indexed by geospatial cells (geohash prefixes, S2 or H3 cells): each cell holds the available drivers in it. A nearby query looks at the rider's cell and neighboring rings until it has enough candidates. Shard by region; send riders coarse, throttled positions.

Part Not started

Step 3: Matching and trips

When a rider requests a ride:

  1. Find candidates: the nearby available drivers from step 2.
  2. Rank by ETA: ask the routing service how long each driver needs to reach the rider by road. A driver 300 m away on the other side of a river can be 10 minutes away; one 1 km away on the same street, 2 minutes.
  3. Offer the ride to the best driver, with a timeout of about 10–15 seconds.
  4. If they accept, the ride is matched. If they decline or don’t answer, offer it to the next one.

The critical rule: a driver can only have one offer at a time. Two riders requesting at the same moment might both pick the same nearby driver. Reserving the driver must be atomic: “change this driver from available to offered, but only if they’re still available”. If that fails, move on to the next candidate.

The trip itself is a state machine stored durably: requested → matched → driver arriving → in progress → completed (or cancelled at several points). Every change is saved, so the app can always show the right screen, even after a restart.

Dispatch ranks candidates by ETA (batched routing calls), sometimes by a score combining ETA, driver rating, acceptance probability and fairness. Simple systems offer sequentially with short timeouts; large ones run batched matching every second or two per area (solving an assignment problem across all pending requests and available drivers), which improves global ETAs during peaks. Exclusivity is enforced with an atomic conditional update on the driver’s dispatch state (AVAILABLE → OFFERED(rideId, expiresAt)): a compare-and-set in Redis (Lua script or SET … NX on a per-driver lock with TTL) or a conditional UPDATE … WHERE status = 'AVAILABLE' in the dispatch store. Offers expire on their own (TTL), so a crashed dispatcher can’t strand a driver. The trip service owns a durable state machine with idempotent transitions (client retries over flaky networks), timeouts (no driver found within N seconds → notify the rider; driver not arriving → reassign), and events for pricing, payments, notifications and analytics via the outbox. Location samples during trips are batched to storage for fares, receipts and disputes.

// Dispatch state per driver lives in Redis: one key, set only if the driver is still available
class DriverReservations(private val redis: RedisCommands<String, String>) {

    /** Returns true if this ride got the driver; false if someone else reserved them first. */
    fun tryOffer(driverId: String, rideId: String, timeout: Duration): Boolean {
        val result = redis.set(
            "dispatch:$driverId",
            rideId,
            SetArgs().nx().px(timeout.toMillis()),                 // NX: only if not already reserved; PX: expires
        )
        return result == "OK"
    }

    fun accept(driverId: String, rideId: String): Boolean =
        redis.eval<Long>(                                          // only the ride that holds the offer can confirm it
            "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('PERSIST', KEYS[1]) else return 0 end",
            ScriptOutputType.INTEGER,
            arrayOf("dispatch:$driverId"),
            rideId,
        ) == 1L

    fun release(driverId: String, rideId: String) {
        redis.eval<Long>(
            "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end",
            ScriptOutputType.INTEGER,
            arrayOf("dispatch:$driverId"),
            rideId,
        )
    }
}

suspend fun dispatch(ride: RideRequest): MatchResult {
    val ranked = etaService.rank(ride.pickup, nearby.candidates(ride.pickup.lat, ride.pickup.lng))
    for (driver in ranked) {
        if (!reservations.tryOffer(driver.id, ride.id, timeout = 15.seconds.toJavaDuration())) continue   // taken
        when (offers.send(driver.id, ride, timeout = 15.seconds)) {
            OfferAnswer.Accepted -> if (reservations.accept(driver.id, ride.id)) return MatchResult.Matched(driver)
            OfferAnswer.Declined, OfferAnswer.TimedOut -> reservations.release(driver.id, ride.id)
        }
    }
    return MatchResult.NoDriver
}
// The same guarantee with a conditional SQL update in the dispatch store
@Transactional
public boolean tryOffer(String driverId, String rideId, Instant expiresAt) {
    int updated = jdbc.update("""
        update driver_dispatch
           set status = 'OFFERED', ride_id = ?, expires_at = ?
         where driver_id = ?
           and (status = 'AVAILABLE' or (status = 'OFFERED' and expires_at < now()))
        """, rideId, Timestamp.from(expiresAt), driverId);
    return updated == 1;                                       // 0 rows: someone else has this driver
}
  • SET … NX PX writes the reservation only if no reservation exists (NX), and makes it expire on its own (PX). Two dispatchers trying the same driver at the same moment: exactly one gets OK.
  • The expiry matters: if the dispatcher crashes after reserving, the driver becomes available again after 15 seconds instead of being stuck forever.
  • accept only succeeds for the ride that holds the reservation, so a late “accept” for an expired offer can’t steal a driver now offered to someone else.
  • The SQL version does the same with a conditional update: only one transaction can change AVAILABLE to OFFERED, and the row count says who won.
Spot the bugTwo riders, one driver

Tap the line with the bug.

fun offerTo(driverId: String, rideId: String): Boolean {
    val status = redis.get("dispatch:$driverId")
    if (status != null) return false                   // already reserved
    redis.set("dispatch:$driverId", rideId)
    return true
}
boolean offerTo(String driverId, String rideId) {
    String status = redis.get("dispatch:" + driverId);
    if (status != null) return false;                   // already reserved
    redis.set("dispatch:" + driverId, rideId);
    return true;
}

Production puzzles

Predict the output

During a concert ending, 5,000 ride requests arrive within two minutes in one area, with 1,200 available drivers. Dispatch offers each request to its nearest driver, one request at a time in arrival order. What goes wrong?

Exercisehard

Handle the driver's app losing connection

A driver accepted a ride and is on the way to the pickup, when their phone loses connectivity for 90 seconds in a tunnel. What should the rider see, what does the system do, and what happens when the driver reconnects?

›

Separate what is known (the trip state) from what is stale (the position), and decide when a stale position should cause action.

SolutionTry it yourself first
  • Trip state is durable (DRIVER_ARRIVING); it doesn’t change because the connection dropped. The driver isn’t put back in the available pool.
  • Rider view: show the last known position with an estimated position along the route (dead reckoning from speed and heading) and a “updating location” hint after ~20 seconds; don’t jump the car around.
  • Thresholds: after a longer silence (say 3–5 minutes) with no progress, ask the driver (push, SMS) and offer the rider the option to cancel without a fee or to be rematched; automatic reassignment only after a clear timeout.
  • Reconnect: the driver app resumes the stream, sends its buffered positions (batched), and fetches the current trip state; idempotent transition requests make retried “arrived” or “started” taps safe.
  • Server side: gateways detect the dropped connection; the location service marks the driver stale but keeps their trip assignment; alerts if many drivers in an area drop at once (an outage, not a tunnel).

Predict the output

A dispatcher reserves a driver with SET dispatch:d42 ride-7 NX PX 15000, then crashes before sending the offer. What happens to driver d42?

  • Candidates → ETA ranking (batched routing) → offers with short timeouts; batched assignment per area every 1–2 s under load.
  • Exclusivity: atomic CAS on driver dispatch state (Redis SET NX PX + owner-checked Lua for accept/release, or conditional UPDATE); offers expire by themselves.
  • Trip state machine: durable, idempotent transitions, timeouts (no driver, not arriving → rematch), outbox events to pricing, payments, notifications.
  • Disconnections: keep trip state, show estimated positions, escalate after thresholds; buffered positions on reconnect.

Check this part

  1. Why rank candidates by ETA instead of straight-line distance?

  2. What does NX do in SET dispatch:d42 ride-7 NX PX 15000?

  3. Why does every driver reservation need an expiry?

  4. What helps matching quality during demand bursts?

Matching takes nearby candidates, ranks them by ETA from a routing service, and offers the ride to one driver at a time with a short timeout. A driver is reserved atomically with a conditional update (available → offered), so concurrent requests can't take the same driver. The trip is a durable state machine (requested, matched, arriving, in progress, completed, cancelled) with timeouts and idempotent transitions.

Key takeaways

  • Driver positions are many, short-lived writes: keep the latest one in memory, not in a SQL table.
  • A grid of map cells makes “drivers near me” a quick lookup; always check neighboring cells.
  • Rank by driving time, offer to one driver at a time, and reserve drivers atomically with an expiry.
  • Trips are a durable state machine that survives app restarts and lost connections.
  • Separate ephemeral location state from durable trip and payment state; partition by region.
  • Choose a cell system for your density and neighbor needs (geohash, S2, H3).
  • Enforce exclusivity with atomic, expiring reservations; batch matching under bursts.
  • Design for mobile reality: battery, flaky networks, stale positions and idempotent retries.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.