Skip to main content

Scenario: Uber Ride Matching

Diagram convention: Arrows and messages are labeled 1, 2, 3… to show processing order. Each diagram is followed by a Step-by-step flow table explaining every numbered step.

1. The Interview Question​

"Design the ride-matching system for a city with 100K active drivers and 50K concurrent ride requests at peak. Match riders to drivers within 30 seconds."

2. Real-World Context​

DimensionDetail
Company / systemUber — real-time marketplace; geospatial indexing + dispatch
ScaleMillions of trips/day; sub-second location updates; 100K drivers × 1 update/5s = 20K location writes/sec per city
Why architects careCombines real-time geospatial data (EL), atomic trip assignment (EC), and hot-cell mitigation at airports/events
Public referencesUber engineering blog (dispatch, geospatial); H3 hexagonal indexing

AWS deployment context​

Typical Uber-style dispatch on AWS: API Gateway + ECS Fargate dispatch service; Amazon Kinesis for driver location stream; ElastiCache Redis with H3 cell indexing for geospatial queries; Amazon DynamoDB for trip state machine (conditional writes); Amazon SNS + Pinpoint for driver push offers; Amazon Location Service or own ETA graph for road-network refinement; CloudWatch for match latency SLOs.

Step-by-step flow:

StepActionExplanation
1Request rideRider submits pickup/dropoff via POST /trips.
2GPS streamDriver app sends location every 3–5s to Kinesis.
3Update indexLocation indexer consumes stream shards.
4H3 cell writeDriver position stored in Redis keyed by H3 cell ID.
5Create tripDispatch API creates trip in REQUESTED state.
6Query nearbyMatching engine searches expanding H3 k-ring.
7k-ring lookupRedis returns available drivers in surrounding cells.
8Atomic assignConditional write assigns driver — prevents double-booking.
9Offer pushSNS sends trip offer to driver app.

3. Step-by-Step Interview Answer (60 min)​

Minutes 0–8: Requirements​

TypeDetail
FRRequest ride; match driver; track trip; complete payment
NFRp99 match < 30s; 99.9% availability; driver location freshness < 5s
Non-goalsGlobal cross-city matching; autonomous routing; surge pricing (unless time permits)

Clarify: One city scope; partition by city boundary for multi-region.

Step-by-step flow:

StepActionExplanation
1Match SLOp99 < 30s from request to driver accept.
2Atomic assignSame driver never assigned to two active trips.
3Location ELDriver positions may be 1–2s stale — acceptable for matching.
4AvailabilityDispatch must survive AZ failure; city-boundary partition.

Minutes 8–20: High-level architecture​

Step-by-step flow:

StepActionExplanation
1RequestRider creates trip with pickup coordinates.
2GPS streamDriver locations ingested continuously.
3IndexH3 cell index updated in Redis.
4MatchMatching engine scores candidates.
5QueryExpanding k-ring search around rider pickup.
6AssignAtomic conditional write on trip + driver lock.
7NotifyPush offer to top-ranked driver.
8PaymentTrip completion triggers payment (out of scope for matching).

Component responsibilities:

ComponentResponsibilityConsistency
Location pipelineIngest GPS → update geo indexEL — 1–2s staleness OK
Geospatial indexH3 cells; shard by cityEL — eventual
Matching engineScore + rank driversReads stale locations OK
Trip storeState machine + assignmentEC — conditional writes
NotificationDriver offer pushAt-least-once

Minutes 20–40: Deep dives​

Geospatial — H3 indexing:

Step-by-step flow:

StepActionExplanation
1LatLng to H3Convert pickup to H3 cell at resolution 8 (~0.5 km²).
2k-ring k=1Search rider cell + 6 immediate neighbors.
3Expand radiusIf no available drivers, expand k-ring to k=2, 3… up to 30s timeout.
4Redis lookupSMEMBERS h3:cell:{id}:drivers — O(1) per cell.
5ETA refineFilter by road-network ETA (not straight-line distance).

Matching algorithm — sequential offer:

Step-by-step flow:

StepActionExplanation
1POST /tripsRider requests ride.
2Create tripPersist REQUESTED state in DynamoDB.
3Find driversMatching engine invoked asynchronously or inline.
4–5H3 queryRetrieve candidate driver IDs from geo index.
6ScoreRank by ETA (60%), rating (25%), vehicle type (15%).
7–8Conditional assigndriver_status=idle condition — atomic lock.
9Push offerDriver has 15s to accept.
10a–11aAcceptTrip transitions to MATCHED.
10b–11bRejectRelease driver; offer next candidate.

Atomic assignment — prevent double-booking:

# DynamoDB conditional write — trip assignment
dynamodb.update_item(
TableName="Trips",
Key={"trip_id": trip_id},
UpdateExpression="SET driver_id = :d, #s = :matched, version = version + 1",
ConditionExpression="attribute_not_exists(driver_id) AND #s = :requested",
ExpressionAttributeNames={"#s": "status"},
ExpressionAttributeValues={
":d": driver_id,
":matched": "MATCHED",
":requested": "REQUESTED",
},
)

# Separate driver lock table
dynamodb.update_item(
TableName="DriverLocks",
Key={"driver_id": driver_id},
UpdateExpression="SET trip_id = :t, locked_at = :now",
ConditionExpression="attribute_not_exists(trip_id)",
ExpressionAttributeValues={":t": trip_id, ":now": now()},
)

Hot spots — airport surge:

Step-by-step flow:

StepActionExplanation
1High density500 concurrent requests in single H3 cell (airport).
2Rate limitCap matching QPS per cell — prevent Redis overload.
3QueueBuffer requests in SQS; process in batches.
4Batch matchGreedy or auction matching every 2s for efficiency.

Minutes 40–55: Scale numbers​

MetricEstimateCalculation
Location updates20K writes/s100K drivers ÷ 5s
Ride requests peak~85/s5K/min
Kinesis shards20+20K records/s ÷ 1K/shard
Redis memory per city~500 MB100K drivers × 5 KB/driver state
DynamoDB trips1M trips/day2 KB × 1M ≈ 2 GB/day
Match latency targetp99 < 30sExpand k-ring until match or timeout

Minutes 55–60: Evolution​

PhaseScopeKey change
1Single cityBatch matching every 2s; polling geo index
2Real-timeKinesis stream; sequential offer; ML ETA
3Multi-regionCity-boundary partition; no cross-city matching

4. Whiteboard Guide​

  1. Left: Rider + Driver apps
  2. Center-top: Kinesis → Location indexer → Redis H3 index (label EL)
  3. Center-bottom: Dispatch API → Matching engine → DynamoDB trips (label EC)
  4. Right: SNS push to driver
  5. Shade airport cell red — hot spot mitigation
  6. Draw conditional write arrow on trip assignment

AWS whiteboard layout​

Step-by-step flow:

StepActionExplanation
1Location pathHigh-volume EL writes to geo index.
2Match pathEC assignment on trip + driver lock.
3NotifyPush offer after successful assign.

5. Principal-Level Signals​

  • Atomic driver assignment — conditional writes; never assign same driver twice
  • Separates location freshness (EL) from trip consistency (EC) — PACELC framing
  • H3 vs quadtree — H3 uniform cells; quadtree variable depth; H3 preferred at Uber scale
  • Hot-cell mitigation — per-cell rate limit + batch matching at airports
  • Expanding radius — k-ring search with 30s timeout; surge signal if no drivers
  • Sequential vs batch offer — sequential simpler; batch auction better for dense hotspots

6. Red Flags​

  • Assign driver without conditional write — race condition double-booking
  • Strong consistency on location index — unnecessary; kills throughput
  • Global matching across cities — latency + complexity; partition by city
  • Straight-line distance only — ignore road network ETA
  • No driver release on reject/timeout — driver stuck "busy" forever

7. Follow-Up Questions​

QuestionStrong answer
Driver location stale 5s?OK for matching — EL; trip assign uses EC lock at match time
Two riders same driver?Conditional write on DriverLocks — second assign fails
Airport 500 requests/cell?Per-cell SQS queue + batch auction every 2s
H3 resolution?res-8 for city blocks (~460m edge); res-9 for dense urban
Driver goes offline mid-offer?Offer timeout 15s → release lock → next candidate

9. Practice Drill​

60-minute timed whiteboard with numbered steps 1–9 on match sequence. Self-score: requirements (10), diagram (15), deep dive (20), failures (10), numbers (5).


10. Production High-Level Design​

10.1 Architecture diagram index​

SectionTopic
§2End-to-end AWS deployment
§3Core component flow
§10.2C4 logical context
§10.3Full VPC stack
§10.4Trip lifecycle states
§11.4Match sequence
§11.5Kinesis → Redis pipeline
§12Multi-AZ + city boundaries
§13Metrics and alerts
§148-week rollout
§15Load + race condition tests
§16Production readiness

10.2 System context (C4 Level 1)​

Step-by-step flow:

StepActionExplanation
1Request tripRider submits pickup/dropoff.
2GPS updatesDriver stream at 3–5s interval.
3Index positionUpdate H3 cell membership in Redis.
4Create tripPersist REQUESTED in trip store.
5Query driversk-ring search in geo index.
6ETA scoringRoad-network ETA for top candidates.
7AssignAtomic write; push notification.

10.3 AWS production architecture​

Step-by-step flow:

StepActionExplanation
1API ingressWAF + API Gateway → ALB → Dispatch API.
2Location streamDriver GPS → Kinesis (partitioned by driver_id).
3Index updateLocation indexer writes to Redis H3 cells.
4Match flowMatcher queries Redis, assigns in DynamoDB.
5PushSNS delivers offer to driver device endpoint.
AWS componentResponsibility
KinesisDurable location stream; 20+ shards at 20K/s
ElastiCache RedisH3 cell → driver set; sub-ms lookups
DynamoDBTrip state machine; conditional assignment
ECS FargateStateless dispatch + matcher; auto-scale on queue depth
SNSMobile push for trip offers
CloudWatchmatch_latency_p99, unmatched_trips, driver_lock_conflicts

10.4 Trip state machine​

Step-by-step flow:

StepActionExplanation
1REQUESTEDTrip created; matching begins.
2OFFEREDDriver received push; 15s to respond.
3MATCHEDDriver accepted; rider notified.
4Re-offerRelease driver lock; try next candidate.
5–6TerminalCancel or no drivers found.
7–8Active tripPickup → dropoff → payment.

11. Production Low-Level Design​

11.1 API contract​

Endpoint: POST /v1/trips

{
"rider_id": "R123",
"pickup": {"lat": 37.7749, "lng": -122.4194},
"dropoff": {"lat": 37.7849, "lng": -122.4094},
"vehicle_type": "uberx",
"idempotency_key": "req_8f3a"
}

Response:

{
"trip_id": "T991",
"status": "REQUESTED",
"estimated_match_seconds": 15
}
HTTPMeaning
201Trip created; matching in progress
200Idempotency hit — same trip returned
503Dispatch overloaded — retry with same key

11.2 DynamoDB schema​

Table: Trips

{
"trip_id": "T991",
"rider_id": "R123",
"driver_id": null,
"status": "REQUESTED",
"pickup_h3": "8828308281fffff",
"pickup": {"lat": 37.7749, "lng": -122.4194},
"dropoff": {"lat": 37.7849, "lng": -122.4094},
"vehicle_type": "uberx",
"version": 1,
"created_at": "2026-07-28T21:00:00Z",
"city": "san-francisco"
}

Table: DriverLocks

{
"driver_id": "D42",
"trip_id": "T991",
"locked_at": "2026-07-28T21:00:05Z",
"ttl": 1735689600
}

GSI: city-status-index — query active trips per city for ops dashboard.

11.3 Redis geo index structure​

# Driver in H3 cell
SADD h3:8828308281fffff:drivers D42 D17

# Driver metadata (hash)
HSET driver:D42 lat 37.7750 lng -122.4190 status idle vehicle uberx rating 4.9 updated_at 1735689600

# On location update: remove from old cell, add to new cell
SREM h3:{old_cell}:drivers D42
SADD h3:{new_cell}:drivers D42
HSET driver:D42 lat ... lng ... updated_at ...

11.4 Match handler — step-by-step​

Step-by-step flow:

StepActionExplanation
1match()Matcher invoked for trip T991.
2–3k-ringQuery Redis for drivers in nearby H3 cells.
4FilterRemove busy/offline drivers.
5–6ETA batchRoad-network ETA for remaining candidates.
7RankScore: 60% ETA + 25% rating + 15% vehicle match.
8–9TransactWriteAtomic trip assign + driver lock in DynamoDB.
10PushSNS notification to driver D88.
11OFFEREDUpdate trip status; start 15s accept timer.

TransactWriteItems (atomic assign):

dynamodb.transact_write_items(TransactItems=[
{
"Update": {
"TableName": "Trips",
"Key": {"trip_id": trip_id},
"UpdateExpression": "SET driver_id=:d, #s=:offered, version=version+1",
"ConditionExpression": "#s = :requested AND attribute_not_exists(driver_id)",
"ExpressionAttributeNames": {"#s": "status"},
"ExpressionAttributeValues": {":d": driver_id, ":offered": "OFFERED", ":requested": "REQUESTED"},
}
},
{
"Update": {
"TableName": "DriverLocks",
"Key": {"driver_id": driver_id},
"UpdateExpression": "SET trip_id=:t, locked_at=:now",
"ConditionExpression": "attribute_not_exists(trip_id)",
"ExpressionAttributeValues": {":t": trip_id, ":now": now()},
}
},
])

11.5 Location indexer​

Step-by-step flow:

StepActionExplanation
1Consume batchRead up to 500 records per Kinesis poll.
2H3 encodeConvert lat/lng to H3 cell at resolution 8.
3SREM oldRemove driver from previous cell (if cell changed).
4SADD newAdd driver to current cell set.
5HSET metadataUpdate lat, lng, updated_at for ETA queries.
ParameterValue
Kinesis retention24 hours
Indexer batch size500 records
Driver TTL in Redis30s without update → remove from index
H3 resolution8 (city), 9 (dense urban)

11.6 Driver offer timeout handler​

def on_offer_timeout(trip_id: str, driver_id: str):
# Step 1: Release driver lock
dynamodb.delete_item(
TableName="DriverLocks",
Key={"driver_id": driver_id},
ConditionExpression="trip_id = :t",
ExpressionAttributeValues={":t": trip_id},
)
# Step 2: Reset trip to REQUESTED
dynamodb.update_item(
TableName="Trips",
Key={"trip_id": trip_id},
UpdateExpression="SET #s = :requested REMOVE driver_id",
ConditionExpression="#s = :offered",
ExpressionAttributeNames={"#s": "status"},
ExpressionAttributeValues={":requested": "REQUESTED", ":offered": "OFFERED"},
)
# Step 3: Re-match with excluded driver
match_engine.match(trip_id, exclude=[driver_id])

12. HA/DR and City Partitioning​

PrincipleImplementation
City partitionEach city = separate Redis cluster + DynamoDB table prefix
Multi-AZECS + Redis cluster + DynamoDB global tables optional
FailoverRoute 53 health check; shift traffic to standby AZ
No cross-cityRider in SF never matched to driver in NYC

13. Observability and Operations​

MetricAlert threshold
match_latency_p99> 30s
unmatched_trips_rate> 5% for 5 min
driver_lock_conflict_rateSpike — race condition indicator
kinesis_iterator_age_ms> 5000 — location index stale
redis_cell_driver_count max> 200 per cell — hot spot
offer_accept_rate< 60% — driver supply issue

Structured log:

{
"trip_id": "T991",
"event": "driver_assigned",
"driver_id": "D88",
"h3_cell": "8828308281fffff",
"k_ring": 2,
"candidates_evaluated": 12,
"match_latency_ms": 1240,
"eta_seconds": 180
}

14. Implementation Roadmap (8-Week Rollout)​

WeekDeliverable
1Trip API + DynamoDB schema + state machine
2Kinesis location stream + Redis H3 indexer
3Matching engine — k-ring + sequential offer
4TransactWrite assign + driver lock
5SNS push + offer timeout handler
6Hot-cell rate limiting (airport POC)
7Load test 85 req/s + 20K loc/s
8Multi-AZ hardening + dashboards

15. Testing Strategy​

TestPass criteria
Concurrent assign same driverExactly one succeeds — TransactWrite
Offer timeoutDriver lock released; re-match triggered
k-ring expandMatch found within 30s in sparse area
Hot cell 500 reqRate limit engages; no Redis timeout
Location stale 5sMatch still succeeds with EL positions
Idempotent trip createSame key → same trip_id

16. Architecture Review Checklist​

#GateStatus
1Trip assignment uses TransactWrite or conditional writes☐
2Driver lock table with TTL for orphaned locks☐
3Location index EL — not blocking on strong consistency☐
4H3 k-ring expand with 30s timeout☐
5Offer timeout releases driver + re-matches☐
6Hot-cell rate limiting for airport/event cells☐
7City-boundary partition — no cross-city matching☐
8match_latency_p99 dashboard + alert☐
9Load test at 85 req/s + 20K loc/s☐
10Race condition integration test in CI☐