Auditing a Parcel-Routing Scheduler: Bugs, Structures, and Concurrency
System DesignModel answerLast updated
Review a Python parcel-routing codebase for correctness bugs, complexity bottlenecks, and thread-safety failures, then propose concrete fixes for each.
Background
You have just written process_order(...) inside a provided Python skeleton for a parcel-routing system. The codebase has four main classes — Order, Vehicle, Parcel, and Dispatcher — along with a collection of helper functions.
The system's rules:
- Each vehicle has a fixed departure time and a fixed weight capacity.
- Each order has an arrival time and one or more parcels, each with a weight.
- A parcel may only be loaded onto a vehicle that departs strictly after the order arrives.
- Parcels may be split across multiple vehicles.
- An order is either fully accepted (all parcels allocated, capacities updated) or fully rejected (the system state is untouched).
- Allocation follows a deterministic policy: fill vehicles in ascending departure order, breaking ties by vehicle ID.
The interviewer now asks you to step back and review the whole codebase — not just your own function.
What Is Expected
Work through three parts. For each, explain your reasoning and back claims with specific examples or complexity figures.
Part 1 — Correctness
What categories of bugs and unhandled edge cases would you look for in this kind of dispatcher? How would you verify or surface them under time pressure?
Part 2 — Performance
The baseline keeps all vehicles in an unsorted list. Each process_order call linearly scans all n vehicles to find eligible ones, sorts that eligible subset, and fills them one by one. Fleet size is on the order of 10⁵ vehicles; order volume may reach millions per day with bursts of many orders per second.
Analyze the baseline complexity for m orders over n vehicles, identify the bottlenecks, and propose data-structure replacements. State the resulting complexity after your changes, with an amortized argument where appropriate.
Part 3 — Concurrency and Scale
The baseline runs in a single process with no synchronization. Describe precisely what goes wrong when multiple threads call process_order concurrently. Then design an approach that makes concurrent order processing correct. Finally, discuss what you would change if order volume grew beyond what one machine handles comfortably.
Constraints
- In-memory, single-process Python; no external database or queue in the baseline.
- Cargo is divisible: an order is accepted if the total remaining capacity of eligible vehicles is at least the total parcel weight. (Bin-packing semantics are explicitly out of scope.)
- 64-bit integers for all weights and capacities.
- Rejected orders must produce zero state change.
- The fleet is static for the lifetime of the process (no arrivals or removals of vehicles).
- Order cancellations are not required.
Clarifying Questions Worth Raising
Before diving in, a strong candidate would confirm:
- Is "departs after order time" strict (
>) or non-strict (>=)? - Are departure times unique, or can multiple vehicles share a timestamp?
- What consistency guarantee is needed under concurrency — serializable, or weaker?
- Is there a read-heavy query pattern (e.g., "total remaining capacity on a route") that competes with writes?
Hints
Hint 1
For Part 1, think about what must be true before the first mutation and what invariants must hold after every successful or failed call. Write those down as assertions and drive test cases from them — especially the boundary between a fit and a miss-by-one.
Hint 2
For Part 2, the key observation is that departure times never change once loaded. That lets you sort the fleet once and turn every eligible-set query into a suffix lookup. Think about which data structure answers 'sum of remaining capacity from index i to the end' in O(log n) with point updates, and how you handle already-full vehicles cheaply.
Hint 3
For Part 3, map out the read-check-write sequence inside process_order and ask where two threads can interleave to corrupt state. A global serializing queue is the simplest correct design; explain why per-vehicle locks are tempting but hard to make correct given the deterministic fill order.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Parcel-Routing Dispatcher Review
The goal here is to show you can reason about a system at multiple levels — correctness invariants, algorithmic structure, and concurrent execution — not just implement a single function.
Part 1: Correctness Review
Work through these bug categories in priority order.
1. Atomicity of rejection — the most common and most damaging bug.
A typical broken implementation subtracts capacity from vehicles as it iterates, then discovers at the end that the total was insufficient and returns a failure. The order is rejected, but vehicles have already been drained. The fix is to separate the two phases:
- Check first: sum the remaining capacity of eligible vehicles. If the total is below the order's weight, return immediately — no mutation has occurred.
- Commit second: only then iterate and subtract.
Alternatively, build a complete allocation plan as a list of (vehicle_id, weight_taken) pairs and apply the mutations only once the plan is confirmed total.
2. Boundary comparisons.
Check every location where departure time is compared to order arrival time. Is it > or >=? Is it consistent between the filter loop, any binary search (bisect_left vs bisect_right), and helper functions that might re-derive the eligible set? When two vehicles share a departure time, there must be a deterministic secondary key (vehicle ID is natural) so sort order is stable across runs.
3. Zero and empty edge cases.
A vehicle whose remaining capacity reaches exactly 0 must not be treated as negative or re-entered into future allocations. Also check: an order with an empty parcel list (should it be accepted immediately?), a parcel with weight 0 (accept or reject?), a weight that exactly equals one vehicle's entire capacity, and negative weights (reject with a clear error before any mutation).
4. Shared mutable state in helpers.
Look for helpers that return a reference to an internal list that the caller then modifies — this aliases the scheduler's own data. Look for in-place sorts on a shared vehicle list, which silently reorder global state. Look for Python's mutable default argument trap: def f(x, acc=[]) accumulates across calls.
5. Bookkeeping drift.
Any cached aggregate — a per-route total, a "global remaining" counter — can fall out of sync with per-vehicle values if some code path updates one but not the other. The invariant Σ remaining + Σ allocated == Σ initial capacity should hold exactly at all times.
Verifying under time pressure: state the invariants explicitly, assert them in a lightweight wrapper, and run five hand-built cases: exact fit, one-unit short, order time equal to a departure time, order with no eligible vehicles, and an empty parcel list.
Part 2: Complexity and Data-Structure Improvements
Baseline cost. Each process_order scans all n vehicles to find eligible ones: O(n). It then sorts the eligible subset of size k: O(k log k). Over m orders, worst-case total is O(m · n log n). With n = 10⁵ and millions of orders, this is several orders of magnitude too slow.
Core insight. Departure times are fixed. Sort the fleet once by (departure, vehicle_id) at startup: O(n log n), paid once. The eligible set for any order is now a contiguous suffix starting just after the order's arrival time. A single binary search (bisect_right) finds that starting index in O(log n).
What you still need:
- Feasibility check: sum of remaining capacity over a suffix. A Fenwick tree (binary indexed tree) answers prefix sum queries and handles point updates in O(log n) each.
- Skipping drained vehicles: once a vehicle reaches zero remaining capacity it is permanently done. A union-find "next non-empty" pointer array with path compression lets you jump over drained vehicles in near-constant amortized time.
Amortized argument. Each vehicle is drained to zero at most once across the entire run, so the total number of "vehicle fully drained" events is at most n. Each accepted order partially fills at most one vehicle (the last one it touches) without draining it. Therefore total vehicle-touch events across all m orders is at most n + m, each costing O(log n) for a Fenwick update. The rejection path touches nothing.
Resulting complexity: O(n log n) preprocessing + O(m log n) for all order processing, with near-O(1) amortized union-find overhead. Space is O(n).
import bisect, threading
class Fenwick:
def __init__(self, vals):
self.n = len(vals)
self.t = [0] * (self.n + 1)
for i, v in enumerate(vals):
self.add(i, v)
def add(self, i, delta):
i += 1
while i <= self.n:
self.t[i] += delta
i += i & -i
def prefix(self, i):
"""Sum of indices [0, i)."""
s, i = 0, i
while i > 0:
s += self.t[i]
i -= i & -i
return s
def range_sum(self, lo, hi):
"""Sum of indices [lo, hi)."""
return self.prefix(hi) - self.prefix(lo)
class Dispatcher:
def __init__(self, vehicles):
# vehicles: list of (vehicle_id, departure_time, capacity)
self.vehicles = sorted(vehicles, key=lambda v: (v[1], v[0]))
self.dep = [v[1] for v in self.vehicles]
self.rem = [v[2] for v in self.vehicles]
self.fw = Fenwick(self.rem)
n = len(self.vehicles)
# nxt[i] = smallest index >= i with rem > 0; index n is a sentinel
self.nxt = list(range(n + 1))
self.lock = threading.Lock()
def _find(self, i):
"""Path-compressed next-non-empty lookup."""
root = i
while self.nxt[root] != root:
root = self.nxt[root]
while self.nxt[i] != root:
self.nxt[i], i = root, self.nxt[i]
return root
def process_order(self, arrival_time, parcel_weights):
if any(w < 0 for w in parcel_weights):
raise ValueError("negative parcel weight")
need = sum(parcel_weights)
with self.lock:
start = bisect.bisect_right(self.dep, arrival_time) # strict '>'
available = self.fw.range_sum(start, len(self.rem))
if need > available:
return None # rejected — zero state change
alloc, i = [], self._find(start)
while need > 0:
take = min(need, self.rem[i])
self.rem[i] -= take
self.fw.add(i, -take)
alloc.append((self.vehicles[i][0], take))
need -= take
if self.rem[i] == 0:
self.nxt[i] = i + 1 # retire this vehicle
i = self._find(i + 1)
return alloc # deterministic: earliest departure first
An empty parcel list returns [] (accepted with no allocation), which is the correct all-or-nothing behaviour for a trivially satisfiable order.
Part 3: Concurrency and Scale
What goes wrong without synchronization.
Python's GIL does not protect multi-step sequences. Two threads both calling process_order can interleave like this:
- Thread A reads remaining capacity: 100 units available.
- Thread B reads remaining capacity: 100 units available.
- Thread A needs 80 and passes the feasibility check.
- Thread B needs 80 and also passes the feasibility check.
- Both commit. Combined allocation is 160, but only 100 existed. Remaining capacity goes negative.
Beyond overselling, the Fenwick tree and the nxt union-find structure each require a read-modify-write sequence. Interleaved updates corrupt both structures, breaking every subsequent query in ways that are hard to detect and reproduce.
Correct approaches and trade-offs.
| Approach | Correctness | Throughput | Complexity |
|---|---|---|---|
| Global lock (as in code above) | Serializable, deterministic | Single-core bound | Trivial |
| Single-writer queue (one dispatcher thread, many producer threads) | Serializable, deterministic | Single-core bound, but producers don't block each other | Low |
| Per-vehicle locks in index order + Fenwick redesign | Correct for disjoint orders | High contention on low-index (earliest departure) vehicles | High |
| Optimistic concurrency + retry | Eventually consistent | Retry storms on hot vehicles | High |
Recommendation: a single-writer dispatch queue. Producer threads push order requests onto a queue.Queue; one dispatcher thread pulls and processes them in arrival order. This guarantees serializability, preserves determinism (auditable results), and keeps the implementation simple. The lock in the code above is already equivalent to this for in-process use.
Common mistake: reaching for per-vehicle locks. The deterministic fill policy means every order starts at the same low-index vehicles, so all threads contend on the same locks immediately. You get little parallelism and significant complexity (deadlock avoidance, Fenwick atomicity, etc.).
Scaling beyond one machine.
- Partition the fleet by route or geographic region. Each partition owns its vehicles and runs an independent single-writer dispatcher. Orders are routed to the right partition by a stateless front-end.
- Replace the in-memory Fenwick tree with a persistent, ordered key-value store (e.g., a B-tree index on departure time) that supports atomic compare-and-swap on capacity values.
- Use a durable message queue (Kafka, SQS) in front of each partition to absorb burst traffic and provide replay for auditing.
- For read-heavy query patterns (remaining capacity by route), maintain a read replica that trails the write path by a bounded lag, rather than contending on the writer.