System Design Atlas
LOCAL GUEST MODERead and practice without an account.

Your saved topics and reading progress stay in this browser. Sign in to sync supported profile and progress data.

Ride Matching and Live Tracking (Uber)

Two riders accept offers for the same driver while a cancel arrives.

● HardSystem 1712 min3 prerequisites
My progress
Topic tools

Layout updated

Explore the design, then rehearse the decisions without looking.

Problem statement

Design a ride matching service like Uber. Riders can request a trip, get matched with an available nearby driver, and track that driver on a map.

Functional requirements

  • Request a ride and match an available driver.
  • Accept or cancel offers and update trip status.
  • Show authorized live driver locations.

Non-functional requirements

  • Aim for ride creation under 300 ms; first offer within 2 s.
  • Never assign one driver to two active rides.

Back-of-the-envelope estimates

Illustrative estimate
1M rides/day ≈ 11.6 creates/s; 10× peak ≈ 116/s
500k online drivers, heartbeat/location every 3 seconds ≈ 167k updates/s
200 bytes per fix × 167k/s ≈ 33.4 MB/s ≈ 2.88 TB/day raw
100k active rides × 1 subscriber × one update/3 s ≈ 33k pushes/s
116 creates/s × 20 candidates ≈ 2,320 candidate checks/s
10-minute location backlog at 167k/s ≈ 100M events

Entities

Entity / logical owner
Ride(id, riderId, status, version, driverId); Driver(id, eligibility, activeRideId, version)
Offer(id, rideId, driverId, expiresAt, status); Assignment(id, rideId, driverId, active)
Redis cell index + per-driver liveness/location record
(eventId, aggregateId, version, type, payload); PaymentIntent(rideId, attemptId, status)

API design

Operation / inputResponse and retry contract
POST/rides {requestId, pickup, destination, product}Unique (riderId, requestId), payload hash and stored response in PostgreSQL. Same request returns the same ride; a changed payload with the same key is rejected.
POST/offers/{id}/accept; POST /rides/{id}/cancel; POST /rides/{id}/transitionAuthenticated conditional commands with requestId and expected version. Acceptance checks expiry using database time; every command has a precise commit boundary.
POST/driver-locations or persistent stream {sessionEpoch, seq, lat, lon, capturedAt}Gateway authenticates driver/device and validates coordinate/speed bounds. Kafka keyed by driverId preserves per-partition order; app sessionEpoch + sequence rejects late old-session messages.
SUBSCRIBE /rides/{rideId}/location; GET /rides/{id}Authorize rider/assigned driver, return latest with sequence, then stream updates. PostgreSQL primary is authoritative for membership and transitions; a replica needs read-your-writes handling.

High-level design

How to draw this design

  1. Request a rideRider and Ride
  2. Find and assign driversMatching workers, Redis , and PostgreSQL
  3. Track locationDriver client, location gateway, Kafka, and tracking workers
  4. Publish trip updatesWebSockets, notifications, and payment effects

Find candidates nearby, commit one assignment, then keep the rider updated as positions arrive.

State ownership
PostgreSQL owns rides, drivers, offers, and the . Redis holds current location hints.
Scale
Size the frequently updated location path separately from assignment transactions.
Correctness
Validate the ride, driver, and offer together so a driver cannot be assigned twice.
Failure and recovery
Reconcile uncertain assignments after failover and surface stale positions.
Uber Ride Matching & Live Tracking
G rider->ride 1. Submit request ride->db 2. Persist state db->kafka 3. Publish event kafka->match 4. Consume work match->geo 5. Pass validated input match->db 6. Persist state driver->ride 7. Submit request kafka->effects 8. Consume work effects->driver 9. Pass validated input driver->gateway 10. Submit request gateway->locations 11. Publish event locations->tracking 12. Consume work tracking->geo 13. Pass validated input tracking->ws 14. Pass validated input ws->rider 15. Pass validated input ws->ride 16. Pass validated input rider Rider Client edge ride Ride / Dispatch API compute db PostgreSQL / ONE Business DB state · durable driver Driver Client edge match Matching / Offer Workers compute kafka → Kafka: Ride Events Topic messaging gateway Location Ingest Gateway edge geo Redis GEO / Liveness state · memory effects Notifications / Payment compute locations → Kafka: Driver Location Topic messaging tracking Location / Tracking Workers compute ws Authorized WebSockets edge
  • Edge
  • Compute
  • State
  • Messaging

━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault

Select a component or follow a numbered connection.

Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.

Read the 16 flow steps

High-level design component walkthrough

Client / user

Rider Client

Request ride and track arrival

Why, tradeoff and connected operations

An application or user-facing endpoint starts or receives this flow.

Tradeoff: Retries and stale mobile state

Connected operations: Submit request; Pass validated input

Backend service

Ride / Dispatch API

Authenticate lifecycle commands

Why, tradeoff and connected operations

Isolate this operation so it can scale and fail independently from storage.

Tradeoff: Bound concurrency and retries

Connected operations: Submit request; Persist state; Submit request; Pass validated input

Relational database

PostgreSQL / ONE Business DB

All business tables +

Why, tradeoff and connected operations

PostgreSQL keeps ride, driver assignment and records in one transaction boundary. Conditional updates prevent conflicting assignments. makes related business changes ; the lookup is a separate derived index.

Tradeoff: Single primary write ceiling

Connected operations: Persist state; Publish event; Persist state

Client / user

Driver Client

Accept offers; send sequenced GPS

Why, tradeoff and connected operations

An application or user-facing endpoint starts or receives this flow.

Tradeoff: Disconnects and GPS quality

Connected operations: Submit request; Pass validated input; Submit request

Backend service

Matching / Offer Workers

Rank bounded nearby candidates

Why, tradeoff and connected operations

Isolate this operation so it can scale and fail independently from storage.

Tradeoff: ETA latency and offer contention

Connected operations: Consume work; Pass validated input; Persist state

Queue / event stream

Kafka: Ride Events Topic

Replay committed ride events

Why, tradeoff and connected operations

Kafka retained partitioned stream. Key events by the domain ordering key; replay and independent consumers motivate this choice. rows remain in the source database; a relay publishes after commit. Buffer independent producers and consumers, with bounded and replay semantics.

Tradeoff: Duplicate delivery;

Connected operations: Publish event; Consume work; Consume work

Gateway / routing

Location Ingest Gateway

Validate device and sequence

Why, tradeoff and connected operations

Centralize admission and routing while keeping business-state ownership downstream.

Tradeoff: High-rate connections and load

Connected operations: Submit request; Publish event

Cache / in-memory index

Redis GEO / Liveness

Nearby hints and latest position

Why, tradeoff and connected operations

Redis and expiring liveness entries quickly find nearby available-driver candidates. Frequent position updates stay out of the business transaction tables. Redis provides approximate candidates; PostgreSQL still decides the final assignment.

Tradeoff: Stale membership; rebuildable

Connected operations: Pass validated input; Pass validated input

Backend service

Notifications / Payment

Idempotent external effects

Why, tradeoff and connected operations

Isolate this operation so it can scale and fail independently from storage.

Tradeoff: Provider failures; delayed notices

Connected operations: Consume work; Pass validated input

Queue / event stream

Kafka: Driver Location Topic

Ordered driver partitions

Why, tradeoff and connected operations

Kafka retained partitioned stream. Key events by the domain ordering key; replay and independent consumers motivate this choice. rows remain in the source database; a relay publishes after commit. Buffer independent producers and consumers, with bounded and replay semantics.

Tradeoff: Backlog and raw GPS cost

Connected operations: Publish event; Consume work

Stream / batch processing

Location / Tracking Workers

Sequence guard and coalescing

Why, tradeoff and connected operations

Compute derived state away from request handlers; checkpoints and govern recovery.

Tradeoff: Intermediate positions may drop

Connected operations: Consume work; Pass validated input; Pass validated input

Gateway / routing

Authorized WebSockets

plus live ride updates

Why, tradeoff and connected operations

Centralize admission and routing while keeping business-state ownership downstream.

Tradeoff: Slow sockets and reconnect storms

Connected operations: Pass validated input; Pass validated input; Pass validated input

Engineering control room

Deep dives — decisions, failures and recovery

Open a deep dive to follow the steps, try an example and see how recovery works.

Deep dive 1

Choose one driver assignment in PostgreSQL

Check the ride, driver and offer and commit one assignment together.

Read the explanation and worked example
How it works

Treat Redis nearby-driver results as candidates. In one PostgreSQL transaction, lock or conditionally validate the ride, driver and offer in a consistent order, check expiry and status, and write the assignment plus event. Database constraints defend against two active assignments.

Walk through an example

Two riders accept offers involving the same driver. Both may have seen the driver as available in Redis, but only one business transaction can commit the valid assignment.

Failure and recovery

The losing request receives the recorded conflict or current ride state. If the winner loses its response, the same command identity returns the original assignment; it must not search for a second driver automatically.

Why this helps

Nearby-driver results can be stale. A Redis lock does not prevent a permanent double assignment after it expires or fails over.

What you give up

Constraints and a consistent lock order settle races. Reusing a request identity lets a client learn the winning result after losing the response.

Deep dive 2

Do not let old locations move the car backward

Accept only newer fixes from the current driver session.

Read the explanation and worked example
How it works

Each driver connection carries a session and increasing location sequence. Keep only a newer valid fix for that session, and use a short liveness expiry. Tracking workers can combine intermediate fixes so a slow subscriber sees the latest useful position instead of every stale point.

Walk through an example

A driver's phone reconnects and an old buffered location arrives after the new session has already moved. Comparing only arrival time could teleport the map marker backward.

Failure and recovery

Reject old-session or regressing fixes, expose stale-location age and let reconnect fetch the latest authorized . A missing heartbeat affects discovery, but must not implicitly cancel the durable ride assignment.

Why this helps

Delayed packets can arrive after a reconnect and otherwise overwrite the latest position.

What you give up

Rebuild Redis from fresh updates and show location age. An old map point does not cancel or change the durable trip assignment.

Deep dive 3

Keep business changes in one transaction

Store ride, driver, offer and payment-intent tables in one PostgreSQL database.

Read the explanation and worked example
How it works

Keep rides, driver eligibility, offers, payment intent and business tables inside one transactional PostgreSQL authority. Services may have different APIs and worker pools without requiring separate business databases. Sharding comes later around a boundary whose transactions can actually remain local.

Walk through an example

Separating offers and assignments into independent databases would make accepting an offer a distributed race that the original single transaction could resolve directly.

Failure and recovery

Use read replicas and derived stores for non-authoritative views. Fence regional writer promotion, reconcile uncertain assignments before reopening discovery, and state the recovery point implied by replication rather than promising lossless failover by default.

Why this helps

Different service APIs do not require different databases. Splitting these tables would make assignment harder to commit safely.

What you give up

Regional failover must stop the previous writer and check uncertain assignments before matching resumes. That coordination can temporarily delay new rides.

Deep dive 4

What happens if a region fails?

Check existing assignments before the recovery database offers drivers again.

Read the explanation and worked example
How it works

Business writes stay in the one PostgreSQL transaction authority while regional gateways and Redis serve local discovery/tracking. Promote a remote database only after the old primary and understanding which assignments may not have replicated.

Walk through an example

A stale standby marks an already assigned driver available after the primary region fails.

Failure and recovery

Pause affected matching, reconcile active rides and uncertain commands, and rebuild Redis from fresh location sessions plus authoritative driver eligibility. Resume dispatch only after assignment safety is established.

Why this helps

A fast location path must not turn regional failover into two ride-assignment authorities.

What you give up

The single business database simplifies assignment but can add distant-write latency; stronger remote durability costs more coordination.

Deep dive 5

Stale offers, expiry and cancellation races

An offer is a conditional proposal, not an assignment that exists until Redis removes it.

Read the explanation and worked example
How it works

Store offer identity, driver/ride versions and expiry in the business database. Acceptance, expiry and cancellation must compare expected state under the same transaction authority. Cleanup and notification workers carry IDs/versions, never unconditional instructions to overwrite current state.

Walk through an example

An offer times out, a new offer is created, and the driver's delayed accept for the old offer arrives.

Failure and recovery

Reject the expired identity, return authoritative ride state and publish only committed transitions. Retried cleanup must not free a driver already assigned by a newer command.

Why this helps

Fresh nearby-driver discovery cannot protect against delayed business commands.

What you give up

Longer offers improve response opportunity but hold resources and increase stale-accept ambiguity; shorter expiry raises retry and matching work.

Additional technical detail

1 · Requirements and consistency contract

Design ride request, nearby-driver discovery, offer/acceptance, cancellation, trip lifecycle and live driver tracking. One rider receives at most one active ride; one driver is committed to at most one active ride. Provide approximate pickup ETA and a map that updates within a few seconds. Exclude pooled rides, global dispatch optimization and detailed pricing algorithms. Payment is a stateful integration, not the focus of matching.

Use one transactional PostgreSQL database for all business tables: riders, drivers, rides, offers, assignments, payment intents, records and . Services own operations, not separate physical databases. Redis owns disposable /liveness projections; Kafka carries durable events and location streams. This follows the requested architecture; the accessible prep-chat excerpt did not expose the earlier Uber walkthrough. Numbers below are proposed assumptions, not Uber production data.

  • Targets: ride creation below 300 ms regionally, first offer within 2 seconds, and location age below 5 seconds in healthy conditions. Human acceptance takes longer and is measured separately. Aim for 99.95% ride availability; protect assignment correctness during partitions.
  • Strong state: assignment, cancellation and trip transitions serialize in PostgreSQL. Soft state: nearby results, ETA and map positions may be stale. Revalidate eligibility before committing an assignment.
  • Interview pacing: clarify 5 min; scale/model 5; 10; assignment and tracking 15; failure/regions 7; final summary 3. Explain decision, reason and tradeoff, then stop.

2 · Scale and boundaries

Assumption / calculationDesign implication
1M rides/day ≈ 11.6 creates/s; 10× peak ≈ 116/sA single well-provisioned PostgreSQL primary is a reasonable starting hypothesis. Benchmark lifecycle writes, index contention and failover headroom rather than assuming unlimited capacity.
500k online drivers, heartbeat/location every 3 seconds ≈ 167k updates/sKeep per-fix location updates outside PostgreSQL. Kafka partitions and Redis city/cell indexes carry this stream.
200 bytes per fix × 167k/s ≈ 33.4 MB/s ≈ 2.88 TB/day rawReplication, protocol overhead and add cost. Retain raw GPS briefly, downsample historical tracks and apply privacy policy.
100k active rides × 1 subscriber × one update/3 s ≈ 33k pushes/sWebSocket gateways scale on connection count, TLS, buffers and . Extra observers multiply delivery.
116 creates/s × 20 candidates ≈ 2,320 candidate checks/sBound radius and candidate count. Road-ETA calls need a concurrency budget and fallback ranking.
10-minute location backlog at 167k/s ≈ 100M eventsAt 250k/s recovery rate, net drain 83k/s takes about 20 minutes. Latest-position serving should skip obsolete backlog while archival consumes separately.

3 · APIs, entities and data stores

/ table or streamKey and guarantee
POST /rides {requestId, pickup, destination, product}Unique (riderId, requestId), payload hash and stored response in PostgreSQL. Same request returns the same ride; a changed payload with the same key is rejected.
Ride(id, riderId, status, version, driverId); Driver(id, eligibility, activeRideId, version)Shared PostgreSQL transaction domain. Trip states: REQUESTED → MATCHING → ASSIGNED → ARRIVING → IN_PROGRESS → COMPLETED; cancellation follows explicit permitted transitions.
Offer(id, rideId, driverId, expiresAt, status); Assignment(id, rideId, driverId, active)Offers are expiring invitations, not completed assignments. Partial unique indexes enforce at most one active Assignment per driver and per ride. A rider guard/partial unique active-ride index prevents duplicate active rides.
POST /offers/{id}/accept; POST /rides/{id}/cancel; POST /rides/{id}/transitionAuthenticated conditional commands with requestId and expected version. Acceptance checks expiry using database time; every command has a precise commit boundary.
POST /driver-locations or persistent stream {sessionEpoch, seq, lat, lon, capturedAt}Gateway authenticates driver/device and validates coordinate/speed bounds. Kafka keyed by driverId preserves per-partition order; app sessionEpoch + sequence rejects late old-session messages.
Redis cell index + per-driver liveness/location recordQuery nearby candidates with GEOSEARCH and bounded neighboring-cell . Check lastSeen and eligibility hints. members do not each gain a from expiring the whole set; use separate records plus a stale-member sweeper.
SUBSCRIBE /rides/{rideId}/location; GET /rides/{id}Authorize rider/assigned driver, return latest with sequence, then stream updates. PostgreSQL primary is authoritative for membership and transitions; a replica needs read-your-writes handling.
(eventId, aggregateId, version, type, payload); PaymentIntent(rideId, attemptId, status)Same PostgreSQL transaction as business changes. /relay to Kafka is at least once. Payment provider calls use durable keys and outside the DB transaction.

4 · Deep dive 1 — Discovery, offers and atomic assignment

On ride creation, PostgreSQL commits the request and matching intent together. The matching worker reads a bounded set of nearby Redis cells, excludes stale/offline candidates, ranks by approximate distance and a bounded number of road-ETA calls, then persists offers and notification intents in PostgreSQL. Start with sequential offers or a small parallel batch; broad lowers matching delay but annoys drivers and raises contention.

Acceptance uses one short transaction, without network calls under row locks. All lifecycle commands follow the same documented lock order: rider guard if needed, ride row, then driver rows in sorted ID order, then offer/assignment rows. After obtaining locks, reread status/version and offer expiry; do not trust values read before the lock. Cancel, expire and accept must all follow this protocol.

  1. Authenticate the accepting driver; resolve the durable record. Lock the ride and driver, then offer. Verify ride is MATCHING, offer belongs to that driver and ride, offer is unexpired, driver is eligible and activeRideId is null.
  2. Insert active Assignment. Unique constraints on active rideId and active driverId are a final guard against conflicting code paths. Conditional updates change ride to ASSIGNED and Driver.activeRideId to this ride; require the expected affected-row counts.
  3. Mark the winning offer accepted, invalidate other offers for the ride, increment business versions, and insert RideAssigned plus response/ state in the same transaction. Commit before reporting success.
  4. A losing accept returns a stable conflict or already-resolved result. If the connection dies after COMMIT, retry the same requestId and read the durable result. Retry deadlocks/serialization errors with bounded backoff, never an unbounded tight loop.

Race proof: two rides competing for one driver serialize on the driver row; only the first sees no active ride. Two drivers accepting one ride serialize on its row. Cancel racing accept serializes on the ride: if cancel wins, accept fails; if accept wins, cancellation uses the assigned-ride policy and clears the driver/assignment transactionally when allowed. Offer expiry cannot release a completed assignment because expiry checks offer state/version under lock.

Tradeoff: database transactions provide a simple invariant at the cost of contention and a primary-write ceiling. Redis locks are unnecessary for correctness and must not become a second assignment authority. A stale result may waste an offer, but cannot double-book a driver. See PostgreSQL row locks and partial unique indexes for the underlying mechanisms.

5 · Deep dive 2 — Geo partitioning and live tracking

Route updates through a driver-authenticated gateway into Kafka, then location workers update Redis and a tracking channel. State includes server-issued sessionEpoch, monotonic sequence and lastSeen; compare /sequence atomically per driver. Reject older packets even if they arrive later. Device timestamps help diagnose staleness but are not trusted ordering authorities.

  • scale: partition by city and spatial cell, split hot airport/downtown cells and query adjacent cells near boundaries. Cap expansion radius, candidates and ETA calls. Hashing driverId alone distributes writes but cannot directly answer neighborhood queries.
  • Cell moves: add the new-cell membership and remove the old one; cross- moves are not assumed . Temporary duplicates are deduplicated by driverId; canonical latest-location sequence filters obsolete membership. /sweeping repairs missing removals. Discovery is approximate, assignment is authoritative.
  • Liveness: use a separate /lastSeen record and filter every candidate; rebuild Redis from fresh heartbeats/latest stream state after loss. Do not replay hours of old locations as fresh online status. Background removal bounds memory growth. Redis GEOSEARCH supplies the neighborhood primitive, not assignment atomicity.
  • Tracking: gateways subscribe only for authorized active rides. Subscribe/buffer first, fetch a with sequence, then emit newer buffered updates; sequence dedup closes the /live race. Reconnect fetches the latest state rather than every historical map point.
  • : pending positions per driver/ride and drop intermediate map points for slow clients; never drop business transitions. Show last update time and stop implying motion when data is stale. GPS spoofing and jumps trigger validation, not automatic reassignment.

Recovery/tradeoff: losing intermediate locations is acceptable for a live map; losing an assignment is not. Raw archival and latest-location serving use independent consumer groups so long archive recovery does not delay current tracking. Bound queues, idle sockets and reconnect concurrency.

6 · Deep dive 3 — Outbox, trip lifecycle and external effects

PostgreSQL is the only business source of truth. A transition transaction writes both the new ride state and an event. The relay publishes committed rows to Kafka and marks progress after publication; a crash between publish and progress causes a duplicate. Consumers use eventId and aggregate version, apply idempotent effects, and repair version gaps from authoritative state.

Notifications include offer ID, expiry and version. The client may receive an obsolete offer after another driver wins; acceptance still consults PostgreSQL. Kafka partitioning by rideId preserves that stream's local ordering, but does not order every driver and ride globally. Never infer assignment truth from whether a push notification arrived.

On completion, atomically finalize the trip, deactivate its Assignment, clear Driver.activeRideId only if it still refers to that ride, and create a PaymentIntent/ event. A payment worker calls the provider with a stable key, records the result and reconciles unknown outcomes. Do not hold a database transaction during a payment call. Payment failure enters a durable retry/debt state; it must not resurrect an old active ride.

Tradeoff: asynchronous effects may lag while business state is correct. Recovery: scan old matching requests, expired offers and undelivered rows with bounded batches and conditional updates. Kafka loss can be repaired from retained business/ data; must exceed the supported replay window. Do not delete dedup records before supported clients can stop retrying.

7 · Deep dive 4 — Failure domains and multi-region

The baseline is one PostgreSQL business database with a primary and synchronous standby, plus remote disaster-recovery replicas. Redis and stateless gateways can be regional; business writes route to the primary. This keeps the requested single transaction domain and accepts WAN latency for distant markets. Read replicas serve history, while assignment and post-commit state checks use primary or a verified commit .

Async remote replication has nonzero . After a region is isolated, fence the old primary before promotion. If replication may have lost assignments, pause affected matching and reconcile active rides/drivers; a stale standby that marks a busy driver free cannot safely resume dispatch. A / orchestrator is useful only if the old writer is actually prevented from committing. Clients reconnect, read authoritative ride state and rebuild Redis liveness.

If the interview requires global low-latency writes at much larger scale, explicitly revisit the one-database constraint: independent market databases or distributed are alternatives, not hidden assumptions in this design. Cross-market driver transfer would require draining active work and transferring ownership. If zero regional is required while retaining PostgreSQL, synchronous remote commit adds WAN latency and can block writes on link loss. State the chosen availability tradeoff.

8 · Failure table, operations and security

Failure / pressure testRecovery and evidence
Worker dies after offer creation or assignment commitDurable relays later; client retry reads original request result. Watch oldest row and unmatched-request age.
Redis disappears or holds an assigned driverRebuild only from fresh location/liveness; PostgreSQL eligibility recheck protects assignments. Reduce matching radius/rate while discovery recovers.
Kafka unavailableExisting committed trips remain valid; buffers transitions. Location freshness degrades explicitly. Admission control before /disk exhaustion.
Two accepts, cancel and expiry raceRow-lock protocol, status/version checks and unique constraints decide one outcome. Alert on unexpected constraint errors and lock wait percentiles.
Tracking gateway or network failsJittered reconnect, authorize again, + sequence, bounded buffers. Display stale location; no implicit trip cancellation.
Primary/region lostFence writer, establish safe committed state, promote or pause; reconcile before exposing free-driver state. Measure , replication lag and uncertain assignments.

Measure create-to-offer and offer-to-accept latency, candidates per match, stale candidate rejection, lock contention, lag, location age, gateway buffer drops, ETA error and unassigned-rider rate. Authorize every ride subscription and transition; do not reveal arbitrary drivers' precise locations. Limit , encrypt GPS, audit support access and rate-limit fake ride requests. Roll out schema changes expand/backfill/contract; version events and keep old consumers compatible.

9 · Final architecture and repeat queue

I use one PostgreSQL database for all business state and a short transaction to bind a ride and driver atomically. Redis and liveness find plausible candidates; they never decide ownership. Offers expire in durable state, and acceptance, cancellation and completion serialize through consistent row locks and unique active-assignment constraints. The same transaction writes an , which feeds Kafka and idempotent notifications/payment workers. High-rate GPS travels through a separate location stream into Redis and authorized WebSocket tracking, with sequence guards and coalescing. On regional failover I fence the old writer and establish safe assignment state before resuming dispatch. I relax map freshness, not double-booking safety.

Tradeoffs and alternatives

DecisionTradeoff / alternative and recovery implication
Choose one driver assignment in PostgreSQLConstraints and a consistent lock order settle races. Reusing a request identity lets a client learn the winning result after losing the response.
Do not let old locations move the car backwardRebuild Redis from fresh updates and show location age. An old map point does not cancel or change the durable trip assignment.
Keep business changes in one transactionRegional failover must stop the previous writer and check uncertain assignments before matching resumes. That coordination can temporarily delay new rides.
What happens if a region fails?The single business database simplifies assignment but can add distant-write latency; stronger remote durability costs more coordination.
Stale offers, expiry and cancellation racesLonger offers improve response opportunity but hold resources and increase stale-accept ambiguity; shorter expiry raises retry and matching work.

Production scars & failure modes

Failure investigation

Two riders accept offers for the same driver while a cancel arrives.

Look for: Trace ride/driver versions, active-assignment constraints and command identity.

Recovery and invariant: Lock and conditionally transition the business rows in one transaction; constraints choose one outcome. Retry returns the original result rather than issuing another assignment.

Component / failureRequired behavior / recoveryOperational implication
Worker dies after offer creation or assignment commitDurable relays later; client retry reads original request result.Watch oldest row and unmatched-request age.
Redis disappears or holds an assigned driverRebuild only from fresh location/liveness; PostgreSQL eligibility recheck protects assignments.Reduce matching radius/rate while discovery recovers.
Kafka unavailableExisting committed trips remain valid; buffers transitions.Location freshness degrades explicitly Admission control before /disk exhaustion.
Two accepts, cancel and expiry raceRow-lock protocol, status/version checks and unique constraints decide one outcome.Alert on unexpected constraint errors and lock wait percentiles.
Tracking gateway or network failsJittered reconnect, authorize again, + sequence, bounded buffers.Display stale location; no implicit trip cancellation.
Primary/region lostFence writer, establish safe committed state, promote or pause; reconcile before exposing free-driver state.Measure , replication lag and uncertain assignments.

90-second interview summary

I would separate transactional ride ownership from high-rate location tracking. Rider requests enter a dispatch . Redis and liveness find nearby candidates, but PostgreSQL decides whether a driver is actually eligible and whether a ride can be assigned.

Accepting an offer is one transaction across ride, driver and offer rows in the same PostgreSQL business database. It checks expected versions and expiry, commits one assignment and records intent. Constraints prevent two active assignments, and a lost response is resolved by the same command identity.

Driver locations use a session and sequence so late data cannot overwrite a newer session. Kafka and tracking workers distribute authorized, coalesced map updates through WebSockets. Missing heartbeats can remove a driver from discovery without silently cancelling an existing ride.

I would keep business writes at one fenced authority and allow regional gateways, read views and soft location state. After database promotion, uncertain assignments are reconciled before matching resumes; a stale replica must not declare busy drivers free. I would monitor matching delay, conflicts, age and location freshness. The tradeoff is a simple business boundary with explicit failover coordination, while the much larger tracking stream accepts bounded staleness and dropped intermediate points.

Explain it without looking

Explain choose one driver assignment in postgresql

Reveal answer

Check the ride, driver and offer and commit one assignment together.

Nearby-driver results can be stale. A Redis lock does not prevent a permanent double assignment after it expires or fails over.

Constraints and a consistent lock order settle races. Reusing a request identity lets a client learn the winning result after losing the response.

Explain do not let old locations move the car backward

Reveal answer

Accept only newer fixes from the current driver session.

Delayed packets can arrive after a reconnect and otherwise overwrite the latest position.

Rebuild Redis from fresh updates and show location age. An old map point does not cancel or change the durable trip assignment.

Explain keep business changes in one transaction

Reveal answer

Store ride, driver, offer and payment-intent tables in one PostgreSQL database.

Different service APIs do not require different databases. Splitting these tables would make assignment harder to commit safely.

Regional failover must stop the previous writer and check uncertain assignments before matching resumes. That coordination can temporarily delay new rides.

Explain what happens if a region fails?

Reveal answer

Check existing assignments before the recovery database offers drivers again.

A fast location path must not turn regional failover into two ride-assignment authorities.

The single business database simplifies assignment but can add distant-write latency; stronger remote durability costs more coordination.

Explain stale offers, expiry and cancellation races

Reveal answer

An offer is a conditional proposal, not an assignment that exists until Redis removes it.

Fresh nearby-driver discovery cannot protect against delayed business commands.

Longer offers improve response opportunity but hold resources and increase stale-accept ambiguity; shorter expiry raises retry and matching work.

Revision checklist

Revision checklist

  • Reconstruct choose one driver assignment in postgresql: Check the ride, driver and offer and commit one assignment together.
  • Reconstruct do not let old locations move the car backward: Accept only newer fixes from the current driver session.
  • Reconstruct keep business changes in one transaction: Store ride, driver, offer and payment-intent tables in one PostgreSQL database.
  • Reconstruct what happens if a region fails?: Check existing assignments before the recovery database offers drivers again.
  • Reconstruct stale offers, expiry and cancellation races: An offer is a conditional proposal, not an assignment that exists until Redis removes it.
  • Name the authoritative state, boundary, retry identity and failure-domain durability guarantee.
  • Explain one alternative and exactly which guarantee you would relax.
  • Redraw the request and recovery paths without looking; mark what required a hint.

60-minute interview outline

60-minute interview walkthrough

TimeFocusWhat to cover
0–5 minIntroductionsIntroduce yourself briefly and confirm the interview format.
5–15 minScope and scaleScope request, matching, acceptance, and location tracking. Size driver updates separately from ride transactions.
15–30 minHigh-level designDraw Redis nearby-driver discovery, the PostgreSQL assignment transaction, and the Kafka location path to the rider.
30–45 minDeep divesExplain how competing offers resolve to one assignment. Define how stale location updates are discarded.
45–55 minFailure and recoveryWalk through an uncertain assignment after failover or delayed tracking. Keep ownership checks authoritative and surface stale locations.
55–60 minWrap-upSummarize the design and its main tradeoff. Leave time for questions.
On this page
  1. Problem statement
  2. Functional requirements
  3. Non-functional requirements
  4. Back-of-the-envelope estimates
  5. Entities
  6. API design
  7. High-level design
  8. High-level design component walkthrough
  9. Engineering control room
  10. Deep dives — decisions, failures and recovery
  11. Tradeoffs and alternatives
  12. Production scars & failure modes
  13. 90-second interview summary
  14. Explain it without looking
  15. Revision checklist
  16. 60-minute interview walkthrough

Save & sync your Atlas progress

Sync your profile and topic progress across browsers, then return to the same study desk.

Google sign-in will appear here after its Azure provider is configured.

Architecture diagram