Part 9 · Blueprint 61
Food Delivery & Multi-Hop Logistics
13 min reading · Sources · Editorial review pending
The nearest courier can arrive too early or make another committed delivery late.
Page details
Published date · Last edited:
Draft edition. Editorial review and supplementary reading recommendations are still being completed.
Format: Architecture walkthrough. Prerequisites: the beginner bootcamp. Chapter prerequisites: Distributed Transactions: 2PC vs. Saga Orchestration, Ride-Hailing & Geospatial Matching, Distributed Task & Cron Scheduler (Temporal / Quartz Scale).
Sixty-second mental model
Problem: The nearest courier can arrive too early or make another committed delivery late.
Use: Schedule against preparation uncertainty and route feasibility.
Design boundary: Coordinate restaurant preparation and courier travel under a changing customer promise. Courier assignment, order readiness and payment each require recoverable state.
Layer 1 · Intuition
Hypothetical scenario: Northwind is designing food delivery. Maya represents product requirements, Dev implementation and Priya reliability. The team must agree what one delivery means and which component owns the order and dispatch state.
Think of a dispatcher coordinating cooking and a courier's arrival. Separate the requester from order and dispatch state, then identify the retained evidence needed after failure.
- Authority
- The entitled state owner.
- Invariant
- A rule preserved across concurrency and failures.
Architecture and worked reasoning
Design boundary: Coordinate restaurant preparation and courier travel under a changing customer promise. Courier assignment, order readiness and payment each require recoverable state.
Responsibilities on the request path
Workload and limiting resource
Hypothetical meal readiness is 18 minutes away and courier travel to pickup is eight minutes. Immediate dispatch can create about ten minutes of waiting if predictions hold. Delaying assignment changes availability risk; the earliest geographically nearest courier is not automatically the best policy.
Keep the units attached to each intermediate result. The assumptions above describe a hypothetical exercise, not observed vendor capacity. A real capacity decision also needs a measured service curve, skew, recovery traffic and an explicit admission policy for overload.
Mutation or publication path
- Accept the order under restaurant/payment policy.
- Choose a courier using predicted readiness and route constraints.
- Record pickup/dropoff evidence and recover missed transitions.
Observation and recovery path
- Read the current order timeline.
- Recompute promises from evidenced state changes.
- Expose uncertainty instead of preserving a stale ETA.
Failure that changes the decision
Hypothetical scenario: The courier cancels after the restaurant begins preparation. Reassignment must preserve one order identity and account for food readiness and customer deadline.
Attempt this decision before reading the explanation
Can restaurant and courier updates be represented as one boolean delivered flag?
No. Distinct states and evidence are needed to recover preparation, pickup, transit, delivery and cancellation consequences.
Supporting mechanism analysis
Hypothetical scenario: Northwind. Maya represents product, Dev implementation and Priya reliability. The following workflow develops the underlying mechanism.
Hypothetical scenario. A stadium exit concentrates Northwind dispatch requests. A driver crosses a spatial-cell boundary while old samples remain visible, and an offer response arrives after expiry. Dev lets each cell accept independently. Maya asks which rule prevents two assignments of the same driver.
Evolve the baseline under contention and stale observation. Keep geographic candidate organization separate from assignment authority, and preserve the original operation when its answer is lost. The burst changes concentration, not what a valid assignment means.
The same driver can appear in overlapping observations. Without the chosen shared authority, geographic placement can multiply acceptance decisions rather than merely distribute search.
This protects the operation’s meaning while discovery changes. Define how expiry and late replies race, rather than assuming their arrival order settles the result.
Spatial cells can organize candidate observations and distribute queries. They are not automatically permanent ownership of a driver. A vehicle moves while its old sample remains in another cell, so both cells can temporarily return it. Candidate duplication must not become independent assignment authority.
Maintain one coherent accepted driver/request transition or a documented ownership handoff that excludes conflicting writers. Moving an observation and transferring assignment authority are different state changes. A complete design says how in-flight offers and delayed samples behave while either change is occurring.
Hypothetical worked example. Choose fifty assignment requests per second, each examining twenty candidate records. Candidate evaluation is 50 × 20 = 1,000 checks per second. A revised fifty-candidate budget produces 50 × 50 = 2,500 checks per second. The increase is 2,500 − 1,000 = 1,500 checks per second before any extra routing or offer work.
These checks are logical evaluations, not necessarily network calls or physical database reads. A set-based query may combine them, and a poor spatial predicate may examine additional records before returning candidates. Larger coverage can improve the chance of finding someone eligible while spending more work and offering drivers farther away.
Select offer generation 7, then reassignment generation 8. A delayed response naming 7 cannot change a record whose authorized current offer is 8. Comparing 8 − 7 = 1 identifies a generation advance; the authority check, not the numerical difference alone, rejects the obsolete transition.
Hypothetical scenario. Offer O7 names request K, driver D, expiry and assignment generation 7. Acceptance is a conditional transition on the current offer, not an unqualified message saying yes. When expiry wins first, a new generation may be offered; a late acceptance for O7 must not revive it.
A geographic handoff moves assignment ownership, not merely spatial lookup. Transfer the current state and recoverable operation identities, fence the former owner and advance the ownership epoch. A stale dispatcher may still send messages after a partition; the effect target must reject its obsolete generation.
Location freshness and assignment exclusivity remain independent. A fresh driver can already be assigned, and a safely exclusive assignment can rely on a poor arrival estimate. Measure candidate evaluation, offer acceptance and reassignment outcomes separately. During contention, expanding the candidate set increases checks and may improve discovery, but it does not remove the serialized grant boundary.
Acceptance can commit while its response is lost. The driver then sees uncertainty even though the service has an accepted assignment. A matching retry inspects that operation and returns its permitted current result. Creating another assignment intention would bypass recovery of the first.
Similarly, a cancellation click on one phone does not establish a committed cancellation. The server-side state machine resolves its race with acceptance and communicates the resulting state. Local timers can stop waiting or change presentation, but the effect boundary decides which transition occurred.
If the database response is lost after acceptance commits, preserve uncertainty and reconcile the same operation. Creating a new assignment request to recover a missing response can bypass the original invariant. The same effect-boundary reasoning used for payments applies here without importing payment-specific policy.
“Closest means fastest arrival.” Geometric distance is one input. Road routing, current conditions and availability determine a different estimate.
“An expired screen means an expired server operation.” Local presentation and authoritative offer state can diverge. Reconcile before assuming a business transition.
Start with a declared region, freshness threshold and candidate budget. Expand deliberately when no acceptable candidate exists, recording the cost and resulting user wait. Do not silently scan the entire fleet to make every query appear successful.
Monitor stale-sample rejection, candidate counts, offer acceptance, obsolete transitions, assignment conflicts and unresolved outcomes. Separate location pipeline health from assignment success. A perfectly fresh map can coexist with a broken offer state machine.
Partition candidate discovery geographically where useful, but preserve a coherent assignment authority for drivers crossing cells. A boundary handoff must not make the driver independently available in two partitions. Reject a design that equates a spatial cell with permanent ownership of a moving person.
The partner fleet size and update intervals are illustrative. Position age, spatial representation and query selectivity affect real candidate quality and cost. An exclusive assignment also needs an authoritative acceptance rule, and a late response must satisfy the current offer generation rather than only its original request identity.
Layer 3 · Internals
Food delivery coordinates three clocks: preparation, courier travel and the customer's delivery promise. Assigning the nearest idle courier immediately can produce a long unpaid wait if the kitchen has not started the order. A readiness estimate should be a range or distribution with observable updates, not an exact prediction treated as fact.
Batching two orders is a constrained routing decision. Include pickup readiness, vehicle capacity, drop-off deadlines and existing commitments; minimizing driving distance alone can make food late. Google's vehicle-routing-with-time-windows formulation illustrates how route feasibility differs from simple nearest-neighbor matching. Keep order, restaurant acknowledgment and courier assignment as separately recoverable records. A disconnected restaurant tablet may replay an old acceptance after cancellation, so version transitions and define the authority resolving that race. When an ETA model changes, evaluate its calibration separately from the dispatch policy that consumes it; better prediction does not automatically imply a better assignment outcome.
Trade-offs and limits
| Approach | Provides | Requires |
|---|---|---|
| Immediate nearest-courier assignment | Simple to explain under ready-to-pick-up work. | Preparation uncertainty can create avoidable waiting. |
| Readiness-window dispatch | Aligns assignment with expected pickup feasibility. | Prediction error and existing route commitments must be handled explicitly. |
Recovery decision
Hypothetical scenario: The courier cancels after the restaurant begins preparation. Reassignment must preserve one order identity and account for food readiness and customer deadline.
No. Distinct states and evidence are needed to recover preparation, pickup, transit, delivery and cancellation consequences.
Write your design before revealing the review
Can restaurant and courier updates be represented as one boolean delivered flag?
Drafts and self-review are stored only in this browser. They are separate from reading completion.
Compare your decision
No. Distinct states and evidence are needed to recover preparation, pickup, transit, delivery and cancellation consequences.
The courier cancels after the restaurant begins preparation. Reassignment must preserve one order identity and account for food readiness and customer deadline.
Check your understanding
Can restaurant and courier updates be represented as one boolean delivered flag?
No. Distinct states and evidence are needed to recover preparation, pickup, transit, delivery and cancellation consequences.
How would you recover from this failure: The courier cancels after the restaurant begins preparation. Reassignment must preserve one order identity and account for food readiness and customer deadline.
Start with the exact boundary that failed. Accept the order under restaurant/payment policy. Choose a courier using predicted readiness and route constraints. Record pickup/dropoff evidence and recover missed transitions. Then recover evidence through the observation path: Read the current order timeline. Recompute promises from evidenced state changes. Expose uncertainty instead of preserving a stale ETA. Preserve the distinction between a confirmed state change and an unavailable response.
Which assumption in the worked calculation would a burst or concentrated tenant invalidate first?
Hypothetical meal readiness is 18 minutes away and courier travel to pickup is eight minutes. Immediate dispatch can create about ten minutes of waiting if predictions hold. Delaying assignment changes availability risk; the earliest geographically nearest courier is not automatically the best policy. Recompute the affected resource rather than multiplying unrelated storage and network budgets by the same factor. Coordinate restaurant preparation and courier travel under a changing customer promise. Courier assignment, order readiness and payment each require recoverable state.
Which component in this topology could be removed from a smaller first deployment?
Order workflow, Prep prediction, Courier assignment, Delivery timeline name responsibilities, not a requirement for separate processes. Co-locate responsibilities when their transaction, trust and capacity boundaries permit it. Accept the order under restaurant/payment policy.
What evidence must a caller have before relying on the observation path?
Read the current order timeline. Recompute promises from evidenced state changes. Expose uncertainty instead of preserving a stale ETA. No. Distinct states and evidence are needed to recover preparation, pickup, transit, delivery and cancellation consequences.
45-minute interview rubric
- 00–05: scope delivery and order and dispatch state.
- 05–12: identify the limiting resource and derive the domain workload above, retaining units and assumptions.
- 12–28: draw order and dispatch state, numbered writes and reads.
- 28–40: challenge recovery: Schedule against preparation uncertainty and route feasibility.
- 40–45: defend order_id placement, observations and remaining assumptions.
Go deeper
- Vehicle Routing Problem with Time Windows | OR-Tools | Google for Developers · Primary document · developers.google.com. Schedule against preparation uncertainty and route feasibility. Verified 2026-10-26.
- Introduction | H3 · Primary document · h3geo.org. Schedule against preparation uncertainty and route feasibility. Verified 2026-10-26.
Decision log
Schedule against preparation uncertainty and route feasibility.
Preserve delivery identity and order and dispatch state ownership.
Revisit changed workload, observations or recovery objectives.