Practice: Uber
Design ride matching that uses fresh driver locations, sends bounded offers, and assigns at most one driver to a ride and one ride to a driver.
Design ride matching that uses fresh driver locations, sends bounded offers, and assigns at most one driver to a ride and one ride to a driver.
Write your own design before opening hints or the solution review. The numbers below are exercise assumptions, not claims about any company’s production traffic. You may challenge an assumption, but record the replacement and explain which decision changes.
Scenario and constraints
- Assume 1 million active drivers across 200 metro areas and 50,000 ride requests per minute at peak.
- Driver location points arrive every 3 seconds and are considered stale after 15 seconds.
- A quote expires after 30 seconds; offer response windows are 8 seconds.
- Matching is partitioned by city; payment is outside the assignment transaction.
Your deliverables
- Define quote, driver location, ride request, offer, assignment, and lease identities.
- Calculate geo-cell candidate volume and show how stale points are filtered before ranking.
- Model the offer/accept state machine and atomically reserve both driver and ride.
- Bound offer fanout and retry work; explain city partitioning, rebalancing, and stale accept fencing.
Reason about this sequence
Read the diagram
Two dispatchers find driver D → Both create candidate offers → First valid acceptance commits → Second ownership check fails → Second trip searches again
For every step, annotate what is durable, what the caller knows, and which identity survives a retry. Identify the point where two concurrent actors could disagree. Do not assume a timeout means failure or a cache value grants ownership.
Interviewer follow-ups
- Two dispatchers offer the same ride to different drivers. What durable transaction prevents two assignments?
- A driver accepts after the offer lease expired and another driver was assigned. What does the server return?
- A location stream is delayed during a city surge. How do you preserve correctness while keeping matching responsive?
Answer each follow-up using the same design first. If it breaks, change the smallest boundary that repairs the invariant and explain the new cost. Show whether the change adds latency, storage, coordination, or operational work.
Staged hints
Hint 1 — reveal
Answer: Hint 1 — Treat location search as advisory; the final assignment must atomically claim both the ride and driver under one fenced authority.
Hint 2 — reveal
Answer: Hint 2 — Search nearby cells, filter by exact distance and freshness, then rank by a suitable travel-time estimate or simpler baseline. A straight-line nearest driver is not always the fastest on a road network. Bound the candidate set and expand the radius when necessary under a stated latency budget.
Hint 3 — reveal
Answer: Hint 3 — A driver accepts just after an offer expires and another trip is assigned. The old acceptance must compare offer identity, expiry, and current driver state, then reject safely. A delayed mobile packet is not proof that the old offer remains valid. Measure offer acceptance latency, stale-candidate rate, assignment conflicts, and time-to-match.
Evidence-based self-review
- Location is a discovery hint, while the assignment authority owns the ride/driver exclusivity invariant.
- One conditional transition reserves both resources with a stable offer ID and fencing/version check.
- Late acceptance and duplicate commands are idempotent and cannot steal a newer assignment.
- Candidate search, offer fanout, per-city workers, location freshness, and overload shedding are bounded.
Score each item 0 if absent, 1 if named without an enforceable mechanism, or 2 if the mechanism and a failure are explained. Record evidence from your own diagram beside the score. Then choose one weak decision, revise it, and repeat the relevant follow-up. This rubric is a learning tool, not a hiring forecast.
Clarify this prompt before choosing components
Ask the highest-impact questions first, agree on priorities, and record the interviewer’s answers. If a detail is unspecified, state an assumption and explain which decision depends on it. The numbers in this worked lesson are exercise assumptions, not company facts.
| Ask the interviewer | Why the answer changes the design |
|---|---|
| Driver discovery, matching, trip state or payments first? | Location candidates and authoritative trip transitions are separate. |
| Location update frequency and maximum staleness? | Spatial indexing needs freshness limits and bounded candidates. |
| Can one driver accept two riders, and how are cancellation races resolved? | Matching requires conditional assignment and explicit trip-state transitions. |
Use the Interview Playbook for the shared 45-minute sequence and fresher, intermediate, senior and staff evidence. Start with one complete operation. Extend the answer with the failure/recovery traces below, then defend a workload-specific alternative and a measurable rollout. Scope and evidence matter more than a large component list.
Reveal the full worked solution
Save your attempt before continuing.
Uber: Understand the building blocks
Choose a mechanism because it satisfies a requirement. These explanations describe the exercise design, not undisclosed implementation choices at the named company.
Uber: Quick vocabulary
| Term | Meaning and role in this exercise |
|---|---|
| API: Application Programming Interface | The contract for requests, responses and errors between components. An API route does not itself enforce every business invariant. |
| GPS: Global Positioning System | A source of location observations. Device reports can be delayed/noisy; validate sequence, age and accuracy under the exercise policy. |
| ETA: Estimated Time of Arrival | A predicted travel/arrival time. It depends on route and workload assumptions, not only straight-line distance. |
| PK: Primary Key | The declared row identity in a database schema; it does not automatically enforce every cross-row business rule. |
Uber: Spatial index and exact distance filter
What it means: An index that groups positions so a nearby query examines a bounded candidate set instead of scanning every location.
Why this problem needs it: Many moving drivers need efficient nearby candidate lookup.
How to use it: Search cells or bounding regions that intersect the requested radius, including boundaries, then compute exact distance and current eligibility for candidates.
Example in this design: Candidate D1 falls within the radius; check a fresh location and current driver availability before offering.
When it fits: Useful when frequent nearby queries make a full scan too expensive.
Alternative and limits: A small dataset may need only a scan. Geohashes, quadtrees and spatial database indexes have different update, precision and query costs. Proximity does not imply availability.
Uber: Geohash and quadtree
What it means: A geohash encodes a location into a hierarchical grid cell; a quadtree repeatedly divides a region into four child regions. Both can narrow spatial candidates.
Why this problem needs it: A hierarchical cell scheme is one optional spatial implementation.
How to use it: Choose a resolution, search intersecting neighboring cells/regions, and filter exact distances. A single same-prefix lookup misses nearby points across a cell edge.
Example in this design: A driver across a cell edge can be closer than one in the rider’s own cell, so inspect intersecting neighbors.
When it fits: Choose based on update rate, density and query shape rather than the word “nearby” alone.
Alternative and limits: A supported database spatial index avoids operating a separate index service. Redis geospatial queries are another implementation option, with explicit freshness and capacity limits.
Uber: Compare-and-set (CAS) and optimistic concurrency
What it means: A conditional write changes state only if an expected version or value still matches. The comparison and write share one atomic boundary.
Why this problem needs it: A location index cannot reserve a driver.
How to use it: Carry the version read by the caller; atomically compare, mutate and advance it. On conflict, re-read or reject under the business policy.
Example in this design: Offers O1 and O2 compete for D1; one atomic assignment claim wins.
When it fits: Useful when concurrent requests must not silently overwrite the same owned state.
Alternative and limits: Row locks or a serial owner can simplify highly contended updates. A read followed by an unconditional write is not CAS.
Uber: Lease, ownership epoch and fencing
What it means: A lease grants temporary work ownership. A fencing token or epoch identifies a newer owner so stale owners can be rejected at the mutation boundary.
Why this problem needs it: Offers expire and former owners can resume.
How to use it: Claim a job under an atomic authority, increment its attempt/epoch, and require that value on result publication. The protected resource must enforce the check.
Example in this design: Require the current offer/epoch for acceptance or release.
When it fits: Useful when workers can pause, restart or overlap after a timeout.
Alternative and limits: A non-expiring lock risks blocking forever. Lease expiry alone cannot stop an old process that resumes; external effects need their own supported idempotency/reconciliation.
Uber: WebSocket
What it means: A protocol for bidirectional messages over a persistent connection after a handshake. It is a transport, not a durable message store.
Why this problem needs it: Rider/driver apps need live offer and trip updates.
How to use it: Authenticate the session, route incoming messages to their owner, and bound outgoing buffers. Reconnect using application message IDs and cursors.
Example in this design: Ignore delayed location sequence 42 after 43, even when both arrive over a valid connection.
When it fits: Useful when both sides send frequent low-latency updates.
Alternative and limits: Polling is simpler at low update rates; Server-Sent Events fit one-way server updates. A new connection does not restore missed messages by itself.
Read the diagram
Spatial index finds nearby candidate driver D1; Fresh location does not reserve driver D1; Offers O1 and O2 compete in one atomic claim; Current offer and owner epoch control acceptance
Interview scope and guarantees
Request a ride, find nearby eligible drivers, assign one driver, track trip state, and complete payment. Matching needs one current assignment per trip and a defined driver capacity. ETA is an estimate; a location point is not an availability guarantee.
Capacity worksheet
Assume 1 million online drivers update every 4 seconds: 250,000 updates/s. At 150 bytes/update that is 37.5 MB/s raw. With 1,000 ride requests/s, separate the high-volume location projection from the smaller but contention-sensitive assignment store.
Concrete API contract
POST /trips {pickup,destination,product} -> {tripId,state}
POST /drivers/{id}/locations {sequence,lat,lon}
POST /trip-offers/{id}/accept {generation}
POST /trips/{id}/transitions {expectedVersion,action}Data model and access paths
driver_state(driver_id PK,status,current_trip,version)
trips(trip_id PK,rider_id,driver_id,state,version)
offers(offer_id PK,trip_id,driver_id,generation,expires_at)
locations(driver_id PK,cell,position,sequence,observed_at)Evolve a solution and explain each change
Read the diagram
Find candidates / Index recent driver positions and filter eligibility. / Nearby does not mean available or assigned.; Offer a ride / Record a ride and issue expiring offers to a bounded candidate set. / Two riders can concurrently target the same driver.; Commit assignment / Conditionally claim driver and ride; use fencing for reassignment and stale location. / A location projection must not grant exclusive ownership.
Step 1: Find candidates
Index recent driver positions and filter eligibility. Nearby does not mean available or assigned.
Step 2: Offer a ride
Record a ride and issue expiring offers to a bounded candidate set. Two riders can concurrently target the same driver.
Step 3: Commit assignment
Conditionally claim driver and ride; use fencing for reassignment and stale location. A location projection must not grant exclusive ownership.
Responsibility overview
Read the diagram
Rider to Ride API: request ride; Ride API to Assignment DB: commit ride state; Driver to Dispatcher: accept offer ID; Assignment DB to Dispatcher: dispatch intent; Dispatcher to Location index: fresh nearby candidates; Dispatcher to Assignment DB: conditional assignment
Worked end-to-end scenario
Riders R1 and R2 both see driver D within two kilometres. Each dispatcher sends an offer. D accepts R1; the assignment transaction verifies both that R1 is unassigned and D is available, then commits one assignment. R2’s attempt reloads and chooses another candidate. A late acceptance from an expired offer includes its old offer ID and cannot override a newer match. During the ride, location updates carry sequence or freshness metadata; a delayed packet must not move D back to yesterday’s street. ETA estimation can be approximate while assignment ownership remains strict.
Why these access paths matter
Use coarse spatial cells for candidate discovery, exact distance and freshness for refinement, and driver ID for authoritative availability. Store rides by rider and state; index dispatchable rides by zone. Cell boundaries require neighboring-cell queries. Assignment across records needs a clear transaction or coordination boundary, not two unrelated cache writes.
Build the baseline first
Read the diagram
Rider → trip intent → nearby driver candidates; Dispatcher → offer → atomic assignment; Trip transitions → durable events → rider updates
- Rider → trip intent → nearby driver candidates.
- Dispatcher → offer → atomic assignment.
- Trip transitions → durable events → rider updates.
Evolve the design under load
Read the diagram
Cell-indexed locations → bounded geo search; City dispatch partitions → candidate ranking; Regional gateways → live location updates
- Cell-indexed locations → bounded geo search.
- City dispatch partitions → candidate ranking.
- Regional gateways → live location updates.
Defend the hardest decision
Search neighboring spatial cells and calculate actual distance or ETA for candidates. Dense city cells need subdivision or bounded results. Atomically consume a valid offer and reserve driver capacity. A transaction spanning trip and driver state is straightforward when colocated; otherwise use an explicit reservation protocol with expiry and reconciliation rather than pretending two independent writes are atomic.
Failure and recovery analysis
Two dispatchers offer the same driver different trips. The driver’s authoritative compare-and-set chooses one winner; the losing trip returns to matching. A late acceptance with an old generation is rejected. A stale driver point must age out of eligibility even if it remains in the geospatial index. Losing GPS does not automatically cancel an in-progress trip.
Security and privacy boundary
Restrict precise trip location to participants and authorized operations; redact historical paths from ordinary service logs.
Interview follow-ups with reasoning
Question: How does surge pricing interact with acceptance?
Show answer and explanation
Answer: Store a quote version and expiry so a displayed price cannot silently change.
Question: How do you rebalance city partitions?
Show answer and explanation
Answer: Transfer ownership using epochs and reject stale dispatcher writes.
Question: What if the payment provider times out?
Show answer and explanation
Answer: Complete trip state separately and reconcile payment with its stable key.
Operate and verify the design
Match time, stale-location rate, rejected stale offers and assignment conflicts.
Deliver an expired offer acceptance after a different trip has reserved the same driver.
A second scenario to test transfer
Two riders receive the same driver as a nearby candidate. Two dispatchers send offers. The driver’s first valid accepted assignment commits at the owner; the competing transition fails and searches another candidate. A stale location index may continue listing the driver briefly, but the authoritative assignment check prevents double booking. This lets discovery be fast without making it the correctness boundary.
Can an available flag in the location cache authorize assigning a driver?
Show answer and explanation
Answer: No. It can suggest a candidate, but the assignment owner must conditionally validate current availability and offer state. Cache freshness is insufficient to protect an exclusive ownership invariant.
Compare alternatives
| Stage | Consistency need | Reason |
|---|---|---|
| Nearby discovery | Bounded stale candidates | Fast geographic search |
| Offer display | Versioned temporary state | Mobile latency |
| Assignment | Exclusive authoritative transition | No double booking |
| Trip updates | Recoverable state stream | Reconnect and audit |
A design-changing exercise
The location cache says available but the driver row says assigned. Which wins?
Show answer and explanation
Answer: The ownership row. Spatial discovery is a stale candidate hint and must be revalidated during assignment.
Design workshop: reserve both driver and ride
Core scope is rider request, nearby matching, offer acceptance, trip progression and payment. Pooling and complex surge optimization are extensions. Choose five-second location freshness, offer expiry at ten seconds and no two active rides for a driver. Discovery latency may degrade; assignment safety must remain intact.
Choose a city-owned transactional assignment authority for the baseline. rides and drivers are co-located so acceptance locks driver and ride in stable order, verifies offer ID/deadline/version and atomically marks both assigned. This is a deliberate partitioning decision; the design does not claim arbitrary two-shard updates are atomic.
BEGIN;
SELECT * FROM drivers WHERE id=:driver FOR UPDATE;
SELECT * FROM rides WHERE id=:ride FOR UPDATE;
-- Validate owner epoch, offer identity, expiry, driver availability,
-- and ride awaiting_assignment. Then update both rows and outbox.
COMMIT;A cross-city handoff first closes or transfers authority under a durable epoch; the driver cannot be available under both cities. A coordinator extension reserves driver with a fenced reservation, then attaches the ride and confirms. Recovery queries both reservation states and either finishes or releases the same identity. It must never issue an unrelated fresh reservation while the old one is unknown.
Read the diagram
Create ride A and offer OA; Create ride B and offer OB for same candidate; Accept OA; lock driver + ride A; Commit driver assigned to A; Delayed accept OB; Conflict; choose another candidate for B
Location ingestion stores driver ID, sequence, observedAt, receivedAt and coarse cell. Reject older sequence updates, expire stale eligibility and move the driver between cells with versioned projection updates. At 100,000 drivers updating every five seconds, city ingestion is 20,000 updates/s; 100-byte raw records are 2 MB/s before indexing/replication. Keep only recent location in memory and a bounded diagnostic history under privacy policy.
Candidate search expands intersecting cells, filters vehicle/status/freshness and estimates road travel time for a bounded shortlist. Straight-line distance selects candidates cheaply but does not capture bridges or traffic. A simple score can combine pickup ETA with availability/wait fairness; show each term and do not claim globally optimal routing. Reject a candidate at acceptance if its authority state changed since discovery.
Read the diagram
Boundary / Stored evidence / Client behavior; Quote / Quote ID, currency, expiry, route estimate / Changed destination requires new quote; Offer / Ride/driver/offer ID and deadline / Acceptance is conditional, not a cache flag; Trip / Ordered trip events and owner epoch / Resume after cursor; stale commands conflict; Payment / Trip-linked operation key and provider state / Unknown remains processing until reconciled
POST /quotes returns quoteId, estimateMinor, currency, expiresAt; POST /rides includes quoteId and stable requestKey. GET /rides/id returns trip version and driver location age. Store payment_attempts(trip_id,operation_key,state) and exact fare breakdown. Completion is a trip-authority transition; payment failure is separately recoverable. Driver location outage need not erase an active trip or authorize another one.
Exercise: A driver's location cache says available after assignment committed. Can a second dispatcher claim it?
Show answer and explanation
Answer: It can propose the candidate, but the locked city authority rejects the claim. On owner failure, increase epoch and reconstruct driver/ride assignments before admitting new offers; fail closed while exclusive ownership is uncertain.
Requirement trace and verification
| Requirement | Implementing design block | Verification link |
|---|---|---|
| R1 — Complete the primary user journey within the stated scope. | P01–P04; P09–P10. | V1 — Exercise the successful journey and the excluded/boundary case stated in the scope. |
| R2 — Preserve the problem's authoritative data invariant under concurrency. | P05–P06; P11–P12; DD1. | V2 — Run the race/replay case below and assert the invariant at the durable authority. |
| R3 — Meet the declared scale and API behavior without unbounded work. | P05–P08; P13–P14; relevant overload deep dives. | V3 — Exercise the API errors/retry identity and recompute the workload assumption that drives partition or capacity. |
| R4 — Recover from the named failure without losing or duplicating the user-visible outcome. | P15–P16; deep dives; Operations contract. | V4 — Race offers for one driver, delay an acceptance, and crash the coordinator; at most one active ride owns the driver. |
Operational contract
| Area | Decision and signals |
|---|---|
| SLIs | Match time; location age; offer acceptance conflicts; city queue delay; stale-offer rejection rate. |
| Overload limits | Cap location candidate count, offers per ride, per-city dispatch workers, and routing calls. |
| Recovery | Fence expired offer generations; reconcile driver/ride reservations before reassignment after a timeout. |
| Access controls | Restrict live trip location to rider, assigned driver, and authorized support; audit administrative access. |
| Dominant cost | Location ingestion, routing-provider calls, and real-time trip updates. |
Senior-level interviewer follow-ups
Question: A driver moves while a ride request is being assigned. What does the location index guarantee?
Show answer and explanation
Answer: The spatial index provides candidates from recent location versions; the authoritative assignment checks driver availability and version transactionally. A stale position may hurt ETA but must not grant a second ride.
Question: What if the nearest drivers are all busy by the time offers arrive?
Show answer and explanation
Answer: Expand the bounded search or retry against a fresh candidate snapshot, with an offer deadline and request generation. Avoid holding an unbounded set of drivers while searching.
A 60-second design answer
I would partition live locations by city or cell to find a short list of nearby drivers, then compute a better ETA for that shortlist. Assignment is a conditional state transition on the driver and ride owner; the spatial index is approximate and short-lived. Offers expire and retries use generations. I would track location age, candidate miss rate, assignment conflicts, pickup ETA error, and city-level overload.
Related concepts to revisit
Technical references
PostgreSQL transaction isolation and concurrent updates.
Treat a location as evidence, not ownership
Driver d7's latest location is close to rider r1, but the sample is 20 seconds old. The candidate path checks age and ranks a bounded nearby set; current assignment state then decides availability. An offer to r1 owns d7 at version 8. A competing r2 request cannot obtain the same driver, and a late acceptance for an expired offer cannot attach to a newer trip.
d7 location: (cell C), sampled 20 seconds ago
assignment: r1 offer O1, version 8
r2 conditional claim: conflict
O1 expires; O2 created at version 9
late O1 acceptance: reject/reconcile, never overwrite O2Read the diagram
d7 location: (cell C), sampled 20 seconds ago; assignment: r1 offer O1, version 8; r2 conditional claim: conflict; O1 expires; O2 created at version 9; late O1 acceptance: reject/reconcile, never overwrite O2
Adaptive location updates reduce write load when motion/visibility needs allow, but they change freshness. Matching partitions/routing must handle border candidates and ownership, not assume each geographic cell is a sealed world. A request queue protects bounded processing only under an honest acceptance/wait contract.
Show answer and explanation
Answer: A cached available bit and a nearby coordinate are both insufficient to promise an assignment. The driver's authoritative transition and offer identity determine the outcome.
Decision review: Uber
Uber: What it is
A ride-hailing design discovers nearby drivers, offers trips and commits mutually consistent driver and ride assignment.
Uber: Why it is needed
Location is transient evidence; racing offers, acceptance expiry and lost responses require an authoritative assignment protocol.
Uber: When to use it
Use a per-driver/per-ride ownership rule when neither may be active in conflicting assignments; define location and offer staleness.
Uber: How to use it
Keep GPS sequence/timestamp policy separate from trip truth. Commit eligible offer acceptance against driver availability, ride state and offer generation, then return a discoverable stable assignment.
Uber: Compare an alternative
Serializing every dispatch globally is unnecessary. Partition independent work while coordinating the contested driver/ride boundary; approximate location can improve browsing but not ownership.
Uber: Worked decision exercise
The following inputs and policies are original exercise assumptions; they are not measurements or undisclosed company behavior.
Driver C has location sequence 43 when delayed 42 arrives. Ignore the stale position under the sequence policy. Offers O1 and O2 race for C; accepting O1 must reject a conflicting O2 even if both map displays still show availability.
Read the diagram
Location 43 arrives before delayed 42: do not regress; Offers O1 and O2 target driver C; Authority accepts one eligible assignment; Retry the same acceptance identity after a lost reply
May a timed-out acceptance be retried with a new offer identity to speed recovery?
Show answer and explanation
Answer: First resolve the original stable acceptance. It may have committed. A new identity can create inconsistent intent unless the protocol explicitly handles replacement. A stale acceptance after expiry cannot take a driver already assigned to another ride.
Uber: Check the design
Observe location age, offers per driver, assignment conflicts and unresolved acceptances. Test driver disconnect after pickup without making the same trip available for a duplicate assignment.
Screenshot variant: One-city cab booking
For SDE-1, scope one city to requesting a ride, finding eligible nearby drivers, accepting one driver and completing/cancelling a trip. Assume 10,000 drivers update every five seconds: 2,000 location writes/s. This flow can use a regional location index plus a transactional trip authority; do not begin with a global routing platform.
Use driver(id,status,version), location(driver_id,lat,lon,observed_at), trip(id,rider_id,state,driver_id,generation) and offer(trip_id,driver_id,expires_at,generation). POST /trips accepts a request key; POST /offers/{id}/accept conditionally claims both an unassigned trip and an available driver; PATCH /trips/{id}/state validates the actor and legal transition. Location freshness narrows candidates but never proves availability.
Riders R1 and R2 both find D7 nearby. R1's accept transaction wins the driver/trip ownership constraint; R2 must try another candidate. An old offer arriving after cancellation cannot resurrect the trip because its generation/state no longer matches. Display searching until a durable match exists, and expire offers using authoritative time.
Screenshot variant: Ride matching across one country
For SDE-2, partition the country into dispatch regions and spatial cells, search neighboring cells and route each trip/driver to one current ownership region. A driver near a cell boundary must remain discoverable; a driver changing regions needs a versioned handoff so two regions cannot each grant a trip. Use geographic distance/ETA as candidate ranking, then arbitrate ownership transactionally.
Bound fanout: offer to a small candidate set, wait within a dispatch deadline, then expand radius or report no match. A simultaneous broadcast to every nearby driver creates contention and driver fatigue. Isolate airport/stadium hot cells and impose per-rider retries and per-region dispatch concurrency. Country-wide availability does not require one global lock or one globally synchronous location table.
Show answer and explanation
Answer: A partition can leave the location index stale while trip state remains authoritative. Prefer a smaller valid candidate set or a clear temporary failure over assigning the same driver twice. Measure location age, search-to-match latency, offer acceptance/expiry, stale-accept rejections and region-handoff conflicts; test two riders racing for the same driver and a driver crossing a region during acceptance.
Deep dive: moving a driver is not transferring assignment authority
The existing walkthrough already explains city-local atomic driver/ride assignment and stale offers. This workshop extends that baseline to delayed GPS sessions, lost acceptance replies, two-authority dispatch and ownership migration. Geography is discovery evidence; changing a driver's displayed cell must never create another owner allowed to assign that driver.
Separate location identity, age and business eligibility
Authenticate location writers to the driver/device session. Record a server-issued session incarnation, sequence, observation time, receive time, accuracy and coordinates. A sequence is ordered only within its session; a restarted app beginning at one must not be compared with another session's sequence 9,000 without an explicit session transition. This exercise permits one current reporting session per driver, fences old sessions at ingest and rejects conflicting same-sequence payloads.
Observation age and ingestion age are different. A newly received offline batch can contain old positions; a client clock far in the future must not create indefinitely fresh eligibility. Apply a declared clock-skew/accuracy policy, reject implausible future observations and bound freshness using trusted receive time plus validated observation evidence. If skew cannot be established, mark uncertainty or exclude the candidate rather than claiming precision. GPS absence does not prove an assigned driver is available or that an active trip ended.
A move between cells emits versioned removal/addition updates. Delayed add/remove messages must compare the driver's current session/location version, so an old removal cannot erase a newer membership. Readers may temporarily see a duplicate driver across neighboring cells: deduplicate by driver identity and revalidate authority. Search cells intersecting the radius, including borders, then exact distance and a bounded road-ETA shortlist. A single matching cell prefix can miss the closest driver across its boundary.
State the assignment boundary and retry response
request(rider, request_key, intent_hash, trip_id)
trip(id, owner, owner_epoch, generation, state, driver_id, decision_id)
driver(id, assignment_owner, owner_epoch, state, reservation_id, trip_id)
offer(id, trip_id, trip_generation, driver_id, driver_epoch,
quote_id, expires_at, disposition, assignment_id)
assignment(id, trip_id, driver_id, offer_id, committed_version)Bind request retries to authenticated rider and canonical pickup/destination/product/quote intent. A lost accepted response returns the same trip/assignment; changed meaning conflicts. At an accept endpoint, verify the authenticated driver, offer identity, expected trip generation, quote conditions, authoritative expiry and current ownership. At equality with expiry, this exercise rejects new acceptance. First resolve an already committed identical acceptance receipt before applying the current expiry check: a retry after the deadline is not a new late acceptance.
For one city, co-locate driver and trip records with one transaction authority. Lock or condition both under a fixed ordering, enforce one active assignment per driver/trip, consume the offer and commit the assignment plus publication intent atomically. If cancellation wins first, increment generation and reject the old offer. If assignment wins first, cancellation operates on that current assignment under the trip policy; it cannot pretend the driver was never claimed. Stable receipt recovery does not bypass current authorization on the status API.
Read the diagram
An offer deadline limits new acceptance; it does not erase an accepted assignment.
Cross-authority matching needs an explicit decision protocol
Country-wide discovery can find a driver whose assignment authority differs from the trip owner. Two independent CAS writes are not an atomic assignment. One extension uses a durable trip coordinator and driver participant: the driver authority prepares exclusive reservation P bound to trip/generation/driver epoch, then the coordinator records exactly one COMMIT or ABORT decision for that decision ID. The participant confirms or releases P only according to that authoritative decision. The rider sees confirmed only after the necessary committed participant evidence, not merely a successful prepare reply.
A prepared participant must not release itself solely because a local timer elapsed while a coordinator COMMIT might be in flight. Its deadline can trigger reconciliation or an abort request, but the single decision authority arbitrates commit versus abort. A partition can leave a prepared driver unavailable until the decision is recovered; this is an explicit availability cost. Prevent indefinite uncontrolled exposure with bounded prepared counts, admission shedding, replicated decision recovery and an operator repair procedure, not by inventing a second owner.
Replays use the same reservation/decision identity. An ABORT cannot reverse a committed decision, and a delayed COMMIT for an aborted generation cannot claim a newer reservation. Notify from durable decision/outbox state; delivery success is distinct from assignment truth. If this coordination cost is unsuitable, constrain matching to one authority or relocate the transaction boundary before offering. State the resulting border coverage or latency trade-off rather than claiming arbitrary cross-shard atomicity.
Transfer authority independently from cell movement
A driver physically crossing a region need not migrate business ownership immediately. Keeping its home assignment authority through an active trip often avoids unnecessary distributed transitions. When actual migration is required, freeze new claims at the old owner under a durable migration ID, resolve or carry prepared/current assignments, transfer a verified state/version checkpoint and atomically advance the ownership directory to the new epoch. The new owner opens claims only after installing that state; stale old-owner mutations must be rejected at the protected authority, not just by a dispatcher cache.
A directory CAS alone is insufficient if the old database still accepts writes. Coordinate old-owner freeze and new-owner activation with destination-side fencing and recoverable migration state. If the old region cannot be contacted, use an independently enforceable authority/fencing mechanism before promotion; otherwise remain unavailable for those drivers. Do not infer exclusivity from a lease timeout or geographic distance. Replaying an old completed migration cannot increment epochs and create another ownership transfer.
Location projections may advertise both old and new regions during transition. Route claims via the authoritative directory and reject stale epochs; projection duplicates affect search efficiency, not driver capacity. A busy assignment carried to the new owner remains busy. Region failback follows the same transfer protocol and does not overwrite accepted newer history.
Budget discovery, offers and recovery separately
The city variant's 10,000 drivers updating every five seconds yield 2,000 location updates/s. At an illustrative 200 bytes each, that is 0.4 MB/s raw before indexing/replication. For 1,000 ride requests/s, searching nine cells with a cap of 50 candidates/cell can examine up to 450,000 candidate references/s before duplicate removal. A shortlist of ten ETA evaluations/ride is 10,000 ETA evaluations/s; offering to three drivers per wave is 3,000 offers/s per wave. Multiple waves and retries multiply that cost.
Set total candidate/ETA/offer budgets across the entire search deadline, not independently per retrying worker. Use per-driver offer concurrency/cooldowns and per-tenant/region admission. Truncated discovery means a bounded attempt found no match; it does not prove no eligible driver exists anywhere. A fairness policy can consider driver wait time alongside pickup ETA, with explicit units and starvation checks; shortest straight-line distance is not a global matching optimum.
At 100 uncertain assignments/s and a five-minute reconciliation outage, 30,000 cases accumulate. If recovery resolves 150/s while 100/s remain incoming, useful drain is 50/s and takes at least 600 seconds before overhead. Prepared drivers remain unavailable during uncertainty, so bound that pool separately from queue memory. Track search-to-confirmed latency, GPS/session rejection, current location age, offer load, accepted-retry recovery, prepared age, decision gaps and migration conflicts. Restrict precise pickup/location histories to participants and authorized operations with bounded retention.
Ride assessment: preserve one assignment through change
Question: A new GPS session reports sequence 1 after the previous session reached 9,000. Is comparing bare sequence numbers sufficient?
Show answer and explanation
Answer: No. Fence/report session identity and apply the declared current-session transition, freshness and conflict policy. Neither sequence alone nor recent receipt proves an old sample is fresh.
Question: Acceptance committed before expiry but its reply was lost. Should an identical retry after expiry create a new offer or report that no assignment exists?
Show answer and explanation
Answer: Neither. Resolve the original authorized receipt and return the same assignment. Expiry rejects new acceptance; it cannot erase a committed assignment.
Question: A cross-region prepare timed out while the coordinator might have committed. Can the driver region release the reservation immediately?
Show answer and explanation
Answer: No under this protocol. Reconcile the single durable decision and preserve the reservation while uncertain, with bounded admission/exposure. A unilateral timeout release can permit a second conflicting assignment.
Score one point for scoped session/freshness and bounded border discovery, atomic local assignment and retry/expiry arbitration, explicit recoverable cross-authority decisions, frozen/stateful/fenced ownership transfer, and finite offer/recovery/privacy budgets. Compare Transactions and Isolation, Outbox and Sagas and Disaster Recovery.
Can an available flag in the location cache authorize assigning a driver?
Your design draft
Clarify assumptions, explain your approach, and test the difficult cases. Save your draft, then compare it with the study notes.
Self-review checklist
Self-guided practice. Automated AI feedback and code execution are not connected.