System designby Learnastra

System-design interview · Core interviews

Design a ride-hailing backend

By Anup Rai

Design ride discovery, exclusive driver assignment and recoverable trip tracking, while keeping frequent GPS updates separate from durable trip decisions.

You will learn to

  • Trace ride creation, offer acceptance and trip recovery end to end.
  • Prevent both two rides claiming one driver and two drivers claiming one ride.
  • Scale location ingestion and tracking without weakening assignment ownership.

Practice in this chapter

8 interview questions with model answers and follow-ups.

Go to interview practice

Useful foundations: Design nearby place search and friend discovery · Databases, data models, and ACID transactions · Real-time communication: polling, long polling, SSE, and WebSocket · Message queues, event logs, delivery guarantees, and backpressure

Workload and timing examples are interview assumptions.

01Define the ride and the guarantee

Design a ride-hailing service for one operating region. A rider requests a pickup, nearby drivers receive offers, one driver accepts, and both participants track the trip through completion. Exclude pooling, surge-price calculation, route computation and a full payment ledger from the first answer. An external routing service can supply estimated pickup times; that does not require designing the road graph here.

Use ride R501, rider Maya and driver D17 throughout. The essential guarantees are that R501 has at most one winning driver and D17 has at most one active ride. Nearby-map results are approximate: a driver may move or accept another request before Maya acts. Only a committed acceptance creates an assignment.

Assume latest positions older than ten seconds are excluded from discovery, first offers arrive within two seconds for 95% of admitted requests with eligible nearby supply, and an accepted assignment commits within one second at the 95th percentile, excluding human decision time. These are negotiated targets. When the database cannot safely decide who owns a ride, pause assignment rather than report success from competing regional writers. GPS availability and durable trip availability remain separate concerns.

Ask whether matching must choose the globally best driver or a suitable nearby driver, whether assignments cross operating regions, and whether billing belongs in scope. Choose suitable regional matching here; confirm the assignment and location targets below before expanding the architecture.

02Functional requirements

  1. Request and discover. Create a ride request, find suitable nearby available drivers and send bounded, expiring offers.

  2. Accept and manage a trip. Allow one offered driver to accept, then support authorized start, completion and cancellation transitions.

  3. Track participants. Publish recent driver positions and deliver active-trip updates to the rider and driver.

  4. Recover status. Let either participant retrieve authoritative trip state after a lost response or disconnected socket without creating another ride or assignment.

03Non-functional requirements

These are illustrative interview assumptions, not product facts or measured benchmarks. Confirm them before choosing components, then validate the completed design under the stated workload. Here p95 means the 95th-percentile latency: 95% of measured requests take no longer than that value. Report errors and rejected work alongside latency; a fast failure is not a successful outcome.

  1. Workload. Plan for 500,000 concurrently online drivers updating every three seconds, about 166,667 position updates/s, and one million rides/day. Size localized surges separately from daily averages.

  2. Response time. Target a first offer within two seconds for 95% of admitted requests with eligible nearby supply. Target acceptance commit within one second p95, excluding driver decision time. Track no-supply outcomes separately rather than treating them as successful offers.

  3. Position freshness. Exclude positions older than ten seconds from discovery. Matching remains approximate because drivers move and spatial indexing may lag.

  4. Assignment correctness. Each ride has at most one winning driver and each driver at most one active ride. Cancellation and acceptance must make one consistent decision about both records.

  5. Durability and availability. Require acknowledged assignments to survive one database-node failure using synchronous durable replication and safe failover. Pause assignment when current write authority cannot be established; a location outage must not erase an existing trip.

  6. Access control. Authenticate drivers and riders, restrict precise tracking to current trip participants and prevent old sessions from overwriting new location updates.

04Follow one ride before adding services

Start with one regional application, a relational database and a connection gateway that sends messages to phones. The database stores rides, driver availability, offers and latest positions. Maya creates R501 with a request key. The application selects nearby available candidates, asks a routing service for a few pickup estimates, and sends a small batch of expiring offers.

D17 accepts offer O81. The application runs a short transaction that checks the offer, the ride and the driver together. It records assignment A77, marks both sides assigned, stores the successful reply for retries and commits notification work. After commit, the gateway informs Maya and D17. If the socket fails, the assignment still exists and either phone can retrieve it.

The trip then moves through assigned, in-progress and completed states, with cancellation allowed according to the agreed policy. Only authorized participants may change those states. Completion releases the driver through the same authority that assigned them. A location heartbeat cannot independently mark an assigned driver available.

This baseline already supports the whole user flow. More services later isolate high-volume location traffic and delivery work; they do not supply correctness that was absent from the first version.

Design diagramOne region can complete a ride assignment

The database decides assignment; phone delivery follows the commit.

One region can complete a ride assignmentThe database decides assignment; phone delivery follows the commit. rider to api: Create ride / accept offer; api to routing: Rank a bounded shortlist; api to db: Atomic assignment and replay; db to gateway: Committed notification work; gateway to rider: Offer or trip updateCreate ride / accept offerRank a bounded shortlistAtomic assignment and replayCommitted notification workOffer or trip updateACTORRider and driverphonesSERVICERegional ride serviceSTORERides, drivers, offers,outboxSERVICEConnection gatewayEXTERNALPickup ETA servicesyncasync
Read each connection in order
  1. syncCreate ride / accept offerRider and driver phones → Regional ride service
  2. syncRank a bounded shortlistRegional ride service → Pickup ETA service
  3. syncAtomic assignment and replayRegional ride service → Rides, drivers, offers, outbox
  4. asyncCommitted notification workRides, drivers, offers, outbox → Connection gateway
  5. asyncOffer or trip updateConnection gateway → Rider and driver phones

05Size locations, rides and subscribers separately

Assume 500,000 drivers are concurrently online at peak and each sends a location every three seconds. That is about 166,667 updates per second. At a compact 40-byte payload, incoming coordinates alone use roughly 6.67 MB/s before network framing, authentication and replication. Daily active drivers are not automatically concurrent drivers, so state that assumption explicitly.

If five viewers subscribe to each driver, there are 2.5 million subscriptions and about 33.3 MB/s of raw outbound coordinate payload at the same update frequency. A million rides per day averages only 11.6 ride starts per second. The low average ride rate does not remove local station surges or justify storing every coordinate in the assignment database.

At 128 bytes per stored sample, retaining every three-second update from 500,000 drivers creates roughly 1.84 TB per day before replicas. Keeping only the latest record uses about 64 MB of raw records, although spatial indexes, connection maps and runtime overhead add substantial memory.

Measure peak updates, candidate counts, routing-call cost, first-offer delay and assignment transaction time separately. A slow routing dependency can dominate matching even while the database is lightly loaded. Bound candidate batches and timeouts instead of requesting precise routes for every driver in the city.

06Separate position, availability and trip state

Interfaces

Request or message Contract
POST /rides with request key Creates one rider request despite network retries.
POST /offers/O81/accept with operation key Attempts assignment and returns the saved result on retry.
GET /rides/R501 Recovers authoritative trip state for an authorized participant.

Recover the running trip after reconnect

GET /rides/R501

Assignment result in the worked example

ride:       R501
driver:     D17
assignment: A77
state:      assigned

Stored records

Record Fields or identity Purpose
Position driver, session, sequence, point, receivedAt Latest observation used for approximate discovery and tracking.
Driver id, state, activeRide, version Durable authority over whether the driver may accept work.
Ride id, rider, state, driver, version Durable request and lifecycle.
Offer id, ride, driver, deadline, state Identifies the driver invited to accept, with a bounded lifetime.

Authentication determines the rider or driver; a submitted driver ID is not permission. Reusing a ride-creation key with another pickup must fail rather than silently return an unrelated trip. Retain replay results for a documented retry interval and expose status recovery afterward.

Index rides by rider and driver so reconnect does not require searching all trips. Store assignment A77 and an outbox event in the same transaction. The outbox is durable delivery work; a worker can retry notifying participants without making the assignment again. Connection records merely identify a current socket and may expire independently of the trip.

07Make acceptance atomic on both sides

All competing accepts for a driver and ride must reach records that can commit together in one regional database transaction. In a consistent lock order, lock the driver, the ride and the offer. Recheck a saved operation result after waiting for locks: a concurrent identical request may already have committed A77. Returning that result is correct; rejecting the retry because D17 is now busy is misleading.

For a new operation, perform these steps within the acceptance transaction:

  1. Verify that O81 targets the authenticated driver, is active and has not expired. Check the authoritative database clock after acquiring locks, because the transaction may have waited past the deadline.

  2. Require D17 to be available and R501 to remain offering with no assigned driver.

  3. Insert the assignment, update both rows, mark the offer accepted and store replay and outbox records in one commit.

Unique active-driver and active-ride constraints provide additional protection.

If D17 also accepts R502, that transaction waits for D17 and then sees the assignment to R501. It cannot change R502. If D18 concurrently accepts R501, the ride check rejects that competing driver and leaves D18 available. Protecting only one side misses the other race.

Keep transactions short and handle bounded deadlock or serialization retries. Never hold database locks while waiting for a person to accept an offer or while calling a routing service.

Request traceA second ride cannot take an assigned driver

Both accepts serialize through D17; the losing ride remains unassigned.

A second ride cannot take an assigned driverBoth accepts serialize through D17; the losing ride remains unassigned. a to db: Lock D17; check R501 and offer; b to db: Wait for D17; db to db: Commit D17 ↔ R501 and result; db to a: Assignment A77; db to b: D17 already assigned; no R502 changePARTICIPANTAccept R501PARTICIPANTAccept R502PARTICIPANTRegional database1. Lock D17; check R501 and offer2. Wait for D173. Commit D17 <-> R501 and result4. Assignment A775. D17 already assigned; no R502changesyncreturn
Read each connection in order
  1. syncLock D17; check R501 and offerAccept R501 → Regional database
  2. syncWait for D17Accept R502 → Regional database
  3. syncCommit D17 ↔ R501 and resultRegional database → Regional database
  4. returnAssignment A77Regional database → Accept R501
  5. returnD17 already assigned; no R502 changeRegional database → Accept R502

08Scale approximate location discovery

When coordinate writes burden the assignment database, move latest positions to a partitioned position service. A spatial index maps cells to driver IDs. Every valid update changes the latest point; cell membership needs changing when the driver crosses a boundary, not for every small movement inside the same cell. Fixed or hierarchical cells are adequate before considering a custom adaptive tree.

Updates carry a server-issued session generation and an increasing sequence. Reject older generations and sequence numbers so delayed packets cannot overwrite a newer position. A restarted app gets a new authenticated generation before restarting its sequence numbers. Validate coordinates and observation age, while acknowledging that a phone can still report noisy or dishonest GPS.

The matcher covers the pickup area, retrieves candidate IDs, reads recent points and checks driver availability. It then evaluates a bounded shortlist using pickup suitability and estimated arrival time. A candidate is not a reservation; acceptance still uses the durable transaction.

A stale index can miss a driver who just entered the area. Freshly reading returned positions removes bad candidates but cannot discover an omitted arrival. Define and monitor indexing delay. Expanding the search area is justified only with credible bounds on movement, delay and measurement error; otherwise state that discovery may miss recently arrived drivers.

09Bound offers and preserve regional ownership

A matcher can process ride requests from durable pending-work records once bursts exceed synchronous capacity. It reads current ride state before each offer batch, so canceled or assigned rides do not keep generating offers. Offer a few suitable drivers at a time, set deadlines, and move to another batch after all valid offers fail or expire. Unlimited broadcasting wastes routing calls and interrupts drivers who cannot all win.

Partition independent operating regions to distribute workload, keeping their ride and driver records together. Location cells and transaction ownership serve different purposes. Moving ten meters across a cell edge should not move the driver’s assignment records to another database owner. An active trip can retain its original authority through completion even when it crosses a regional boundary.

If idle drivers must transfer between regions, stop creating new offers, drain or invalidate old offers, and transfer the authoritative record before enabling the new owner. A monotonically increasing ownership version lets the storage path reject commands from the previous owner. Routing alone cannot stop a paused old process from resuming.

Cross-region assignment is therefore an advanced extension, not a free consequence of drawing multiple matchers. It requires a reservation/transfer protocol or a distributed transaction that preserves both sides of the assignment guarantee.

10Recover trips independently of phone connections

After assignment, authorize Maya and D17 to subscribe to R501. A connection directory maps each participant to a gateway, and each location message includes its session and sequence. The gateway can discard intermediate points for a slow phone and retain only the newest observation. Showing the latest position is usually more useful than replaying a minute of obsolete dots.

Trip lifecycle events are different. Assigned, started, canceled and completed transitions must remain recoverable from durable trip state and the outbox. Events carry trip ID and version. The client ignores older versions and fetches current status when a gap or reconnect occurs. A push notification may wake an app, but it is not authoritative proof that a ride remains assigned.

Cancellation races use the same ride and driver authority. If cancellation commits before acceptance, the offer cannot win. If assignment commits first, cancellation follows the assigned-trip policy and clears the ride and driver assignment together when permitted. A temporary socket loss does neither.

Discovery may show coarsened positions to protect drivers. Precise active-trip coordinates require current participant authorization and bounded retention. A new socket must reauthenticate; possession of an old trip ID alone is insufficient to subscribe.

Design diagramRegional assignment with separate position and delivery paths

Maya’s ride request uses recent position candidates and pickup estimates, then the regional database commits the winning ride/driver assignment. Delivery workers read committed notification work and reach phones through gateways. Frequent position updates use the position service; they cannot change durable assignment ownership.

Regional assignment with separate position and delivery pathsMaya’s ride request uses recent position candidates and pickup estimates, then the regional database commits the winning ride/driver assignment. Delivery workers read committed notification work and reach phones through gateways. Frequent position updates use the position service; they cannot change durable assignment ownership. phones to api: Ride and accept requests; phones to positions: Position updates; positions to geo: Update latest position; api to geo: Nearby candidates; api to routes: Pickup estimates; api to db: Offers and assignment; delivery to db: Read committed outbox; delivery to gateways: Offers and trip versions; positions to gateways: Latest trip coordinates; gateways to phones: Authorized live updatesRide and accept requestsPosition updatesUpdate latest positionNearby candidatesPickup estimatesOffers and assignmentRead committed outboxOffers and trip versionsLatest trip coordinatesAuthorized live updatesACTORRider and driverphonesSERVICERegional matchingAPISERVICEPosition serviceSTORELatest-point spatialindexEXTERNALRouting serviceSTORERegional ride / driverDBWORKERDelivery workersSERVICEConnection gatewayssyncasync
Read each connection in order
  1. syncRide and accept requestsRider and driver phones → Regional matching API
  2. asyncPosition updatesRider and driver phones → Position service
  3. asyncUpdate latest positionPosition service → Latest-point spatial index
  4. syncNearby candidatesRegional matching API → Latest-point spatial index
  5. syncPickup estimatesRegional matching API → Routing service
  6. syncOffers and assignmentRegional matching API → Regional ride / driver DB
  7. syncRead committed outboxDelivery workers → Regional ride / driver DB
  8. asyncOffers and trip versionsDelivery workers → Connection gateways
  9. asyncLatest trip coordinatesPosition service → Connection gateways
  10. asyncAuthorized live updatesConnection gateways → Rider and driver phones

11Trace the failures that change the answer

Failure Required behavior
Acceptance commits, response disappears Retry the same operation or offer and return A77; replay notifications.
Process dies before acceptance commit Transaction rolls back; another still-valid offer may win.
Location service loses recent points Drivers republish; discovery temporarily shrinks while trips remain durable.
Regional database loses its primary Promote only a safe replacement that preserves the promised commits and fences the old writer.
Routing service slows down Bound shortlist work, use an explicitly approximate fallback or return a delayed-match outcome.

Use synchronous durable database replication and safe failover to preserve acknowledged assignments across one database-node failure. An asynchronous replica may lose recent commits during promotion; counting three servers is not a durability argument. Stop unsafe writes when the database cannot establish which primary may write rather than create two successful assignments for one driver.

During a station surge, bound waiting demand and expose queue delay. A durable backlog that waits ten minutes does not satisfy a two-second first-offer goal. Rate-limit retries, expire outdated requests and reserve capacity for acceptance and current-trip reads. Reconnecting phones should back off with randomness so a gateway restart does not overload authentication and storage together.

12Observe the user flow and the ownership rules

Monitor position age, discarded old updates, candidate-to-offer ratio, first-offer delay, acceptance commit latency, cancellation outcomes and notification lag. Split measurements by operating region and local density. Global averages hide the airport queue that is currently failing.

Check durable assignment invariants directly: no active driver appears in two assignments, no ride has two winners, and reciprocal driver/ride references agree. Test two rides competing for D17, two drivers competing for R501, cancellation during acceptance, and a lost response immediately after commit. Pause an old regional process during failover and verify that it cannot resume writing.

Protect location data through participant checks, short retention where possible and audited administrative access. Keep raw coordinates out of general request logs. Apply abuse controls to repeated ride creation and offer acceptance without treating a shared mobile network address as a reliable identity.

The main tradeoffs are deliberate: approximate discovery, regional assignment boundaries and latest-only coordinate delivery. The first simplifies high-volume search, the second keeps exclusive assignment understandable, and the third keeps slow clients current. State which requirements would force revisiting each choice instead of adding every possible service immediately.

13Check the design against its requirements

Use the numbered requirements to check the final design. FR refers to the functional list; NFR refers to the non-functional list. Performance rows specify tests still required, not achieved benchmark results.

Requirement Design mechanism Verification and remaining limit
FR1; NFR1–3: timely suitable offers Recent-position search, a bounded routing shortlist and limited offer batches; isolate location writes from assignment storage. Load-test a station surge and slow routing calls. Measure first-offer delay and stale-position rejection; suitable supply is not a guaranteed completed match.
FR2; NFR4: exclusive assignment One transaction checks driver, ride and offer, then stores reciprocal state and the assignment. Race two rides for D17 and two drivers for R501; race acceptance with cancellation. Exactly one permitted transition wins.
FR3–4; NFR6: tracking and reconnect Authorized gateways deliver latest coordinates; durable trip versions and the outbox recover lifecycle events. Drop sockets, reorder locations and reconnect an unauthorized user. Current trip state survives without replaying every obsolete point.
NFR5: durable ownership Synchronous durable database replication, safe promotion and rejection of old writers. Fail the database node after acknowledgment and pause/resume the old writer. Verify A77 remains and no competing assignment can be acknowledged.

14Rapid revision

Remember: GPS finds candidates; one transaction reserves both driver and ride. Protecting only one side permits a double assignment.

Concern Complete interview answer
Ride creation Authenticate the rider; save one ride and result per request key.
Nearby drivers Search cells, load recent points and shortlist available candidates; results remain approximate.
Offer Tie an expiring offer to one driver and ride; limit offers sent at once.
Exclusive acceptance In one transaction, check driver, ride and offer; save both assignments, the retry result and notification work.
Lost response Return the stored assignment; a timeout does not undo commit.
GPS ordering Use the current GPS session and increasing update numbers to reject delayed coordinates.
Scale Scale GPS collection, matching and connections separately; keep the assignment transaction in its designated database.
Reconnect Read the saved current trip, then resume numbered updates; losing a connection does not cancel assignment.
Overload Limit queued work and route calculations so acceptance and recovery still have capacity.

A strong closing answer follows R501 from creation to A77 and reconnect, then names the two acceptance races. Leave pooling, cross-region matching and billing as explicit extensions because they change which records must stay consistent, rather than merely adding traffic.

Practise the interview questions

Say your answer aloud before opening the model answer. Then answer the follow-up and compare the reasoning.

Foundation · Question 1

Why separate driver position from availability?

Reveal a model answer

Position describes an observation; availability is a durable promise about whether the driver can accept work. A fresh heartbeat must not release an active assignment.

What the answer must demonstrate: Separate observed location from authoritative assignment availability.

Applied · Question 2

D17 accepts R501 and R502 concurrently. What prevents two riders winning?

Reveal a model answer

Both transactions lock or conditionally guard the same driver record and atomically update the corresponding ride. The second sees D17 assigned and changes neither side.

What the answer must demonstrate: Protect both driver exclusivity and ride exclusivity in the same transaction.

Applied · Question 3

The acceptance reply is lost. What should the retry return?

Reveal a model answer

The saved assignment for the same authenticated operation or accepted offer. Check that result after lock acquisition so a concurrent duplicate observes the committed winner.

What the answer must demonstrate: Recover the saved assignment after lock acquisition instead of rejecting a successful retry.

Foundation · Question 4

Why include a session generation as well as a sequence?

Reveal a model answer

Sequences order updates within one publishing session. A generation distinguishes a restarted or replacement session and fences delayed packets from the old one.

What the answer must demonstrate: Explain session replacement, sequence ordering and observation-time limits.

Applied · Question 5

Why send only a few offers at a time?

Reveal a model answer

Bounded batches limit driver interruption and expensive routing work. Each batch rechecks that the ride is still eligible.

What the answer must demonstrate: Connect bounded candidate work to driver interruption and matching latency.

Foundation · Question 6

Should a lost socket make a driver available?

Reveal a model answer

No. The current trip is durable. The phone reconnects, authenticates and recovers its assignment; stale location only affects tracking and discovery.

What the answer must demonstrate: Preserve durable trip ownership across socket loss and distinguish coordinate buffering.

Follow-up · Question 7

How does cancellation race with acceptance?

Reveal a model answer

Both use the ride authority. Cancellation first blocks acceptance; assignment first means cancellation follows the assigned-trip policy and releases both references atomically if allowed.

What the answer must demonstrate: Serialize cancellation with acceptance and use committed versions for notifications.

Follow-up · Question 8

Why not change assignment owner on every spatial-cell crossing?

Reveal a model answer

Cells help find nearby drivers. Assignment ownership keeps ride and driver records consistent. Moving those records on every cell crossing would add unnecessary coordination.

What the answer must demonstrate: Distinguish spatial movement from regional assignment-authority transfer.

Blank-page exercise · 45 minutes

Build the answer yourself

Design ride matching for R501, then make D17 accept two rides while the winning response is lost.

  • Agree numbered functional and non-functional requirements, including regional matching, exclusive assignment and position freshness. Then trace ride creation, offer acceptance and trip recovery end to end.
  • Prevent both two rides claiming one driver and two drivers claiming one ride.
  • Scale location ingestion and tracking without weakening assignment ownership.
  • Trace a timeout and a concurrent request using the actual durable records.
  • Review the final architecture against every numbered requirement, including measured bottlenecks, targets still needing validation and remaining failure limits.

Check that each component and design decision follows from your requirements and workload.

Recall the key ideas

Answer from memory before opening each card. Explain why the choice works and what it costs. Revisit missed cards tomorrow.

Design a ride-hailing backendD17 accepts R501 and R502 at once. Which records must the transaction protect?Recall first, then reveal

Lock the driver and the requested ride, check the offer, then save both assignments, the replay result and notification work together. The losing transaction sees D17 already assigned.

One driver and one ride: protect both sides in one commit.

Return to lesson
Design a ride-hailing backendWhat ride information survives a lost connection?Recall first, then reveal

The saved trip and acceptance result; reconnecting clients can recover them.

Connection is not ownership.

Return to lesson
Design a ride-hailing backendWhich updates may delivery skip when keeping only the latest?Recall first, then reveal

Intermediate GPS coordinates. Trip state changes must remain saved and recoverable.

Skip old coordinates; recover every trip state change.

Return to lesson

Final revision

Summary and interview notes

Find nearby drivers, assign each driver to at most one ride, and recover trip state after disconnection. Keep frequent GPS updates separate from saved assignment decisions.

Remember these points

  • Use approximate coordinates for discovery; use committed ride and driver records for assignment.
  • Guard both ride and driver in one transaction.
  • Persist replay and outbox records with assignment.
  • Recover trips from storage rather than connection state.

Interview tips

  • Separate approximate discovery from exclusive assignment.
  • Race D17’s accepts for R501 and R502, then lose the winning reply.

Important qualifications

  • Traffic and latency figures are interview assumptions, not claims about a named company's deployment.

Continue after the core interview

Explore the advanced version

The advanced lesson keeps the full detailed design. Use these sections when you want to examine the stronger requirements and failure cases.

Technical references

Practice marks stay in this browser.