Fix a Ride Dispatch Selection Bug
Data Structure DesignModel answerLast updated
Reproduce and fix a bug causing incorrect driver-to-order matching in a delivery assignment service.
You're working on a ride-hailing or delivery platform. The system assigns available drivers to incoming orders based on proximity and other factors. Recently, customers have complained that they're being matched with drivers who are farther away, while closer drivers remain available.
You have access to the codebase for the driver selection service. Given a specific failing scenario where an order was matched to the wrong driver, your task is to:
- Reproduce the incorrect assignment using the provided inputs (candidate driver IDs, their cached GPS coordinates with timestamps, and the pickup location)
- Write a minimal test case that fails with the current code
- Identify the root cause of the bug
- Implement a fix
- Explain how you would add observability and resilience features
Discuss your debugging methodology, the time and space complexity of your solution, and how you would handle edge cases like: no available drivers, tied distances, GPS coordinate noise, delayed location updates, service outages, and high request volume.
The service fetches driver locations from a cache, filters for availability and recency, then selects the best match based on distance and load.
Hints
Hint 1
Pay close attention to how timestamps are represented and compared – are all time values using the same units?
Hint 2
Consider what happens when cached location data becomes stale, and how the freshness check actually behaves with mixed units.
Hint 3
Think about making your fix testable by injecting dependencies like the clock, and ensuring deterministic behavior for tie-breaking.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Strong debugging follows a disciplined sequence: reproduce, capture in a test, hypothesize, verify with evidence, fix minimally, then harden.
Step 1: Reproduce the failure
Start with the reported scenario. An order at location P was assigned to driver A, but driver B was obviously closer. Gather the exact inputs the selector received: the list of candidate IDs, their cached locations (coordinates plus timestamps), and the pickup point. Run these inputs through the selector locally with a controlled clock to eliminate nondeterminism.
If the bug only appears when using real wall-clock time, that's your first major clue.
Step 2: Form and test hypotheses
Generate plausible explanations and test each systematically:
- Bad comparator: Is the sort direction inverted? Does it use a consistent ordering?
- Stale cache data: Could a driver's old position be treated as current?
- Unit mismatch: Are timestamps in different units (seconds vs milliseconds) being compared directly?
- Concurrency issue: Could two requests assign the same driver, or could a location update arrive mid-selection?
Step 3: Find the smoking gun
In the reproduction, driver A's cached location is 5 minutes old, recorded at a position that was once very close to the restaurant. The freshness validation looks like:
if time.time() - location.timestamp > MAX_AGE_SECONDS:
skip # too old
But time.time() returns seconds since epoch (~1.7 × 10⁹), while location.timestamp is stored in milliseconds (~1.7 × 10¹²). The subtraction yields a large negative number, so the condition never triggers. Every cached position passes the freshness check, even ancient ones.
This explains the pattern: incorrect assignments cluster around drivers whose app went to sleep or who recently moved away from a hotspot.
Step 4: Write a failing test first
Create a minimal scenario: driver A is 50 meters away but with a 5-minute-old timestamp; driver B is 800 meters away with a fresh timestamp. The test expects driver B to be selected (once stale locations are filtered). The test fails on the buggy code and passes after the fix.
Step 5: Implement the fix
Normalize units at the storage boundary. Store timestamp_ms everywhere. Convert the current time with now_ms = int(clock() * 1000). Inject the clock function so tests can use a fake, deterministic clock.
Also make tie-breaking deterministic. Use a composite key for selection:
(distance_bucket, active_order_count, location_age_ms, driver_id)
This defines a total order: closest bucket wins, then least-loaded driver, then freshest location, finally driver ID as a tiebreaker. Using min() over this tuple ensures the same inputs always yield the same result.
Why this fix is correct
After the fix, a location is eligible only if:
0 <= now_ms - timestamp_ms <= MAX_AGE_MS
Both sides are in milliseconds. Future timestamps (from clock skew) within a small tolerance are accepted; larger skews are rejected.
Distance bucketing (e.g., 25-meter increments) prevents GPS jitter from causing unstable selections when two drivers are nearly equidistant.
Complexity
- Time: O(n) for n candidates. A single pass with
min()suffices; sorting would be O(n log n) and unnecessary. Location fetching is one batched call. - Space: O(n) for the fetched location records.
Edge cases and resilience
No eligible drivers: Return None, emit a metric with rejection reason counts (unavailable, stale location, etc.), and let the caller retry with exponential backoff.
Ties: Resolved deterministically by the tuple key; never rely on dict iteration order.
GPS noise: Distance bucketing absorbs small fluctuations. Two drivers 10 meters apart fall in the same bucket, so load or freshness decides.
Late or out-of-order updates: The cache must accept only updates with timestamp_ms > existing_timestamp_ms, not last-write-wins. The selector rejects stale or far-future timestamps.
Partial outage: Use a timeout (e.g., 200ms) and one retry when fetching locations. Wrap the fetch in a circuit breaker: after N consecutive failures, fail fast for a cooldown period rather than assigning from stale data.
Double assignment race: The selector only proposes a driver. The actual assignment must be atomic (e.g., UPDATE drivers SET order_id = ? WHERE id = ? AND order_id IS NULL or Redis WATCH/MULTI). On conflict, re-select excluding the now-busy driver.
High load: Batch location fetches, pre-filter candidates with a spatial index (geohash, H3) to keep n small, and log per-decision rather than per-candidate to control volume.
Observability
Emit structured logs for each selection with: order_id, selected_driver_id, candidate_count, filtered_count (with reasons), and selection_time_ms. Track metrics: dispatch.selection.latency, dispatch.no_eligible_driver, dispatch.location_fetch.error, dispatch.circuit_breaker.open. These enable quick diagnosis when assignment quality degrades.
Code sketch
import math
import time
from dataclasses import dataclass
from typing import Callable, Dict, Optional
MAX_AGE_MS = 30_000
BUCKET_SIZE_M = 25.0
@dataclass(frozen=True)
class Location:
lat: float
lng: float
timestamp_ms: int
@dataclass(frozen=True)
class Driver:
id: str
active_orders: int
def haversine_m(lat1, lng1, lat2, lng2) -> float:
R = 6_371_000
phi1, phi2 = math.radians(lat1), math.radians(lat2)
dphi = phi2 - phi1
dlambda = math.radians(lng2 - lng1)
a = math.sin(dphi/2)**2 + math.cos(phi1)*math.cos(phi2)*math.sin(dlambda/2)**2
return 2 * R * math.asin(math.sqrt(a))
class DriverSelector:
def __init__(self, fetch_locs: Callable, clock: Callable[[], float] = time.time):
self.fetch_locs = fetch_locs
self.clock = clock
def select(self, drivers: list[Driver], pickup_lat: float, pickup_lng: float) -> Optional[str]:
now_ms = int(self.clock() * 1000)
ids = [d.id for d in drivers]
locations = self.fetch_locs(ids)
candidates = []
for d in drivers:
loc = locations.get(d.id)
if not loc:
continue
age_ms = now_ms - loc.timestamp_ms
if not (0 <= age_ms <= MAX_AGE_MS):
continue
dist = haversine_m(pickup_lat, pickup_lng, loc.lat, loc.lng)
bucket = int(dist / BUCKET_SIZE_M)
candidates.append((bucket, d.active_orders, age_ms, d.id))
if not candidates:
return None
return min(candidates)[3] # driver_id from the winning tuple
This approach isolates the bug, fixes it at the root, and builds in safeguards against similar issues.