Learning pathsPricingChecking sign-in…
Question Breakdowns

Local Delivery Service

Design a service that matches customers placing local orders with couriers, tracks pickup and delivery, and communicates changes.

Clarify this prompt before choosing components

Ask the highest-impact questions first, agree on priorities, and record the interviewer’s answers. If a detail is unspecified, state an assumption and explain which decision depends on it. The numbers in this worked lesson are exercise assumptions, not company facts.

Ask the interviewerWhy the answer changes the design
Browse stores, place orders or dispatch couriers first?These paths have different state and latency owners.
Must every displayed item be reservable, and for how long?Browse estimates cannot substitute for authoritative stock reservations.
What happens if payment succeeds but no courier is available?Define cancellation, refund and reconciliation before adding retries.

Use the Interview Playbook for the shared 45-minute sequence and fresher, intermediate, senior and staff evidence. Start with one complete operation. Extend the answer with the failure/recovery traces below, then defend a workload-specific alternative and a measurable rollout. Scope and evidence matter more than a large component list.

Local Delivery Service: Understand the building blocks

Choose a mechanism because it satisfies a requirement. These explanations describe the exercise design, not undisclosed implementation choices at the named company.

Local Delivery Service: Quick vocabulary

TermMeaning and role in this exercise
API: Application Programming InterfaceThe contract for requests, responses and errors between components. An API route does not itself enforce every business invariant.
SQL: Structured Query LanguageA language for querying/manipulating relational data. Correctness still depends on constraints, transactions and isolation choices.
GPS: Global Positioning SystemA source of location observations. Device reports can be delayed/noisy; validate sequence, age and accuracy under the exercise policy.
ETA: Estimated Time of ArrivalA predicted travel/arrival time. It depends on route and workload assumptions, not only straight-line distance.
SLA: Service-Level AgreementA contractual service commitment. Choose measurable objectives and provider budgets that support the promised behavior.
PK: Primary KeyThe declared row identity in a database schema; it does not automatically enforce every cross-row business rule.

Local Delivery Service: Spatial index and exact distance filter

What it means: An index that groups positions so a nearby query examines a bounded candidate set instead of scanning every location.

Why this problem needs it: Store/courier discovery should avoid an all-location scan.

How to use it: Search cells or bounding regions that intersect the requested radius, including boundaries, then compute exact distance and current eligibility for candidates.

Example in this design: Choose candidates by geography, then check cart feasibility and route ETA.

When it fits: Useful when frequent nearby queries make a full scan too expensive.

Alternative and limits: A small dataset may need only a scan. Geohashes, quadtrees and spatial database indexes have different update, precision and query costs. Proximity does not imply availability.

Mechanism reference

Local Delivery Service: Relational database transaction and constraints

What it means: A relational store keeps structured rows; a transaction commits a bounded group of changes together. Constraints reject specified invalid states.

Why this problem needs it: An all-or-nothing cart needs one authoritative reservation boundary.

How to use it: Use primary/unique keys and a chosen isolation/locking protocol for the actual invariant. Atomically persist related rows and the operation result before acknowledgement.

Example in this design: Store S1 lacks B while S2 has A and B; browsing results cannot promise either cart.

When it fits: Useful for bounded cross-row correctness, joins and access paths that fit the relational model.

Alternative and limits: Key/value stores can fit simpler keyed operations. “SQL” alone does not prevent lost updates, validate every cross-row rule or coordinate an external provider.

Mechanism reference

Local Delivery Service: Saga and compensation

What it means: A saga coordinates several separately committed business steps. Compensation is an explicit corrective business action after a partial outcome.

Why this problem needs it: Inventory, payment and courier assignment commit separately.

How to use it: Track each step and its stable identity; on failure reconcile uncertain outcomes before requesting an allowed compensating action.

Example in this design: Track each step’s identity and reconcile uncertainty before substitution or release.

When it fits: Useful when inventory, payment and dispatch have independent authorities.

Alternative and limits: A local transaction is simpler when all required state shares one database. Compensation may be partial or impossible; it is not automatic transaction rollback.

Local Delivery Service: Lease, ownership epoch and fencing

What it means: A lease grants temporary work ownership. A fencing token or epoch identifies a newer owner so stale owners can be rejected at the mutation boundary.

Why this problem needs it: Dispatch offers must have current ownership and bounded lifetime.

How to use it: Claim a job under an atomic authority, increment its attempt/epoch, and require that value on result publication. The protected resource must enforce the check.

Example in this design: An expired offer cannot release a later courier assignment.

When it fits: Useful when workers can pause, restart or overlap after a timeout.

Alternative and limits: A non-expiring lock risks blocking forever. Lease expiry alone cannot stop an old process that resumes; external effects need their own supported idempotency/reconciliation.

Interview scope and guarantees

Browse nearby stores, place an order, reserve available items, assign a courier, and track progress. Begin with one city and one store per order. Inventory and payment need durable outcomes; location freshness can be approximate. A confirmed order must have one owning fulfillment workflow.

Capacity worksheet

Assume 50,000 active couriers reporting every 5 seconds: 10,000 location writes/s. At 200 bytes/update that is 2 MB/s before overhead. Retaining every update for a day produces 172.8 GB; a current-location projection needs far less. Assume 100 orders/s peak and keep order transactions separate from location ingestion.

Concrete API contract

Contract / pseudocode
GET /stores?lat=...&lon=...&radius=...
POST /orders {storeId,items,address,paymentToken} -> 202 {orderId}
POST /couriers/{id}/location {sequence,lat,lon,time}
POST /offers/{id}/accept {version}

Data model and access paths

Contract / pseudocode
orders(order_id PK, user_id, store_id, state, version)
order_items(order_id, sku, quantity, quoted_price)
assignments(order_id UNIQUE, courier_id, lease_until, generation)
courier_location(courier_id PK, sequence, position, updated_at)
inventory(store_id,sku,available,version); PK(store_id,sku)
stock_holds(order_id,sku,qty,state,expires_at); PK(order_id,sku)
quotes(id PK,store_id,address_version,total_minor,expires_at)
payment_attempts(order_id,attempt_key,state,provider_ref); UNIQUE(order_id,attempt_key)
courier_assignments(courier_id UNIQUE,order_id UNIQUE,offer_id,version)

Evolve a solution and explain each change

Three architecture decisions for Local Delivery Service, including the pressure each introduces.
Three architecture decisions for Local Delivery Service, including the pressure each introduces.
Read the diagram

Accept an order / Persist the basket and address with a quoted service area and price. / An accepted order does not reserve scarce inventory or a courier.; Reserve explicitly / Use conditional stock reservations and a durable order state machine. / A timeout can leave reserved stock without a known payment outcome.; Coordinate fulfillment / Assign one courier through conditional ownership; reconcile payment and reservation deadlines. / Dispatch projections and location updates can be stale.

Open original
Local Delivery Service · architecture decisions
Three architecture decisions for Local Delivery Service, including the pressure each introduces.

Three architecture decisions for Local Delivery Service, including the pressure each introduces.

Step 1: Accept an order

Persist the basket and address with a quoted service area and price. An accepted order does not reserve scarce inventory or a courier.

Step 2: Reserve explicitly

Use conditional stock reservations and a durable order state machine. A timeout can leave reserved stock without a known payment outcome.

Step 3: Coordinate fulfillment

Assign one courier through conditional ownership; reconcile payment and reservation deadlines. Dispatch projections and location updates can be stale.

Responsibility overview

Connected responsibilities for Local Delivery Service. Trace the authoritative and derived paths separately.
Connected responsibilities for Local Delivery Service. Trace the authoritative and derived paths separately.
Read the diagram

Customer to Order API: place order; Order API to Order DB: reserve stock and order; Courier to Dispatcher: accept courier offer; Order DB to Work queue: dispatch intent; Work queue to Dispatcher: claim pending order; Dispatcher to Order DB: conditional assignment

Open original
Local Delivery Service · connected architecture
Connected responsibilities for Local Delivery Service. Trace the authoritative and derived paths separately.

Connected responsibilities for Local Delivery Service. Trace the authoritative and derived paths separately.

Worked end-to-end scenario

A customer buys the final two cartons at store S. The order service records a pending order, then atomically reserves two units while stock permits it. Payment authorization succeeds but its response is lost. The customer retry returns the same order rather than reserving again. A reconciler queries the payment attempt using its stable identity. Only an authorized order enters dispatch. Two dispatchers propose different couriers: one conditional assignment succeeds; the other reloads the order. If no courier is available before the reservation deadline, transition to a stated cancellation/refund policy instead of leaving inventory locked indefinitely.

Why these access paths matter

Read catalog by store and item; mutate available stock with an atomic quantity check, not a cached number. Index open dispatch jobs by service zone and state. Store order lines and reservation IDs so cancellation releases only the quantity held by this order. Separate approximate availability for browsing from the authoritative checkout decision.

Build the baseline first

Local Delivery Service: baseline request paths.
Local Delivery Service · working baseline
Read the diagram

Buyer → order API → order and outbox; Workflow → inventory reservation → payment authorization; Dispatcher → courier offer → conditional assignment

Open original
Local Delivery Service · working baseline
Local Delivery Service: baseline request paths.

Local Delivery Service · working baseline

  1. Buyer → order API → order and outbox.
  2. Workflow → inventory reservation → payment authorization.
  3. Dispatcher → courier offer → conditional assignment.

Evolve the design under load

Local Delivery Service: additional scaling and recovery paths.
Local Delivery Service · scale and recovery paths
Read the diagram

Location stream → geospatial candidate index; City queues → bounded dispatch workers; Order events → tracking projection → client updates

Open original
Local Delivery Service · scale and recovery paths
Local Delivery Service: additional scaling and recovery paths.

Local Delivery Service · scale and recovery paths

  1. Location stream → geospatial candidate index.
  2. City queues → bounded dispatch workers.
  3. Order events → tracking projection → client updates.

Defend the hardest decision

Dispatch first selects nearby eligible couriers, then ranks a bounded candidate set by estimated travel time and workload. A location index suggests candidates; it does not grant assignment ownership. An offer acceptance must atomically check that the order is unassigned and the offer generation is current. To prevent a courier taking incompatible deliveries, validate capacity in the same authoritative assignment boundary or reserve capacity before confirming.

Spatial prefilter and route-time refinement select a bounded set of candidate warehouses; checkout still rechecks authoritative inventory.
Filter candidates geographically before spending routing capacity.
Read the diagram

Customer point + service zone select nearby geo cells → Bound the candidate stores, for example to 50 → Batch route-time estimates with traffic and provider deadlines → Rank by ETA and item coverage; timeout means approximate browsing → Checkout rechecks exact stock at the authoritative inventory rows → Only a stock transaction reserves units; browsing cannot promise them

Open original
Spatial candidates → ETA → authoritative stock
Spatial prefilter and route-time refinement select a bounded set of candidate warehouses; checkout still rechecks authoritative inventory.

Filter candidates geographically before spending routing capacity.

Failure and recovery analysis

The store rejects one item after payment authorization. The workflow must choose substitution, partial fulfillment, or cancellation; a database rollback cannot undo a provider authorization. Persist compensation intent and retry it. If a courier disconnects, mark location stale and contact/reassign according to policy; never dispatch a second courier solely because one heartbeat was missed.

Security and privacy boundary

Expose precise addresses only to authorized participants during fulfillment. Encrypt retained location history and apply a retention limit.

Interview follow-ups with reasoning

Question: What if two couriers accept?

Show answer and explanation

Answer: The conditional assignment permits only one current owner.

Question: What if location arrives out of order?

Show answer and explanation

Answer: Keep the highest accepted sequence and reject implausibly old data.

Question: How would multi-store orders change the design?

Show answer and explanation

Answer: Split fulfillment legs while retaining an order-level outcome and compensation policy.

Operate and verify the design

Order-to-assignment time, stale-driver fraction, compensation age and per-city queue delay.

Lose a courier acceptance response and verify that only one assignment remains authoritative.

A second scenario to test transfer

Two orders select courier C from the same location snapshot. Both offers are displayed, but C accepts the first under the declared policy. The owner atomically assigns C to one order; the competing acceptance fails and dispatch chooses another candidate. The second order can still display an outdated nearby courier briefly without violating assignment correctness.

Couriers C and D both appear close to an order. Two dispatchers offer C two different orders. Define the winning transition and the losing response.

Show answer and explanation

Answer: Use a versioned, conditional active-assignment transition at the courier/assignment authority. One acceptance commits; the other returns conflict and selects a new candidate. Presence or a nearby result cannot grant ownership. Persist the offer and trip event so retries return the same decision.

Compare alternatives

MechanismWhat it decidesFailure to handle
Spatial lookupWho might be nearbyStale and boundary candidates
Assignment ownerWho owns the order/courierConcurrent acceptances
Trip event streamWhat happened and whenDisconnect and replay
Support repairHow exceptional cases closeUnlogged manual state changes

A design-changing exercise

Two orders each observe five units and request four. Can both be accepted?

Show answer and explanation

Answer: Not if inventory is promised strictly. The reservation must conditionally decrement the authoritative quantity in a transaction; an earlier availability read is advisory.

Design workshop: one order, three independent authorities

Core requirements are basket checkout, stock reservation, payment, courier assignment and delivery progress. Route optimization across many stops is an extension. Assume a two-second checkout admission target, five-second location freshness and no oversold stock; discovery can lag, but reservation and assignment decisions cannot use a stale cache as authority.

Add inventory(store_id,sku,available,version), stock_holds(order_id,sku,qty,state,expires_at), quotes(id,store_id,address_version,total_minor,expires_at), payment_attempts(order_id,attempt_key,state,provider_ref) and courier_assignments(courier_id UNIQUE,order_id UNIQUE,offer_id,version). Address records are owner-scoped; quote stores an immutable address and price snapshot. A changed basket or expired quote requires a new quote, not silent price mutation.

sql
BEGIN;
-- Deduplicate customer/request and verify quote before this step.
UPDATE inventory SET available = available - :qty,
                     version = version + 1
WHERE store_id = :store AND sku = :sku AND available >= :qty;
-- Require one affected row for every SKU; otherwise roll back.
INSERT INTO stock_holds VALUES (:order,:sku,:qty,'held',:deadline);
INSERT INTO order_events VALUES (:event,:order,'stock_reserved');
INSERT INTO outbox VALUES (:event,:order,'authorize_payment');
COMMIT;

Lock multiple SKU rows in a stable SKU order and handle deadlock retries. The order authority stores saga state; it does not hold the stock transaction open while calling payment. A provider timeout moves to payment_unknown and a reconciler queries the original key. Confirmed payment permits dispatch. Stock expiry before a late success triggers compensation, not delivery of an unavailable basket.

Checkout saga without a network call inside SQL. Customer to Order/stock authority: Submit stable request and unexpired quote; Order/stock authority to Order/stock authority: Reserve every SKU; persist payment intent/outbox; Order/stock authority to Payment provider: Authorize using original operation key; Payment provider to Order/stock authority: Timeout means unknown; query same operation; Order/stock authority to Dispatcher: Dispatch only after confirmed payment and valid stock; Dispatcher to Order/stock authority: Conditional courier and order assignment; Order/stock authority to Customer: Return tracked order state and version
Checkout saga without a network call inside SQL.
Read the diagram

Submit stable request and unexpired quote; Reserve every SKU; persist payment intent/outbox; Authorize using original operation key; Timeout means unknown; query same operation; Dispatch only after confirmed payment and valid stock; Conditional courier and order assignment; Return tracked order state and version

Open original
Checkout saga without a network call inside SQL
Checkout saga without a network call inside SQL. Customer to Order/stock authority: Submit stable request and unexpired quote; Order/stock authority to Order/stock authority: Reserve every SKU; persist payment intent/outbox; Order/stock authority to Payment provider: Authorize using original operation key; Payment provider to Order/stock authority: Timeout means unknown; query same operation; Order/stock authority to Dispatcher: Dispatch only after confirmed payment and valid stock; Dispatcher to Order/stock authority: Conditional courier and order assignment; Order/stock authority to Customer: Return tracked order state and version

Checkout saga without a network call inside SQL.

Select couriers by nearby eligible cells, filter capacity and freshness, then score estimated road ETA, current workload and assignment fairness. Straight-line distance is a cheap candidate filter, not an ETA. Expand the radius if no suitable courier accepts. For the baseline, one database transaction locks the order and courier rows and changes both from unassigned/available to assigned. This makes the two-resource invariant explicit. Split authorities need a reservation coordinator; this baseline does not pretend two independent cache writes are atomic.

Order saga transitions and compensation. Stock held / Payment success before deadline / Paid; emit dispatch task; Payment unknown / Late provider success after stock expired / Refund pending; do not dispatch; Dispatching / Offer accept with current order/courier version / Assigned; reject competing acceptance; Assigned / Courier disconnect / Track uncertainty; reassign only after old ownership revoked; Delivered / Duplicate completion / Return original completion; no second settlement
Order saga transitions and compensation.
Read the diagram

Current state / Accepted event / Result; Stock held / Payment success before deadline / Paid; emit dispatch task; Payment unknown / Late provider success after stock expired / Refund pending; do not dispatch; Dispatching / Offer accept with current order/courier version / Assigned; reject competing acceptance; Assigned / Courier disconnect / Track uncertainty; reassign only after old ownership revoked; Delivered / Duplicate completion / Return original completion; no second settlement

Open original
Order saga transitions and compensation
Order saga transitions and compensation. Stock held / Payment success before deadline / Paid; emit dispatch task; Payment unknown / Late provider success after stock expired / Refund pending; do not dispatch; Dispatching / Offer accept with current order/courier version / Assigned; reject competing acceptance; Assigned / Courier disconnect / Track uncertainty; reassign only after old ownership revoked; Delivered / Duplicate completion / Return original completion; no second settlement

Order saga transitions and compensation.

Offer acceptance returns 409 with the current order status when ownership changed. GET /orders/id returns state, version, courier freshness and a cursor for durable progress events. Manual repair uses a privileged command with actor/reason/version, not direct unlogged row edits. For 10,000 active couriers reporting every five seconds, ingest 2,000 location updates/s; keep this path separate from checkout's transactional stock load.

Exercise: Courier C is offered orders O1 and O2 and accepts both after a disconnect. Which commits?

Show answer and explanation

Answer: The first transaction claiming C and its order wins. The second reads C already assigned and returns conflict. A timeout is resolved by querying the same offer ID. Reassignment increments the ownership version so delayed acceptance cannot reclaim an order.

Requirement trace and verification

RequirementImplementing design blockVerification link
R1 — Complete the primary user journey within the stated scope.P01–P04; P09–P10.V1 — Exercise the successful journey and the excluded/boundary case stated in the scope.
R2 — Preserve the problem's authoritative data invariant under concurrency.P05–P06; P11–P12; DD1.V2 — Run the race/replay case below and assert the invariant at the durable authority.
R3 — Meet the declared scale and API behavior without unbounded work.P05–P08; P13–P14; relevant overload deep dives.V3 — Exercise the API errors/retry identity and recompute the workload assumption that drives partition or capacity.
R4 — Recover from the named failure without losing or duplicating the user-visible outcome.P15–P16; deep dives; Operations contract.V4 — Run concurrent orders for the final unit and inject payment timeout; stock never becomes negative and compensation runs once.

Operational contract

AreaDecision and signals
SLIsOrder acceptance latency; reservation conflicts; dispatch age; stale-location fraction; compensation age.
Overload limitsCap geospatial candidates, route-time calls, city queue depth, and payment attempts in flight.
RecoveryReconcile unknown payment, release expired inventory holds, and reassign only through a new fenced offer.
Access controlsScope orders to the customer; restrict exact address and courier location to authorized workflow actors.
Dominant costMap/routing provider calls and high-volume location writes.

Senior-level interviewer follow-ups

Question: A restaurant accepts an order but inventory changes before payment completes. What is the recovery rule?

Show answer and explanation

Answer: Create a short-lived inventory hold before confirming checkout, then commit or release it idempotently. If the hold cannot be renewed, cancel or offer an explicit substitution; do not silently charge for unavailable items.

Question: A courier accepts two nearby jobs at nearly the same time. Where is exclusivity enforced?

Show answer and explanation

Answer: Serialize assignment at the authoritative courier or dispatch owner with a conditional state transition and generation. Geospatial search only creates candidates; it cannot reserve a courier.

A 60-second design answer

I would treat restaurant inventory, payment, and courier dispatch as separate authorities connected by a durable order state machine. A quote and inventory hold protect checkout, idempotency protects retries, and dispatch uses a conditional courier assignment after approximate nearby search. I would expose each transition to support staff and measure quote expiry, unassigned orders, hold leakage, and delivery lateness.

Proximity Search Kafka

Technical references

Provider idempotency contract example.

PostgreSQL transaction isolation and concurrent updates.

Reserve the whole cart at one warehouse

Suppose warehouse W1 has apple quantity 3 and milk quantity 1. Cart K7 needs two apples and two milk. Availability search may show W1, but the authoritative transaction rejects K7 because milk is insufficient; apple quantity remains 3. Another cart K8 needing one of each can succeed atomically, leaving apple 2 and milk 0. Lock/update item keys in a declared order to avoid avoidable deadlock.

Contract / pseudocode
W1 before: apple=3; milk=1
K7 needs apple=2,milk=2 -> reject all; unchanged
K8 needs apple=1,milk=1 -> commit; apple=2,milk=0
W1 before: apple=3; milk=1; K7 needs apple=2,milk=2 -> reject all; unchanged; K8 needs apple=1,milk=1 -> commit; apple=2,milk=0
Reserve the whole cart at one warehouse
Read the diagram

W1 before: apple=3; milk=1; K7 needs apple=2,milk=2 -> reject all; unchanged; K8 needs apple=1,milk=1 -> commit; apple=2,milk=0

Open original
Reserve the whole cart at one warehouse
W1 before: apple=3; milk=1; K7 needs apple=2,milk=2 -> reject all; unchanged; K8 needs apple=1,milk=1 -> commit; apple=2,milk=0

Reserve the whole cart at one warehouse

Use geographic pruning to find nearby warehouses, then a bounded travel-time evaluation; distance alone does not guarantee road accessibility or delivery SLA. Cache browse availability under a freshness contract, but reserve stock at the owner. Payment timeout leaves an uncertain operation linked to the order/hold; expiry and compensation use those identities rather than whichever warehouse happens to be cached later.

Show answer and explanation

Answer: Partial apple reservation for failed K7 violates all-or-nothing cart semantics. State if a product intentionally permits split fulfillment; that is a different contract and coordination cost.

Decision review: Local Delivery Service

Local Delivery Service: What it is

A delivery design selects a feasible store, reserves the cart and assigns a courier through separate business authorities.

Local Delivery Service: Why it is needed

Approximate browsing and ETA do not guarantee stock, while a location snapshot does not reserve a courier.

Local Delivery Service: When to use it

Use candidate discovery for shopping, then authoritative inventory and assignment transitions at checkout and dispatch.

Local Delivery Service: How to use it

Bind a stable order to an atomic cart reservation where all-or-nothing is required. Request payment and courier assignment under explicit retry/compensation rules rather than pretending they share one local transaction.

Local Delivery Service: Compare an alternative

Allowing substitutions or partial cart fulfilment changes the reservation contract. A nearest store may be worse than a farther store with all items and a better route ETA.

Local Delivery Service: Worked decision exercise

The following inputs and policies are original exercise assumptions; they are not measurements or undisclosed company behavior.

The cart needs item A and B. Store S1 is nearby but B is unavailable; S2 has both. A cache that still lists B at S1 cannot authorize checkout. Two dispatchers seeing courier C nearby still need one exclusive assignment.

Local Delivery Service: Cart needs A and B; nearest S1 lacks B; Candidate S2 has both; checkout rechecks stock; Reserve cart under order o7 identity; Courier C assignment needs its own authority
Local Delivery Service: a concrete state and recovery trace under the exercise assumptions.
Read the diagram

Cart needs A and B; nearest S1 lacks B; Candidate S2 has both; checkout rechecks stock; Reserve cart under order o7 identity; Courier C assignment needs its own authority

Open original
Local Delivery Service: worked example
Local Delivery Service: Cart needs A and B; nearest S1 lacks B; Candidate S2 has both; checkout rechecks stock; Reserve cart under order o7 identity; Courier C assignment needs its own authority

Local Delivery Service: a concrete state and recovery trace under the exercise assumptions.

If payment succeeds but courier assignment fails, should the order instantly be marked delivered or cancelled?

Show answer and explanation

Answer: Neither follows from those facts. Persist the partial state and use the agreed retry, replacement, timeout or refund policy. Reconcile the payment identity before issuing another charge, and release inventory only when its reservation policy permits.

Local Delivery Service: Check the design

Monitor reservation conflicts, ETA freshness, unassigned paid orders and compensation age. Test lost replies at stock, payment and assignment boundaries independently.

Screenshot variant: Food delivery from order to courier

The restaurant scenario adds preparation and merchant acceptance that a grocery/warehouse design does not automatically cover. Clarify restaurant acceptance timeout, payment authorization, item unavailability, customer cancellation and whether couriers may batch orders. Start with placed -> restaurant_accepted -> preparing -> ready -> picked_up -> delivered, with explicit rejected/cancelled branches.

Model food_order(id,restaurant_id,customer_id,quote_version,state,version), payment(order_id,provider_key,state), preparation(order_id,estimated_ready_at,version) and assignment(order_id,courier_id,generation,state). POST /food-orders stores an immutable quote and request identity; merchant acceptance and courier acceptance are different authenticated APIs. A courier assignment does not imply that the restaurant accepted or prepared the order.

Assume 100,000 orders/day: about 1.16/s average, with a 100x meal burst around 116/s. At 30 minutes in progress, that burst can imply roughly 209,000 concurrent active orders if sustained. Driver GPS updates and merchant hot spots may exceed order-create traffic. Bound dispatch by city and restaurant readiness rather than initiating unlimited country-wide offers.

Authorize payment under policy, obtain restaurant acceptance, estimate readiness and dispatch a courier near the pickup window. Persist transitions and outbox events together. Version readiness updates so late preparation events cannot move the state backward. Courier offers expire; conditional order/courier claims prevent two active assignments. Reassignment requires a new generation and clear pickup custody rules.

Example: the restaurant accepts O1 and estimates ready at 12:20. At 12:15 it delays to 12:35. Dispatch adjusts unaccepted offers and updates an assigned courier under policy rather than creating another order. A late accept from an expired offer is rejected. If the restaurant rejects after payment authorization, persist cancellation and release/void work; uncertain provider results remain pending reconciliation.

Show answer and explanation

Answer: If the courier disappears after pickup, reassigning the same order as if food were still at the restaurant is incorrect. Track pickup evidence and custody; trigger support/recovery policy and compensation as required. Monitor merchant acceptance/preparation delay, assignment age, ready-to-pickup time, cancellation reasons and payment uncertainty. Test restaurant rejection, delayed readiness, duplicate accepts and courier failure both before and after pickup.

Deep dive: reassignment changes an offer, not physical custody

The existing store/basket and restaurant variants already separate stock, payment and dispatch authority. This workshop makes preparation revisions, physical pickup, cancellation and delivery evidence explicit. The baseline remains one city, one merchant/order and one exclusive courier assignment; pooled routes or cross-authority assignment require a separate capacity/coordination design.

Model commercial state, preparation and custody separately

An accepted order stores the immutable basket, quote/address snapshot and request identity. Restaurant acceptance, readiness estimate, courier assignment, pickup custody, delivery proof and payment outcomes are independent facts. Do not collapse them into one latest-arrival enum.

Contract / pseudocode
order(id, customer, merchant, quote_version, basket_hash, address_version,
      commercial_state, state_revision, cancellation_id)
preparation(order_id, revision, accepted, estimated_ready, actual_ready)
assignment(order_id, courier_id, generation, offer_id, state, expires_at)
custody(order_id, state, generation, pickup_operation, holder, evidence)
handoff(id, order_id, source_courier, target_courier, generation, state)
delivery_proof(order_id, assignment_generation, operation_id, evidence,
               verification_state, customer_dispute_state)
compensation(order_id, operation_id, payment_ref, reason, state)

Bind actor permissions to each operation: merchants cannot forge customer cancellation, couriers cannot change quoted prices, and a customer location ID cannot grant another account's address access. Scope retry keys to authenticated actor/order/operation and canonical payload. A response means the recorded stage completed; it does not imply the whole delivery succeeded.

Revision preparation without duplicating dispatch

Merchant revision 7 estimates ready at 12:20; revision 8 moves to 12:35. A delayed revision 7 must not revert the estimate or launch another assignment. Track estimate revision separately from actual-ready evidence and commercial cancellation. Replanning may delay unaccepted offers or notify an already assigned courier under policy; it must not invent a second order, charge or exclusive assignment.

A merchant rejecting before acceptance follows its defined stock/payment compensation. A later inability to fulfill after preparation is a different cancellation reason/cost boundary. Substitution changes basket, price, allergens or delivery promise: create a versioned customer-approved proposal where required, then atomically reconcile changed inventory/quote/payment eligibility. Do not silently overwrite the accepted order. Failed approval leaves the previous agreement or an explicit cancelled outcome.

Arbitrate pickup and cancellation at the custody boundary

An exclusive assignment uses current offer and generation at the order/courier authority. Acceptance replay returns its original receipt. Expired/stale offers cannot reclaim a newer assignment. Before pickup, reassignment can revoke the old generation and release the matching courier capacity under the baseline transaction; this requires proof that custody has not moved.

Pickup is a guarded business command with merchant/order/current-courier evidence, expected assignment generation and stable operation ID. Serialize it against cancellation/reassignment. If cancellation wins before pickup, reject old pickup and keep its cancellation/compensation path. If pickup wins, a later cancellation cannot pretend the goods remain at the merchant: keep physical custody and route the return/support/disposal policy explicitly.

Delivery custody recovery: courier C1 picks up under generation 4; C1 becomes unreachable; dispatch proposes another ordinary offer; custody guard refuses reset to merchant; recover through a recorded handoff or support case
An unreachable courier still may hold the goods.
Read the diagram

C1 picks up under assignment generation 4 → Courier C1 becomes unreachable → Dispatch proposes an ordinary new offer → Custody guard refuses reset to merchant → Recover via verified handoff or support

Open original
Local Delivery Service: recovery decision
Delivery custody recovery: courier C1 picks up under generation 4; C1 becomes unreachable; dispatch proposes another ordinary offer; custody guard refuses reset to merchant; recover through a recorded handoff or support case

An unreachable courier still may hold the goods.

A timeout, GPS disappearance or expired worker lease cannot reverse physical pickup. Track uncertain pickup evidence and investigate before ordinary reassignment. If remote pickup evidence could still be valid under the original authorization, fence new commands and reconcile the original operation rather than claiming the parcel never moved. Business command fencing cannot retract food already handed to a courier.

Transfer custody with explicit handoff evidence

If C1 physically hands the order to C2, create a handoff identity bound to both couriers, order, old custody generation and required acknowledgment/proof policy. Pending handoff does not authorize two independent pickups. Commit the new holder only after the declared evidence is verified, advance custody/assignment generation and retain the original transfer receipt. Replayed or conflicting handoff messages cannot duplicate goods, erase uncertainty or reset custody to the merchant.

If both parties cannot confirm, preserve an unresolved custody/support case with bounded escalation; a system cannot manufacture physical proof from a row update. Handoffs across independent operational authorities need an explicit decision protocol and recovery owner, analogous to the ride-matching extension. Capacity reflects active custody/return work rather than freeing a courier merely because its old offer expired.

Separate delivered claims, verification and disputes

A courier's delivered command is a claim with actor, generation and stable proof identity. Verify the permitted evidence—such as recipient confirmation or an approved exception—under the product's privacy/access policy. GPS proximity alone does not establish that the correct customer received the parcel. A photograph may contain sensitive information and does not automatically resolve a dispute; store minimal scoped evidence with retention and access controls.

Only a current authorized custody holder may submit completion. Reject stale couriers after a verified handoff. Deduplicate accepted proof/transition identity and keep fulfillment, customer acknowledgment, payment capture/payout and dispute status distinct. A dispute arriving after delivered does not delete the original proof or silently rerun fulfillment. It creates a controlled support/compensation workflow with original monetary identities.

Cancellation or refund after pickup may resolve the commercial relationship while goods remain in return custody. Expose both states rather than marking the courier available and the order back at the restaurant. Record stock release/return policy separately: prepared food or damaged goods need not become sellable inventory. A late successful charge after cancellation reconciles against the original payment; a fresh payment key is another operation.

Bound readiness, location, dispatch and recovery work

At 116 orders/s sustained for 1,800 seconds, about 208,800 concurrent in-progress orders follow Little's Law under stable mean-duration assumptions. That is not evidence of 208,800 ready courier slots; readiness, travel time, exclusivity, capacity and abandonment change the population. Fifty thousand couriers reporting every five seconds generate 10,000 location writes/s; at 200 bytes/update this is 2 MB/s before overhead and 172.8 GB/day if every raw point is retained.

Use finite location retention and separate ingestion from transactional pickup/cancel authority. Bound candidate/ETA evaluations, offer waves, per-merchant ready queues and retry/reconciliation work over the full order deadline. A 30,000-case support/uncertain-custody backlog with 80/s capacity and 50/s fresh cases takes at least 1,000 seconds to drain, before investigative delays; adding dispatch workers cannot prove missing physical outcomes.

Track preparation revision lag, paid-unassigned age, ready-to-pickup delay, custody uncertainty, handoff/proof conflicts and compensation age. Test duplicate pickup replies, cancellation on each side of pickup, late readiness, courier loss after pickup and stale delivery after handoff. Rollback disables new policy paths while preserving current custody and monetary evidence; it cannot restore physical inventory by reverting a database snapshot.

Delivery assessment: preserve the physical truth

Question: The assigned courier disappears after pickup. Can the order return to ready and be offered as another merchant pickup?

Show answer and explanation

Answer: No. Preserve custody and invoke verified handoff, return or support recovery. Location loss is not proof that goods returned.

Question: Pickup and cancellation race. May both be acknowledged as if pickup never happened?

Show answer and explanation

Answer: No. Serialize the authorization boundary. Cancellation first rejects pickup; pickup first preserves custody and changes the cancellation recovery policy.

Question: A stale courier submits proof after a verified handoff to another courier. Should the newest-arriving proof mark delivered?

Show answer and explanation

Answer: No. Require current holder/generation and approved evidence. Preserve old claims for investigation without regressing custody or duplicating completion.

Score one point for independent scoped commercial/preparation/custody facts, monotonic readiness and approved substitutions, pickup/cancel/reassign arbitration, evidence-based handoff/completion with dispute privacy, and finite operational/recovery capacity. Compare Ride Matching, Checkout and Outbox and Sagas.

Your study notes