Refactoring and Hardening a Driver Dispatch Service
Data Structure DesignModel answerLast updated
Identify anti-patterns in legacy dispatch assignment code, implement fixes, introduce domain types, and design for thread-safety.
You are tasked with reviewing and refactoring a legacy driver assignment module (DriverAssigner) that pairs nearby available delivery drivers with incoming orders.
The original legacy implementation contains several bugs, bad practices, and vulnerabilities to race conditions:
class driverAssigner:
def __init__(self, drivers=[]):
self.drivers = drivers
def assign_driver(self, order):
try:
best = None
for d in self.drivers:
if d['active'] == True:
dist = abs(d['x'] - order['x']) + abs(d['y'] - order['y'])
if best == None or dist < best[1]:
best = (d, dist)
best[0]['active'] = False
return best[0]['id']
except:
return None
Requirements
- Code Audit & Analysis: Identify the key issues in the legacy code across code quality, software architecture, error handling, input validation, and concurrency.
- Refactor & Redesign: Rewrite the implementation in modern Python. Your refactored version must:
- Use strongly typed value objects (e.g., dataclasses) for domain entities (
Location,Driver). - Eliminate dangerous default arguments, global state leaks, and anti-patterns (such as bare exceptions).
- Implement deterministic tie-breaking logic (e.g., break distance ties by driver ID).
- Throw precise domain exceptions rather than swallowing errors.
- Use strongly typed value objects (e.g., dataclasses) for domain entities (
- Thread Safety: Ensure all operations (
assign_driver,add_driver,release_driver) are thread-safe and avoid check-then-act race conditions.
Hints
Hint 1
Watch out for default mutable arguments in Python function signatures like `drivers=[]`.
Hint 2
Consider what happens when two concurrent threads invoke `assign_driver` at the exact same moment on the same available driver.
Hint 3
Ensure value objects are immutable (e.g., `frozen=True` dataclasses) to prevent accidental external mutations.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Code Audit & Issues Identified
| Category | Bug / Anti-Pattern | Operational Impact | Recommended Fix |
|---|---|---|---|
| State Mutability | Mutable default parameter drivers=[] | State leaks across multiple class instances created without arguments. | Default to None and initialize an internal collection instance. |
| Error Handling | Bare except: block | Swallows real bugs like TypeError, KeyError, and system interrupt signals (KeyboardInterrupt). | Raise explicit, typed domain exceptions (NoAvailableDriverError, UnknownDriverError). |
| Input Validation | No coordinate validation | Invalid types (strings, booleans) or non-finite numbers (NaN, inf) break math silently or crash. | Add validation on numeric limits (math.isfinite) and types upon construction. |
| Domain Modeling | Untyped dict primitives | Susceptible to missing key bugs (KeyError), hard to document or extend. | Replace dicts with immutable, validated @dataclass(frozen=True) entities. |
| Determinism | Distance tie-breaking relies on implicit list iteration order | Unstable, non-deterministic assignment behavior when drivers are at equal distance. | Incorporate secondary sorting key, such as driver_id. |
| Concurrency | Read-then-update race conditions | Two threads reading state simultaneously could double-assign the same driver. | Synchronize read-modify-write operations using a reentrant lock or mutex. |
2. Refactored Solution
from __future__ import annotations
import math
import threading
from dataclasses import dataclass, replace
from typing import Iterable, Optional
class DriverAssignerError(Exception):
"""Base exception for all driver assignment errors."""
class NoAvailableDriverError(DriverAssignerError):
"""Raised when no driver is currently active/available."""
class UnknownDriverError(DriverAssignerError):
"""Raised when operating on a driver ID that does not exist."""
def _validate_coordinate(name: str, value: object) -> None:
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise TypeError(f"{name} must be a valid numeric type, got {type(value).__name__}")
if not math.isfinite(value):
raise ValueError(f"{name} must be a finite number, got {value}")
@dataclass(frozen=True)
class Location:
x: float
y: float
def __post_init__(self) -> None:
_validate_coordinate("x", self.x)
_validate_coordinate("y", self.y)
def manhattan_distance(self, other: Location) -> float:
return abs(self.x - other.x) + abs(self.y - other.y)
@dataclass(frozen=True)
class Driver:
driver_id: str
location: Location
active: bool = True
def __post_init__(self) -> None:
if not isinstance(self.driver_id, str) or not self.driver_id.strip():
raise ValueError("driver_id must be a non-empty string")
if not isinstance(self.location, Location):
raise TypeError("location must be an instance of Location")
class DriverAssigner:
"""Thread-safe service for managing delivery drivers and matching orders."""
def __init__(self, drivers: Optional[Iterable[Driver]] = None) -> None:
self._lock = threading.Lock()
self._drivers: dict[str, Driver] = {}
if drivers:
for driver in drivers:
self._insert_internal(driver)
def _insert_internal(self, driver: Driver) -> None:
if not isinstance(driver, Driver):
raise TypeError("Expected a Driver object")
if driver.driver_id in self._drivers:
raise ValueError(f"Duplicate driver_id detected: {driver.driver_id}")
self._drivers[driver.driver_id] = driver
def add_driver(self, driver: Driver) -> None:
with self._lock:
self._insert_internal(driver)
def release_driver(self, driver_id: str) -> None:
"""Mark a driver as active/available again after completing an order."""
with self._lock:
existing = self._drivers.get(driver_id)
if existing is None:
raise UnknownDriverError(f"Driver ID '{driver_id}' not found.")
self._drivers[driver_id] = replace(existing, active=True)
def assign_driver(self, order_location: Location) -> str:
"""Finds the nearest active driver, marks them inactive, and returns their ID."""
if not isinstance(order_location, Location):
raise TypeError("order_location must be a Location instance")
with self._lock: # Critical section prevents double-assignment races
best_driver: Optional[Driver] = None
best_key: Optional[tuple[float, str]] = None
for driver in self._drivers.values():
if not driver.active:
continue
dist = driver.location.manhattan_distance(order_location)
# Primary key: Manhattan distance, Secondary key: Driver ID (lexicographical)
candidate_key = (dist, driver.driver_id)
if best_key is None or candidate_key < best_key:
best_driver = driver
best_key = candidate_key
if best_driver is None:
raise NoAvailableDriverError("No active drivers currently available")
# Mark selected driver inactive
self._drivers[best_driver.driver_id] = replace(best_driver, active=False)
return best_driver.driver_id
def snapshot(self) -> tuple[Driver, ...]:
"""Returns an immutable snapshot of all registered drivers."""
with self._lock:
return tuple(self._drivers.values())
3. Complexity & Scalability Trade-offs
- Time Complexity:
assign_driver: $O(N)$ linear search over $N$ registered drivers.add_driver/release_driver: $O(1)$ dictionary lookups and mutations.
- Space Complexity: $O(N)$ memory storage for registered drivers.
Architectural Scalability Note
For small fleets ($N < 10,000$), an $O(N)$ scan under a mutex lock is extremely fast and sufficient.
If scaling to tens of thousands of real-time updates:
- Spatial Indexing: Replace linear scanning with a spatial data structure like a 2D R-Tree or Geohash/H3 Hexagon buckets to reduce candidate driver search from $O(N)$ to $O(\log N)$ or $O(1)$ spatial lookup.
- Fine-Grained Concurrency: Replace single-lock global synchronization with partitioned locks (striped locks by geographic region/geohash) or lock-free concurrent data queues.