Real-Time Courier-to-Delivery Matching Engine Design
Greedy & IntervalsModel answerLast updated
Design a scalable real-time engine that matches couriers to incoming delivery requests, defining the cost model, candidate pruning, matching method, complexity, and failure handling.
Courier-to-Delivery Matching Engine
A food delivery platform receives a constant stream of new delivery requests. At the same moment, thousands of couriers are moving around, going online and offline, finishing trips, and declining offers. You must design the component that decides which courier is offered which request.
What to cover
- Objectives. State what the system optimizes. Consider customer lateness, courier idle time at the pickup location, offer declines and cancellations, and fairness in how work and earnings are distributed. Explain how you would combine them into a single cost per courier/request pair.
- Constraints. Define which pairs are infeasible: remaining capacity (including batching of multiple requests), maximum distance, latest acceptable pickup time, and vehicle compatibility.
- Signals. List the inputs you would use, such as location and its age, courier status, vehicle type, historical acceptance rate, ratings, food preparation estimates, and demand surge.
- Algorithm and data structures. Propose an approach (for example greedy with priority queues, bipartite matching or min-cost flow, or scoring plus auction) that holds up under heavy churn and incomplete information.
- Complexity. Give time and space analysis in terms of the number of couriers, requests, and candidate edges.
- Robustness. Explain how you handle delayed or stale location updates, reassignment after declines, and adversarial or gaming behavior.
Assumptions you may use
Take a large metro region with roughly 10,000 active couriers and 2,000 pending requests, with decisions refreshed every few seconds.
Expected output
A structured design discussion. A short code sketch of the core matching loop is welcome.
Hints
Hint 1
Do not assign each request instantly to the nearest courier, and do not run a dense optimal solver over the whole city. Think about collecting requests into a short micro-batch window and solving each window.
Hint 2
Shrink the bipartite graph first: index couriers in a spatial grid, look only at nearby cells for each request, and keep the top K feasible candidates, so edges number at most M times K.
Hint 3
Fold everything into one expected-cost edge score (lateness, waiting, fairness, acceptance probability), then take edges in ascending cost order while checking capacity. Add an aging bonus so unmatched requests do not starve, and inflate ETAs for stale locations.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
This is an open-ended design problem, so start by turning the business goal into a cost function, choose a matching method whose cost fits a real-time budget, and then talk about messy reality. Jumping straight to the Hungarian algorithm is the common mistake.
Objectives, constraints, signals
Objectives (blended into one scalar cost per courier/request edge):
- Customer experience: minimize lateness, i.e. pickup ETA beyond the predicted food-ready time.
- Efficiency: minimize courier waiting at the venue (arriving well before the food is ready).
- Reliability: reduce declines and cancellations by weighting with predicted acceptance probability.
- Fairness: a small bonus for couriers who have been idle longer, so work spreads out.
Hard constraints (violation makes an edge infeasible): remaining capacity (greater than 1 if batching), pickup ETA within the latest acceptable pickup, distance within a maximum radius, and vehicle compatibility.
Signals: location and its age, status (idle, en route, at venue), speed or vehicle, acceptance rate, rating, prep-time estimate, surge level. Surge increases the lateness weight.
Scale and approach
With about 10k couriers and 2k requests, a dense optimal solve (cubic, around 10^12 operations) is out of the question. Instant nearest-courier assignment is myopic. The standard compromise is a micro-batch tick, run every 2 to 5 seconds per geo-shard:
- Candidate generation. Place couriers in a spatial grid (geohash or H3 in production). For each request, scan only neighboring cells within the maximum radius, filter by hard constraints, and keep the best K. This sparsifies the graph from M times N edges to at most M times K.
- Scoring. For each edge, expected cost =
p_accept * cost + (1 - p_accept) * decline_penalty, wherecost = w_late * lateness + w_wait * waiting - w_fair * idle_time. - Matching. Sort all edges by cost and take an edge greedily if the request is unassigned and the courier still has capacity. Greedy matching on weights is a 1/2-approximation and is usually near-optimal on sparse geographic graphs. In small dense clusters you can substitute the Hungarian algorithm or min-cost flow (needed for capacity above 1 with exact guarantees).
- Carry-over. Unmatched requests roll into the next tick with an aging bonus, so remote requests are not starved.
Why it works
- Feasibility: only edges that passed every hard check are considered, and greedy never exceeds capacity or double-assigns a request.
- Quality: each edge in an optimal matching was either chosen or blocked by an already chosen edge sharing an endpoint and having no greater cost, which yields the 1/2 bound.
- Liveness: the aging term grows without bound, so any feasible request eventually wins.
Complexity
Let N be couriers, M requests, K the per-request candidate cap, E at most M*K.
| Step | Time | Space |
|---|---|---|
| Build grid | O(N) | O(N) |
| Candidate generation | bounded by K kept per request (scan cost depends on cell density) | O(E) |
| Sort and greedy | O(E log E) | O(E) |
| Total | O(N + E log E) | O(N + E) |
With M = 2,000 and K = 20, E = 40,000, which takes milliseconds. The grid can be updated incrementally at O(1) per location ping instead of rebuilt each tick.
Code sketch
def assign(couriers, requests, cell_km=2.0, max_km=6.0, k=20):
grid = build_grid(couriers, cell_km) # only couriers with capacity and fresh location
edges = []
for r in requests:
cands = []
for c in nearby(grid, r, max_km):
eta = dist_km(c, r) / c.speed + 0.5 * c.loc_age # pad for stale GPS
if eta > r.deadline:
continue
late = max(0, eta - r.ready_in)
wait = max(0, r.ready_in - eta)
cost = W_LATE*late + W_WAIT*wait - W_FAIR*c.idle
p = c.accept_rate
exp = p*cost + (1-p)*DECLINE_PENALTY - W_AGE*r.age*DECLINE_PENALTY
cands.append((exp, r.id, c.id))
edges += sorted(cands)[:k]
edges.sort()
cap = {c.id: c.capacity for c in couriers}
out = {}
for _, rid, cid in edges:
if rid not in out and cap.get(cid, 0) > 0:
out[rid] = cid
cap[cid] -= 1
return out
The aging term shares a scale with the decline penalty so that long-waiting requests gradually outrank fresh ones. In production, weights are learned offline and validated by A/B tests on lateness, cancellations, and courier pay.
Handling messy reality
- Delayed or stale locations: drop couriers whose last ping exceeds a threshold, and inflate ETA by a fraction of the location age. Optionally dead-reckon along the last heading, or widen uncertainty and prefer couriers with fresh pings when costs are close.
- Declines and timeouts: treat an offer as provisional with a short timeout. On decline, return the request to the pool with an aging boost and exclude that courier for it, then re-run on the next tick. Cascading offers to the top two or three candidates in sequence limits latency.
- Reassignment: allow swaps only when the cost gain exceeds a threshold, to avoid flip-flopping and courier frustration. Never reassign once the courier is at the venue.
- Adversarial cases: couriers can cherry-pick by declining, spoof GPS, or toggle availability. Mitigate with acceptance-rate penalties built into the score, GPS plausibility checks (speed and jump limits), and rate limits on status changes. On the demand side, detect duplicate or fake requests with the usual fraud signals.
- Hot spots: a stadium letting out creates a local supply shortage. Shard by region but allow cross-boundary candidates, and cap K adaptively.
- Batching: with capacity above 1, add a detour-cost term for the second pickup and a hard bound on delay to the first order.
Trade-offs and common mistakes
- A longer batch window gives better matches but adds latency; 2 to 5 seconds is a typical balance.
- Greedy is fast and explainable but not optimal; use exact solvers only on small local clusters.
- Common mistakes: optimizing only distance, ignoring food-ready time (couriers arrive early and idle), no starvation protection, trusting stale locations, and rebuilding the whole index each tick.