SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design Ride Sharing (Uber/Lyft)
  • Design a Payment System
  • Design Ticket / Hotel Booking
  • Design a Search Engine
  • Design Google Maps
  • Design a Collaborative Editor (Google Docs)
  • Design a Metrics and Monitoring System
  • Design a Distributed Message Queue (Kafka-like)
  • Design an E-commerce System (Amazon)
  • Design a Content Recommendation System (YouTube/Netflix)
System Design/Case Studies/Hard
Interview case study

Design Ride Sharing (Uber/Lyft)

Match riders with nearby drivers in real time: location tracking, dispatch, pricing and trip state.

โฑ 38 min readHard case studyAdvanced26 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

โ€œDesign a ride-sharing service like Uber or Lyft.โ€

It is short on purpose. Your first job is to make it specific.

What they checkWhy it matters
Spotting the real loadRide requests are rare. Driver location pings are constant. A strong candidate does the maths and sees that location ingestion, not booking, is the dominant load.
Geospatial thinkingFind nearby drivers fast while thousands of them move. The interviewer wants a cell-based index, the boundary problem, and a reason to keep the hot index in memory.
Correctness under racesOne driver must never be promised to two riders, and one trip must never be created twice. This is the invariant the whole dispatch design protects.
State machines and failureA trip lives for 30 minutes across a phone that drops signal. The answer needs idempotent transitions, crash recovery and no orphaned trips.
Trade-offs in matchingNearest-first is simple. Batch matching is better overall but adds waiting. Naming that cost, with numbers, is the senior signal.

TL;DRThe whole design in 60 seconds

A rider asks for a ride. We find the best nearby available driver, offer them the trip, and if they accept, track the trip through a small state machine until it ends. The hard parts are the firehose of driver locations, matching without double-assigning a driver, and keeping a trip correct across crashes and bad networks.

  • Scale: 3M drivers online at peak, one ping every 4 s, is 750,000 location writes per second. Ride requests are only about 930 per second at peak. Location is roughly 800 times the load.
  • Location: keep only the latest position per driver in memory, in a grid of cells (geohash, S2 or H3), sharded by city. All online drivers fit in about 300 MB. Do not write every ping to a database.
  • Matching: look up the driver's cell and its neighbours, shortlist about 10, rank by road-based ETA, then offer to one driver at a time with a timeout. Reserve the driver atomically so nobody is offered two rides.
  • Trip: a state machine (requested, offered, accepted, arrived, in progress, completed or cancelled). Every transition is idempotent and saved before it is acknowledged.
  • Pricing and ETA: ETA comes from a routing service with live traffic. Surge is a supply-and-demand ratio per cell over a sliding window, smoothed so it does not flap.
  • Live map: WebSocket gateways push the driver's position only to riders with an active trip. Payments are a separate service, reached through a saga.
๐Ÿ’กHow to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
3
5
8
15
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4Rider and driver flows, what is out of scope (pool rides, ratings), scale, one city or global.
2. Estimate3Location writes per second (the dominant load), ride requests, index size, connections.
3. API and data5Location update, request ride, offer and accept, the trip states, what lives in memory.
4. High-level design8Location ingestion, geo index, dispatch, trip service, ETA, pricing, gateways. One request path.
5. Deep dives15Geo index and ingestion, then matching and the double-assignment invariant, then the trip state machine, then surge and the live map.
6. Scale and failures7Region failover, a dispatch crash, a driver offline mid-trip, demand spikes, monitoring.
7. Wrap up3Recap, trade-offs, what is out of scope, the phased plan.

Step 1Clarify requirementsabout 4 min

๐Ÿค”
Pause. Try it yourself first
You have 60 seconds. Write five questions that would change the design. Hint: think about what a driver sends and how often, what happens when two riders want the same driver, and what you are NOT building (pool rides, payments detail).

Questions to ask, and why

AskWhy you ask itTypical answerHow it changes the design
Which flows are in scope: request a ride, match a driver, live tracking, ETA, pricing, payment?Ride sharing is huge. We need a boundary, or we will draw 30 boxes and go deep on none.Request, match, live tracking, ETA and surge pricing. Payment is a stub we call.We design dispatch, location, trip and pricing in detail. Payments is a saga step, linked to a separate design.
Do drivers accept or decline an offer, and how long do they have?A human in the loop makes matching slower and creates a timeout case.Yes. A driver has about 10 seconds to accept.Offers are time-limited and need an expiry. We must handle decline and silence.
Is a rider matched to the nearest driver, or the best match overall?Nearest-first is simple. Looking at all requests together gives a better total but adds waiting.Start simple (nearest by ETA). Mention batching as an improvement.We build per-request matching first, and explain the batch option and its cost.
How fresh must a driver's location be?Freshness sets the update rate, which sets the biggest load in the system.A position every 4 seconds while online. A few seconds of delay is fine.750k writes a second at peak. Latest-only storage, no per-ping database write.
Do we show the driver moving on the rider's map?Live tracking means a second fan-out path and many open connections.Yes, during an active trip.WebSocket gateways, and fan-out only to riders with a live trip.
Is there surge or dynamic pricing?It needs a supply and demand signal per area, in near real time.Yes, a multiplier per area.A pricing service that counts requests and free drivers per cell over a sliding window.
Pool or shared rides, scheduled rides, ratings, support?Each is a project of its own.Out of scope. Mention how pool would change matching.Keep the design to one rider, one driver, one trip.
One city or global? What scale?Geography is the natural way to shard. Scale sets the numbers.Global, many cities. 100M monthly users, 10M rides a day, 3M drivers online at peak.Shard everything by region. Cross-region rides are rare and handled at the border.
What availability do we need, and what may fail?A ride request that fails is lost revenue. A trip in progress that breaks is a safety problem.99.95% for requests. A trip in progress must never be lost.Durable trip store, idempotent transitions, and failover per region.
Can location be approximate, or does privacy matter?Location trails are sensitive personal data.Keep trails short-lived, and only the latest point is used in real time.Sampled trails with a retention limit, and access controls.

Write the scope on the board

Functional (must do)
  • โ€ขA rider requests a ride with a pickup and a drop-off
  • โ€ขFind nearby available drivers and offer the trip to one of them
  • โ€ขDriver accepts or declines within a time limit
  • โ€ขBoth sides see live location and ETA during the trip
  • โ€ขShow a price quote that includes surge, then complete the trip
Non-functional (how well)
  • โ€ขMatch a rider within a few seconds in most cases
  • โ€ขIngest 750k location updates a second at peak
  • โ€ขOne driver is never assigned to two active trips
  • โ€ขA trip in progress survives crashes and weak networks
  • โ€ข99.95% availability for ride requests, per region
Out of scope (say it)
  • โ€ขPool and shared rides (they change matching a lot)
  • โ€ขRatings, support and fraud tooling beyond a mention
  • โ€ขThe map renderer and the road-routing algorithm (see the Google Maps design)
  • โ€ขThe payment internals (see the Payment System design)
๐ŸŽค
Say it out loud
โ€œLet me confirm scope. We build request, match, live tracking, ETA and surge pricing. Drivers accept or decline within about ten seconds. I will treat payments as a service we call, and leave out pool rides, ratings and the map renderer. Scale: 100 million monthly users, 10 million rides a day, 3 million drivers online at peak, each sending a location every 4 seconds. I will shard by region, and I care most about two things: never promising one driver to two riders, and never losing a trip in progress. Does that match?โ€

Step 2Estimate the scaleabout 3 min

๐Ÿค”
Pause. Try it yourself first
On paper: location writes per second, ride requests per second, the size of the in-memory driver index, and the number of live connections. Which one is the biggest load, and what does that tell you about where to spend design effort?

Assumptions (say them first)

AssumptionValue
Drivers online at peak3,000,000
Location update intervalevery 4 seconds
Size of one location updateabout 100 bytes
Rides per day10,000,000
Peak to average ride requests8 times (illustrative)
Candidate drivers per request10
Average trip, including wait20 minutes
Trip row sizeabout 2 KB
Regions (for sharding)10, evenly (illustrative)
One Redis-like node, simple operationsabout 100,000 per second, target 50% load

The arithmetic, line by line

WhatMathsResult
Location writes per second (peak)3,000,000 รท 4 s750,000 per second
Location ingest bandwidth750,000 ร— 100 bytes75 MB/s
Ride requests per second, average10,000,000 รท 86,400about 116 per second
Ride requests per second, peak116 ร— 8about 930 per second
Location load compared with ride requests750,000 รท 930about 800 times more writes than requests
In-memory index of online drivers3,000,000 ร— 100 bytes300 MB (about 30 MB per region)
Writes per second per region750,000 รท 1075,000 per second, one shard handles it
Nodes for location writes at 50% load, if one shared store750,000 รท 100,000 รท 0.515 nodes
Raw pings per day if every one were kept (average online is 25% of peak)3,000,000 ร— 21,600 pings ร— 0.2516.2 billion pings, 1.6 TB a day
Pings kept if we sample one in five (every 20 s)16.2 billion รท 5 = 3.24 billion ร— 100 bytes0.32 TB a day, about 118 TB a year
Trip storage10,000,000 ร— 2 KB20 GB a day, about 7.3 TB a year
Trip state writes116 ร— 6 transitions (peak: ร— 8)about 700 a second average, 5,600 at peak
ETA calls at peak (10 candidates each)930 ร— 10about 9,300 per second
Concurrent trips at peak930 per second ร— 1,200 sabout 1.1 million
Live-map pushes per second at peak1,100,000 trips รท 4 sabout 280,000 messages a second
WebSocket gateways (50,000 connections each)drivers 3,000,000 รท 50,000, riders 1,100,000 รท 50,00060 for drivers, about 22 for riders
What the numbers tell us about the design
  • โ€ขLocation pings are about 800 times the ride requests. The location path is the load; matching and booking are small.
  • โ€ขAll online drivers fit in 300 MB. The hot geo index lives in memory, per region, and does not need a database.
  • โ€ขWriting every ping to a database would be 1.6 TB a day of data nobody reads in real time. Keep the latest point, and sample a trail for analytics.
  • โ€ขMatching needs only about 9,300 ETA calls a second, so a routing service can serve it, but ETA must be fast and cached.
  • โ€ขRider and driver sockets are about 80 gateways in total. Connection count and fan-out, not storage, drive the real-time tier.
๐ŸŽค
Say it out loud
โ€œLet me do the maths. Three million drivers pinging every four seconds is 750 thousand location writes a second, about 75 megabytes a second. Ride requests are only about 930 a second at peak, so location is roughly 800 times the load. The latest position of every online driver is about 300 megabytes, so the whole index fits in memory, and per region it is tiny. That tells me not to write every ping to a database: keep the latest in memory, and sample a trail for analytics. Matching is cheap by comparison, about nine thousand ETA calls a second. All of these numbers are illustrative assumptions.โ€

Step 3Define the API and the data modelabout 5 min

๐Ÿค”
Pause. Try it yourself first
Write the calls for both apps: what a driver sends, how a rider asks, how an offer reaches a driver. Then list the trip states, and say what lives in memory and what must be saved.

Endpoints

MethodPathRequestResponseNotes
PUT/v1/drivers/me/location{ lat, lng, heading, speed, ts, seq }204Sent every ~4 s, often over a long-lived connection. Last write wins per driver. seq lets us drop an old ping that arrives late.
POST/v1/drivers/me/status{ status: online | offline }200 { status }Going online adds the driver to the geo index. Going offline (or no ping for 15 s) removes them.
POST/v1/rides{ pickup, dropoff, quoteId }201 { rideId, state: REQUESTED }Idempotency-Key header, so a retry never creates a second trip. quoteId pins the price the rider saw.
GET/v1/rides/{id}none200 { state, driver, eta, price }Plus a WebSocket or push stream for live changes. The GET is the fallback after a reconnect.
POST/v1/rides/{id}/cancelnone200 { state: CANCELLED, fee }Idempotent. The fee depends on the state when it is cancelled.
POST/v1/offers/{offerId}/respond{ accept: true | false }200 { rideId } or 409From the driver. 409 means the offer expired or was withdrawn. The driver gets a clear answer, not silence.

Data model

WhereWhat is storedNotes
Geo index (memory, per region)cell โ†’ set of driver ids, and driver โ†’ {lat, lng, status, updated_at}Latest only. About 100 bytes a driver. Entries expire if no ping for ~15 s. Rebuilt in seconds from incoming pings after a crash.
Trips (durable store)trip_id, rider_id, driver_id, state, pickup, dropoff, price, version, timestampsSharded by trip_id or rider. Every state change is a write with a version number.
Driver state (small, strongly consistent)driver_id โ†’ {status, current_trip, reserved_until}The place where a driver is reserved for exactly one offer or trip.
Trail (log)sampled (driver, time, lat, lng)Append-only stream to a log or object store. Used for analytics and disputes, with a short retention.
Surge counters (memory)cell โ†’ {requests, free drivers} per sliding windowTiny. About 20 MB for 100,000 cells.
Trip state machine
REQUESTED  --offer sent-->      OFFERED
OFFERED    --driver accepts-->  ACCEPTED       (driver reserved for this trip)
OFFERED    --declined/timeout-> REQUESTED      (try the next driver)
ACCEPTED   --driver arrives-->  ARRIVED
ARRIVED    --rider boards-->    IN_PROGRESS
IN_PROGRESS --drop-off-->       COMPLETED  --> payment saga
REQUESTED | OFFERED | ACCEPTED | ARRIVED --cancel--> CANCELLED (fee rules apply)
๐Ÿ“Which store, and why
Three different needs, three different stores. Locations need huge write rates and no history, so an in-memory geo index. Trips need durability, versions and strong consistency per trip, so a sharded transactional store. The question 'is this driver free?' needs one small, strongly consistent record per driver. Do not use one database for all three.
๐ŸŽค
Say it out loud
โ€œThe driver app sends its location every four seconds, last write wins, and the server keeps only the latest point in an in-memory grid. The rider calls create ride with an idempotency key. A trip moves through a small state machine, and every change is saved with a version before it is acknowledged. The offer to a driver is a separate object with an expiry, and the driver answers accept or decline. I keep three stores: an in-memory geo index for location, a durable store for trips, and one small strongly consistent record per driver that says who they are reserved for.โ€

Step 4Draw the high-level designabout 8 min

๐Ÿค”
Pause. Try it yourself first
Draw the boxes for one ride request: where do locations go, how do you find nearby drivers, where is the driver reserved, and how does the rider see the driver move?
Ride sharing: high-level design
๐Ÿš—Driver applocation every 4 s
โ†’โ†“pings
Gateways
๐Ÿ”ŒDriver gatewaysWebSocket
๐Ÿ“ฒRider gatewaysWebSocket + push
โ†’โ†“
๐Ÿ“Location servicelatest per driver, TTL
โ†’โ†“
๐ŸงญGeo indexcells, in memory, per region
Request a ride
๐Ÿ™‹Rider app
๐ŸŽซRide servicetrip state machine
๐ŸŽฏDispatchshortlist, rank, offer
Helpers
๐Ÿ›ฃ๏ธETA and routingroad graph + traffic
๐Ÿ’ฒPricingsurge per cell
๐Ÿ”’Driver statereserve one driver
Durable and async
๐Ÿ—„๏ธTrip storesharded, versioned
๐Ÿ“จEvent logtrail, analytics
๐Ÿ’ณPaymentssaga, separate service
Locations flow into a sharded in-memory index. Dispatch reads it, reserves a driver, and the trip service owns the state. Gateways carry the live map.
ComponentWhat it does
GatewaysHold the WebSocket connections for drivers and riders. Stateless apart from the open sockets. Fall back to push when a socket drops.
Location serviceTakes pings, drops stale ones by sequence number, keeps the latest point, and updates the driver's cell. Expires a driver after about 15 s of silence.
Geo indexIn memory, per region. A grid of cells (geohash, S2 or H3) pointing to the drivers inside. Answers 'who is near this point' in microseconds.
DispatchShortlists nearby free drivers, asks the ETA service to rank them, reserves one, and sends the offer. Handles decline and timeout.
Driver stateA small, strongly consistent record per driver. A compare-and-set on it is what prevents one driver being offered two rides.
Ride serviceOwns the trip state machine and the trip store. Every transition is idempotent and versioned.
ETA and routingPickup ETA and trip ETA from a road graph with live traffic. Cached by cell pair for a few seconds.
PricingQuotes a price with a surge multiplier per cell, valid for a short time. Reads supply and demand counters.
Event logEvery location sample and every trip transition goes onto a log for analytics, disputes and rebuilding views.
Write path (follow one request)
  1. The driver app sends a ping over its WebSocket to a driver gateway.
  2. The gateway forwards it to the location service of that region, with the driver id and a sequence number.
  3. The service drops it if an older sequence arrives after a newer one, and otherwise overwrites the driver's latest point.
  4. If the driver crossed into another cell, the service moves the id between cell sets in the geo index.
  5. A sampled copy (for example one in five) goes onto the event log for trails and analytics. The index is the only place read in real time.
  6. If a driver sends nothing for about 15 seconds, a sweeper removes them from the index and marks them stale.
Read path (follow one request)
  1. The rider asks for a quote. Pricing reads the surge for the pickup cell and returns a price valid for a couple of minutes (quoteId).
  2. The rider confirms. The ride service creates the trip as REQUESTED, using the idempotency key, and saves it.
  3. Dispatch asks the geo index for free drivers in the pickup cell and its neighbours, widening the ring if there are too few.
  4. It sends the shortlist (about 10) to the ETA service and ranks by pickup time on real roads, not straight-line distance.
  5. For the best driver, dispatch does a compare-and-set on the driver's state: free to reserved-for-this-trip, with a 10-second expiry. If it fails, take the next driver.
  6. The offer goes to the driver. If they accept, the trip becomes ACCEPTED. If they decline or time out, release the reservation and offer to the next.
  7. From then on, driver pings are pushed to the rider's gateway for that trip only, so the rider sees the car move.
๐ŸŽค
Say it out loud
โ€œHere is the picture. Drivers connect to gateways and send a ping every four seconds. A location service keeps only the latest point per driver and moves them between cells in an in-memory grid, one per region. When a rider confirms a ride, the ride service saves the trip. Dispatch asks the grid for free drivers in the pickup cell and its neighbours, ranks them by road ETA, and reserves the best one with an atomic compare-and-set before sending the offer. If the driver accepts, the trip is accepted, and from then on the driver's pings are pushed to that rider only. Payments run afterwards as a saga.โ€

Step 5Deep dive into the hard partsabout 15 min

๐Ÿง The pattern for every deep dive
Problem โ†’ options โ†’ pick one โ†’ say why โ†’ say what it costs. Interviewers score the reasoning more than the choice.
5.1

Location ingestion and the geo index

The problem: 750,000 pings a second must update an index that can answer 'who is near this point' in microseconds, while every driver keeps moving. Writing each ping to a database would be 1.6 TB a day of data nobody reads.

OptionHow it worksGoodBad
A database row per driver, updated on every pingUPDATE drivers SET lat, lng, updated_at. Query with a bounding box.Simple. Familiar tools.750k writes a second is far beyond one database, and a bounding-box query on moving data keeps hitting hot rows.
Quad tree over moving pointsA tree that splits where there are many drivers.Adapts to dense and sparse areas.Every move may change the tree. Rebalancing under 750k updates a second is expensive. Good for mostly-static points.
Fixed grid of cells (geohash, S2 or H3), latest position in memoryMap each ping to a cell id. Keep cell โ†’ drivers and driver โ†’ position in memory, sharded by region.A move is two small set updates. Lookup is the cell plus its neighbours. Easy to shard by cell prefix.Needs the neighbour query for the boundary case, and a cell size that fits the density.
A geo-aware key-value store (for example sorted sets with geo commands)Store points in a store that supports radius queries.Less code to write. Fine for a small or mid-sized city.One node per region hits a write limit, and you give up control of the cell layout.
Pick
A fixed grid of cells, latest position only, in memory, sharded by region

The invariant we protect here is simple: the index holds each online driver exactly once, at roughly their latest position. A fixed grid makes a move cheap (remove from one cell set, add to another) and makes a lookup cheap (read a few cells). A quad tree is great for points that rarely move; for 750k moves a second, rebuilding or rebalancing is the cost we cannot afford.

Per region this is only about 75,000 writes a second and 30 MB, so one in-memory shard (with a replica) is enough. If it is lost, it refills from the next pings in about 4 seconds, so we do not need to persist it. The cost: briefly after a crash the index is thin, so dispatch widens its search radius.

Cell size (illustrative)Good forCost
About 150 m (fine)Dense city centres: few drivers per cellMore neighbour cells to read for a 2 km radius (about 100)
About 1 km (medium)Most cities: tens of drivers per cellA good default: a 3 by 3 ring covers about 3 km
About 5 km (coarse)Rural areasToo many drivers per cell in cities, so each lookup scans many
โš ๏ธThe boundary problem
A rider standing at the edge of a cell has drivers just across the line in the next cell. Always read the rider's cell and its neighbours, then sort by real distance. Widen the ring if you find fewer than K drivers. Hexagons (H3) make this cleaner because all neighbours are the same distance away.
๐Ÿ“Cheaper pings
Send less when you can: adaptive frequency (slower when stopped, faster in a turn), send only changes, and batch pings from one gateway into one call to the location service. Fewer pings cut both battery and server load.
๐ŸŽค
Say it out loud
โ€œA database cannot take 750 thousand writes a second, and a quad tree is costly to rebalance for moving points. So I would keep a fixed grid of cells, using geohash, S2 or H3, with only the latest position per driver, in memory, sharded by region. A move is two small set updates. A lookup reads the rider's cell and its neighbours to handle the boundary, then sorts by real distance. Per region it is about 30 megabytes, and if it crashes it refills from the next pings in a few seconds. I would sample a trail onto a log for analytics, not write every ping to a database.โ€
5.2

Matching without double-assigning a driver

The problem: Two riders near the same driver ask at the same moment. If both requests read 'driver G is free' and both offer G, one rider is promised a driver who is already gone. The invariant: a driver is reserved for at most one offer or trip at a time.

OptionHow it worksGoodBad
Read free drivers, offer, hopePick the nearest free driver and send the offer. Check later.Simplest.Races at busy times: two offers to one driver, a driver sees conflicting offers, and a rider is told yes then no.
Lock the whole region while matchingOne distributed lock per region.No races.Serialises matching for a whole city. Throughput collapses and a stuck holder blocks everyone.
Atomic reservation on the driver recordA compare-and-set (free โ†’ reserved for trip T until time X). Only one request wins. A short expiry releases it if nothing happens.Fine-grained, fast, and correct. Cost is one small strongly consistent write per offer.Needs a store with atomic conditional writes and a clock for the expiry, and care with the expiry (fencing).
Batch (global) matching every ~2 secondsCollect requests and free drivers for a window, solve one assignment problem for the whole set, then reserve each pair.A better total pickup time, and no race between requests inside the batch.Riders wait up to the window. A heavier algorithm. Reservation is still needed against other batches.
Pick
Per-request matching with an atomic driver reservation, with batch matching as a later improvement in busy cells

The reservation is what enforces the invariant. Dispatch picks the best driver by road ETA, then does one compare-and-set on that driver's state: from free to reserved for offer O until 10 s from now. If another request got there first, the write fails and dispatch tries the next driver. No locks are held across the network, and a crashed dispatcher cannot strand a driver, because the reservation expires.

Per-request matching is not the best overall. Early riders take drivers that later riders needed more. Batching gives a lower total pickup distance, at the cost of a short wait (see the visualizer). The pragmatic answer: start per-request, and batch only in cells where demand is high enough that the wait is worth it.

Reserving a driver (sketch)
-- one small strongly consistent record per driver
ok = driverState.compareAndSet(
       key      = driverId,
       expect   = { status: FREE },
       set      = { status: RESERVED, tripId: T, until: now + 10s, version: v + 1 })

if (!ok) -> take the next candidate        -- somebody else won
-- on accept:   RESERVED -> ON_TRIP (same tripId, same version check)
-- on decline / timeout / expiry: RESERVED -> FREE   (only if tripId and version still match)
โš ๏ธSay the edge cases out loud
The driver accepts after the offer expired: the accept fails with 409, because the reservation no longer matches. Dispatch crashes after reserving: the reservation expires in 10 s and the driver is free again. A slow dispatcher wakes up late: its write carries an old version, so the store rejects it (the same idea as a fencing token).
Offer styleHowGoodBad
One driver at a timeOffer, wait up to 10 s, then the nextNo wasted offers. Fair to drivers.Slow if several decline: 3 declines is 30 s
A few at once, first to accept winsOffer to 3, cancel the others when one acceptsFaster matchDrivers see offers that vanish. Reserve all three, release two. More complexity.
๐ŸŽค
Say it out loud
โ€œThe invariant is that a driver is reserved for at most one offer or trip. I enforce it with one atomic compare-and-set on a small per-driver record: free to reserved for this trip, until ten seconds from now. If another request wins, I take the next candidate. No lock is held across the network, and if dispatch crashes the reservation simply expires. A late accept fails because the reservation no longer matches. Per-request matching is simple but not optimal, so in busy cells I would add batch matching over a two-second window to lower the total pickup time, and I would be clear that it makes riders wait a little.โ€
5.3

The trip state machine and surviving failure

The problem: A trip lasts about 20 minutes, across phones that lose signal, servers that restart and users who tap twice. Invariants: one active trip per rider, one per driver, and no transition applied twice or lost.

OptionHow it worksGoodBad
Keep trip state in memory on one serverA server owns the trip while it runs.Fast and easy.A crash loses live trips. A rolling deploy drops them. Failover is manual.
Save the state, but update with plain writesUPDATE trips SET state = ? WHERE id = ?Survives a crash.A retried tap or a late message can move the trip backwards (ARRIVED then back to ACCEPTED), and two writers can disagree.
A versioned state machine with conditional writesEach transition says 'from state S at version v to state S2'. The store applies it only if the current state and version match. Retries carry the same transition id.Idempotent, safe to retry, rejects stale or illegal moves, and every change is a durable row.Needs a store with conditional updates, and clients that handle a 409 by re-reading the trip.
Event sourcing: store transitions, derive the stateAppend events (accepted, arrived...) and fold them to get the current state.A full audit trail and easy replay.Heavier to build. You still need a conditional append so two events cannot both be the next one.
Pick
A versioned state machine with conditional writes, plus an event log for audit

The mechanism for no transition applied twice or lost is the conditional write plus a transition id: UPDATE ... SET state = 'ARRIVED', version = v + 1 WHERE id = ? AND state = 'ACCEPTED' AND version = v. A retry with the same transition id finds the work already done and returns success. A stale or impossible move updates zero rows and is rejected. The trip store is sharded by trip id, so each trip is one row on one shard.

One active trip per rider and per driver is a second invariant. For the driver it comes from the reservation record. For the rider, the create call takes an idempotency key and checks a unique constraint on (rider, active). Cost: a few more conditional writes, and every client must handle a 409 by re-reading the trip.

FailureWhat the design does
The driver app loses signal mid-tripThe trip is already saved, so nothing is lost. The app buffers pings and transitions locally, and on reconnect sends them with sequence numbers. The server applies the ones that still fit and ignores the rest.
A server crashes between saving a transition and replyingThe client retries with the same transition id. The store sees the work is done and returns the saved result.
A rider double-taps request rideThe same idempotency key, so one trip. A second key while one is active hits the unique constraint.
A trip is stuck in OFFERED because dispatch diedA sweeper finds OFFERED trips with an expired reservation and puts them back to REQUESTED.
The driver forgets to end the tripA timeout rule and a geofence check suggest completion. A human or support flow settles the rest.
Payment fails after COMPLETEDA saga retries or flags it. The trip is not rolled back (the ride happened). See Design a Payment System.
๐Ÿ’กOrder of events across systems
Save the transition first, then publish it (an outbox), and let notifications, pricing and analytics read the log. Never notify a rider of a state the database does not hold.
๐ŸŽค
Say it out loud
โ€œA trip is a small state machine, and I save every transition as a conditional write: move from accepted to arrived only if the current state is accepted and the version matches, with a transition id so a retry is harmless. That gives me no lost and no repeated transitions, and a late or impossible move is rejected. One active trip per driver comes from the reservation record, and per rider from an idempotency key and a unique constraint. If a server dies, the state is already saved, and a sweeper puts stuck offered trips back to requested. If the driver loses signal, the app buffers and replays with sequence numbers.โ€
5.4

ETA, surge pricing and the live map

The problem: Matching needs a believable pickup time. Pricing must react to demand without flapping. And a million riders must see cars move without a million database reads.

OptionHow it worksGoodBad
Straight-line distance for ETADistance divided by an average speed.Trivial and instant.Wrong near rivers, one-way streets and highways. Ranks a driver across a river as nearest.
Road graph routing with live traffic, cachedShortest path on the road graph using current speeds. Cache results by (cell, cell) for a few seconds.A believable ETA, and about 9,300 calls a second is manageable.Needs a routing service, traffic data and a cache with a short life.
Surge: a multiplier from supply and demand per cellCount requests and free drivers over a sliding window. Map the ratio to a multiplier, with smoothing.Reacts to real conditions and pulls drivers to busy areas.A raw ratio flaps from second to second. Needs smoothing, caps and a short-lived quote.
Push live position to riders over a socketThe gateway forwards each driver ping to the one rider on that trip.A smooth live map. Only riders with an active trip receive anything.About 280,000 messages a second at peak and 1.1 million open connections to manage, with reconnects.
Pick
Road-based ETA with a short cache, smoothed per-cell surge with a short-lived quote, and socket push with a push-notification fallback

ETA decides who is 'nearest', so it must be road-based, and it is the one place the design depends on the maps system (see Design Google Maps). Caching by cell pair keeps it cheap because many requests in the same area ask nearly the same question.

For surge, compute ratio = requests รท free drivers per cell over a sliding window of about a minute, average it with neighbouring cells and the previous value, cap it, and round to steps (1.0, 1.2, 1.5...). The rider gets a quote that is valid for a couple of minutes, so the price they saw is the price they pay. Cost: a rule that is hard to explain and sensitive to regulation and fairness, so state that these rules vary by place and need a policy owner.

Surge rule (illustrative)Requests / free driversMultiplier
Calmup to 1.01.0ร—
Busy1.0 to 1.51.2ร—
Very busy1.5 to 2.51.5ร—
Peak (capped)above 2.52.0ร— cap
๐Ÿ“Smoothing in one line
surge = 0.7 ร— previous + 0.3 ร— new_ratio, updated every 30 seconds. Without it, a single request can flip a cell between 1.0ร— and 1.5ร— and riders see the price change while they look at it.
๐Ÿ’กCheaper live map
Send positions every 2 to 4 seconds and let the client animate between points. Drop updates for riders who have the app in the background and rely on a push when the driver arrives.
๐ŸŽค
Say it out loud
โ€œETA has to come from a road graph with live traffic, because straight-line distance picks the wrong driver across a river. I cache it by cell pair for a few seconds, which keeps nine thousand calls a second cheap. For surge I count requests and free drivers per cell over a sliding minute, smooth the ratio with the previous value and the neighbours, cap it, and give the rider a quote valid for a couple of minutes. For the live map, the gateway forwards each driver ping only to the rider on that trip, with push as a fallback when a socket drops. I would say the surge rules need a policy owner, because fairness and regulation vary by place.โ€
VisualizerFour riders, twelve drivers: who gets whom?Start with one request at a time and atomic reservation. Turn reservation off to see two riders offered the same driver. Then switch to batch matching and compare the total pickup distance. Change who asks first.
How are riders matched?
Reserve the driver before offering?
Who asks first?
ABCDEFGHIJKL1234
โ—‹ letter = driver (green ring = matched, red ring = offered twice)โ–ก number = riderLine = route on the grid. Red dashed = offer that fell through.
Rider 1: Driver G, 1 block
Rider 2: Driver A, 5 blocks
Rider 3: Driver E, 1 block
Rider 4: Driver I, 1 block
Total pickup
8
blocks, riders who got a driver
Average pickup
2.0
blocks per matched rider
Unmatched riders
0
have to wait or ask again
Double-booked drivers
0
offered to two riders
Best possible total
6
batch, for these drivers
Safe, but not the best. Each rider got the nearest free driver at the moment they asked, so there was no double assignment. The early riders took drivers that later riders needed more. Total pickup is 8 blocks, but looking at all four together gives 6 (2 fewer). Choose โ€œRider 4 firstโ€ and the total changes: greedy depends on the order.

A teaching model on an 8 by 8 grid with fixed positions (no random numbers). Distance is the number of blocks along the streets, not a straight line. Real systems use road distance and live traffic for the pickup time, and add many more rules (rating, vehicle type, direction of travel). One request at a time picks the nearest free driver, and ties go to the lower letter. Batch tries every way of pairing riders and drivers and keeps the one with the lowest total.

Step 6Scale, bottlenecks and failuresabout 7 min

๐Ÿค”
Pause. Try it yourself first
What breaks first? Think about a concert ending, a region going down, a driver in a tunnel, and a hot cell. Then say what you would watch.

What breaks first, and the fix

BottleneckFix
750k location writes a secondShard by region (about 75k a second each). Batch pings per gateway. Adaptive ping rate. Keep latest-only in memory, and sample the trail to a log.
A hot cell (stadium, airport) with thousands of drivers and ridersSplit the cell into finer cells, or use a smaller hex size for that area. Batch matching in that cell, and queue requests for the next window.
Demand spike when an event endsSurge pulls drivers in. Dispatch uses batch matching and a request queue with a cap. Shed load on non-essential calls (history, receipts) first.
ETA service latency during matchingCache by cell pair, rank only a shortlist of about 10, set a deadline, and fall back to straight-line ranking if routing is slow.
Open connections: about 80 gateways, millions of socketsStateless gateways behind a load balancer, a connection registry for 'which gateway holds this user', and jittered reconnects after a gateway restart.
Trip store write load at peak (about 5,600 transitions a second)Shard by trip id. Each trip is one row on one shard, so this is easy to spread.
Cross-region rides near a borderAssign the trip to the pickup region. Query the neighbour region's index for drivers within range. The driver reservation lives in the driver's home region.

What if a part fails?

FailureHow the design copes
A geo index shard crashesA replica takes over. The index is rebuilt from the next pings in about 4 seconds. Dispatch widens its search radius during the gap.
Dispatch crashes after reserving a driverThe reservation expires in 10 seconds and the driver is free again. A sweeper returns the trip to REQUESTED and matching restarts.
A whole region goes downRiders and drivers fail over to a standby region. Trips in progress are in a replicated trip store. Accept that a few seconds of transitions may need to be replayed from device buffers.
The driver app is offline (a tunnel)The trip is safe in the store. The app buffers and replays on reconnect. The rider sees the last known position, marked as stale.
ETA or routing service is downFall back to straight-line ranking with a safety margin, and show a wider ETA range to the rider.
Payment service is slow or down at the end of a tripComplete the trip, queue the charge, and retry with an idempotency key. Never block the rider from leaving the car.
What to monitor
  • โ€ขTime to match (request to accepted), by city, p50 and p95, and the rate of unmatched requests
  • โ€ขLocation lag: now minus the newest ping per cell, and the number of stale drivers
  • โ€ขOffer funnel: offers sent, accepted, declined, expired, and the double-reservation conflicts caught
  • โ€ขTrip state errors: rejected transitions (409), stuck states, orphaned trips
  • โ€ขGateway connections, reconnect rate, and push-notification fallback rate
  • โ€ขSurge multiplier by cell and how often it changes (flapping)
Security and abuse
  • โ€ขAuthenticate every ping and offer. A fake driver app could claim a location it is not at.
  • โ€ขSpoofed GPS: compare location with speed, road snapping and device signals (said at a high level, because the detection details are sensitive).
  • โ€ขKeep location trails short-lived and access-controlled. They are personal data, and retention rules vary by place.
  • โ€ขHide exact driver position until a trip is accepted, and hide the rider's exact home from the driver until needed.
  • โ€ขRate-limit ride requests and offer responses per account, and watch for promo and referral abuse.

Step 7Wrap upabout 3 min

Drivers send a location every 4 seconds into a sharded in-memory grid that keeps only the latest point, about 300 MB for all online drivers. A rider's request becomes a trip in a versioned state machine. Dispatch shortlists nearby drivers from the grid and its neighbours, ranks by road ETA, and reserves the best driver with an atomic compare-and-set before offering, so no driver is promised twice. Surge is a smoothed supply-and-demand ratio per cell with a short-lived quote, and the live map is pushed over sockets to riders with an active trip. Payments run later as a saga.

Trade-offs you made

DecisionWhat we gainWhat it costs
Latest-only location in memoryHandles 750k writes a second with a tiny index and no database on the hot path.Position history is only a sample. A shard crash leaves a few seconds of thin coverage.
Fixed grid cells, not a quad treeA move is two cheap set updates. Easy to shard.Needs the neighbour query and a good cell size for density.
Atomic driver reservation with expiryNo double assignment, with no region-wide lock.One strongly consistent write per offer, and care with expiry and stale writers.
Per-request matching firstSimple, fast, no waiting for a batch.Not the best total pickup time. Batching in busy cells can do better, at the cost of a short wait.
Versioned, idempotent state machineSafe retries and no lost or repeated transitions.Clients must handle 409 and re-read. A conditional-write store is required.
Smoothed surge with a quoteStable prices that riders can trust, and supply that follows demand.Complex to explain, and sensitive to fairness and regulation.
If we had more time, we wouldโ€ฆ
  • โ€ขBatch matching in hot cells, with a two-second window and a total-wait objective.
  • โ€ขPool and shared rides: matching becomes a routing problem over several riders.
  • โ€ขPredictive supply: nudge drivers toward areas where demand is about to rise.
  • โ€ขBetter ETA from learned models on top of the road graph.
  • โ€ขA simulation and replay harness to test matching and surge changes before release.
๐ŸŽค
Say it out loud
โ€œTo recap: location goes into a sharded in-memory grid with only the latest point per driver, about 300 megabytes in all. A ride request creates a trip in a versioned state machine. Dispatch reads the pickup cell and its neighbours, ranks by road ETA, and reserves the best driver with an atomic compare-and-set so nobody is promised twice. Surge is a smoothed ratio per cell with a short-lived quote, and the live map is pushed only to riders on an active trip. The trade-offs I made are latest-only location, per-request matching, and a reservation with expiry. With more time I would add batch matching in hot cells, then pool rides.โ€

Q&ACross-questions (26)

๐Ÿ’กHow to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Location and the geo index

The biggest load in the system. Know why, and know the structure.

Matching and the dispatch invariant

The correctness heart of the design: one driver, one offer.

Trips, state and failures

Interviewers push on what happens when the phone, the server or the region fails.

Scale, pricing and operations

The senior questions: spikes, geography, cost, privacy and how you would test it.

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
Add pool and shared ridesMatching becomes routing: a vehicle holds several riders, each match is a route with detours and ETA limits. The driver reservation becomes seats. Batch matching becomes essential.
Add scheduled rides (book for tomorrow 6 am)A scheduled-jobs store holds the request. A job releases it to dispatch shortly before pickup, and a driver can be pre-assigned. Needs a no-show plan.
Riders should see a fixed price, not a surge multiplierPricing returns a quote from a model of expected demand and trip cost. The quote is guaranteed, so the company carries the risk. Surge counters feed the model, not the price directly.
Drivers must be matched fairly (no favourites)Add a fairness term to ranking, such as time since last trip, and measure the distribution of trips. Batch matching can optimise it directly.
Ten times more drivers online7.5M writes a second. Shard more finely by cell prefix, lower the ping rate when idle, and batch at the gateway. The index still fits in memory: 3 GB.
Deliveries (food, packages) on the same platformAdd a second kind of trip with pickup and drop-off at different places, and a different state machine. The geo index and location service are shared.
Hard real-time guarantee: match in under 2 seconds at the 99th percentileNo parallel offers waiting on a human, so use pre-fetched shortlists, a hot reservation path and driver auto-accept in limited cases. More cost, less choice for drivers.
Offline mode for riders with bad signalSMS or push fallback for the key transitions, a long-lived idempotent create call, and a clear local state so the app can resume safely.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts drawing at once, or builds everything (pool, ratings, payments).Scopes request, match, track, ETA and pricing, and states what is left out.Also fixes the numbers, the location freshness, the accept timeout and the failure expectations, and says what drives the design.
EstimationNo numbers, or counts only rides.Works out ride requests per second and some storage.Finds that location writes are about 800 times the requests, and uses that to justify latest-only in-memory storage and sampled trails.
Geo indexSQL table with lat and lng, or a bounding box on every query.Grid or geohash with a neighbour lookup.Explains the boundary problem, cell size by density, why not a quad tree for moving points, sharding by region, and rebuilding from pings.
Dispatch correctnessOffers to the nearest driver with no race handling.Notices the double-assignment problem and adds a lock or a check.States the invariant, uses a per-driver atomic reservation with expiry, handles late accepts and dispatcher crashes, and compares batch matching with its cost.
Failure and stateAssumes servers never fail mid-trip.Saves trip state and mentions retries.A versioned idempotent state machine, sweepers for stuck states, offline driver replay, and a region failover plan with its limits.
CommunicationJumps between topics and lists technologies.Follows the steps and explains each choice.Summarises each step, names trade-offs with numbers, says what is out of scope, and offers a phased plan.

AvoidCommon mistakes on this question

MistakeDo this instead
Treating ride requests as the main loadDo the maths: location pings are about 800 times more frequent. Design the location path first.
Writing every location ping to a databaseKeep only the latest in memory, sampled trails on a log, and say why.
Finding nearby drivers with a bounding-box SQL queryUse a cell grid with a neighbour lookup, in memory, sharded by region.
Ignoring the double-assignment raceState the invariant and reserve the driver with an atomic compare-and-set and an expiry.
Ranking by straight-line distanceRank a shortlist by road ETA with live traffic, and say how you cache it.
Keeping trip state in server memoryA durable, versioned state machine with idempotent transitions and sweepers.
Cancelling a trip when pings stop for a few secondsTunnels and weak signal are normal. Buffer, replay, and escalate only after a long silence.
Putting payment logic inside the trip serviceComplete the trip first, then run a saga with idempotency keys. Link to the payment design.

Revise60-second revision sheet

  • โœ”Load: 3M drivers รท 4 s = 750k location writes a second. Ride requests are only about 930 a second at peak. Location is about 800 times the load.
  • โœ”Index: latest position only, in memory, a grid of cells (geohash, S2 or H3), sharded by region. About 100 bytes a driver, 300 MB in all.
  • โœ”Lookup: the rider's cell plus its neighbours (boundary problem), widen the ring if short, then rank about 10 by road ETA.
  • โœ”Invariant: a driver is reserved for at most one offer or trip. Enforced by an atomic compare-and-set on the driver record with a 10-second expiry.
  • โœ”Offers: one at a time with a timeout. A late accept gets a 409. A dead dispatcher's reservation just expires.
  • โœ”Batch matching: better total pickup time, but riders wait for the window. Use it in busy cells.
  • โœ”Trip: a versioned state machine, conditional writes, transition ids. Saved before acknowledged. Sweepers fix stuck states.
  • โœ”Surge: requests รท free drivers per cell over a sliding minute, smoothed, capped, with a short-lived quote.
  • โœ”Live map: gateways push driver pings only to the rider on that trip. Push notification as a fallback.
  • โœ”Payments: complete the trip first, then a saga with idempotency keys. Never block the rider.

Read these topics next

Geohashโ†’

A way to turn a place into a cell id.

S2 and H3โ†’

The cell systems used for ride sharing, and the hexagon advantage.

Quad Treesโ†’

The alternative index, and why moving points make it costly.

WebSocketsโ†’

How the live map and offers reach the phones.

Distributed Locksโ†’

Why we use a per-driver compare-and-set and not a region lock.

Idempotencyโ†’

Why retried taps and transitions must be harmless.

SAGA Patternโ†’

How trip completion and payment stay consistent.

Design Google Mapsโ†’

Where road routing and ETA come from.

โ† Previous
Design a Social Media Platform (Facebook)
Next โ†’
Design a Payment System