Skip to content

System design walkthrough · 12 min

Assigning delivery partners in real time

Every order needs a rider, now, and every rider can take one order at a time. Start with a database query, add a geo index, watch riders get double-booked, and end with batches per zone.

Seen in food delivery, grocery, ride-hailing and courier apps.

The ask

What we are building

When an order is nearly ready, dispatch must pick a rider: close enough to arrive as the food is ready, free right now, and never given two orders by mistake. Design it for dinner in a big city, every few seconds, all night.

  • Each order gets a rider within seconds of needing one.
  • A rider is never given two conflicting orders at once.
  • Choices keep total waiting low (for food, customers and riders), not just distance.
  • Rider positions change every few seconds; decisions must use fresh ones.
  • A rider can decline or go offline; the order must not get stuck.
Orders at peak
~280 a second
Riders online
~330,000
Rider position every
4 s
Time to decide
a few seconds

Back of the envelope

How big is it?

Illustrative numbers, continuing the live order tracking walkthrough.

WhatWorkingResult
Rows read if each order scans all riders280 orders/s × 330,000 riders~92 million a second
Riders within 3 km of a restauranta dense city at dinner~50
Zones per big cityneighbourhood-sized cells~100
New orders per zone per seconda busy zone at peak~2
Batch every ~2 s, per zone~4 orders × ~50 ridersa tiny problem: milliseconds

Build it, then break it

Your turn: design it first

Make the two calls yourself before reading on. The simulator runs your dispatch at lunch, dinner and in the rain, with the same orders and riders as the versions below.

1How do you find the riders near a restaurant?
2Who decides which rider takes an order?

Answer every question to run it.

Version 1

Find the nearest rider with a database query

Breaks · at dinner: scans pile up and orders wait

For each order: SELECT * FROM riders WHERE status = 'free' ORDER BY distance(location, :restaurant) LIMIT 1, then mark that rider busy. One query, easy to read, correct for the first few hundred orders.

The distance has to be computed for every rider on every order, because a plain index cannot sort by distance from an arbitrary point. At dinner that is tens of millions of rows a second on the database that also takes orders and payments. Orders wait for a rider long after the food is ready. And straight-line distance is wrong anyway: the closest rider may be across a river.

Rows read per order
every rider
Distance used
straight line

Try each load. Numbers are illustrative: a small simulation, not a measurement.

Why not…

  • A spatial index in the database?

    Makes 'riders near here' fast, but rider positions change every few seconds: hundreds of thousands of index updates a second, on the main database, for data that is stale in seconds.

  • Let riders pick orders from a list?

    Works for small fleets and some marketplaces, but popular orders get fought over, unpopular ones sit, and nobody optimises the whole city's waiting time.

Go deeper:Shard key choice

Version 2

A geo index, and each order grabs its nearest rider

Breaks · double-books riders from dinner on, worse in the rain

Keep rider positions in an in-memory geo index: the map cut into cells, each listing the riders in it, updated as positions arrive. 'Free riders near this restaurant' becomes a lookup of a few cells, and real road travel time (not straight-line distance) ranks them.

Now many workers assign orders in parallel, each grabbing the best rider for its own order. At dinner, two workers near the same busy restaurant read the same free rider in the same instant and both assign them: one order is quietly left without a rider. Nearest-first is also short-sighted: giving the nearest rider to this order can leave the next order, a minute later, with nobody.

Finding candidates
a few ms
Decisions
racing
Choices
one at a time

Try each load. Numbers are illustrative: a small simulation, not a measurement.

Why not…

  • Lock each rider while deciding?

    Stops double-booking, but workers now queue on the same popular riders and wait on each other; at dinner the locks become the bottleneck. A conditional update (assign only if still free) is a better safety net than a lock.

  • Assign whoever is closest the instant an order appears?

    Simple and fast, but it is the first-come rule that produces long waits for the orders that come next. Looking at a few seconds of orders together does better for everyone.

Go deeper:Optimistic transactions

Version 3

Match each zone in small batches

Holds · at 10× lunch: no rider booked twice

Split the city into zones, each owned by exactly one matcher. Every second or two, the matcher takes its zone's waiting orders and free riders (from the geo index) and assigns them all at once, choosing the combination with the lowest total wait, using predicted food-ready times and road travel times.

One owner per zone means no two decisions can race: double-booking is impossible by construction. Seeing several orders together means better choices: rider A goes to the order that only A can reach in time, instead of to whichever order arrived first.

Each batch is small (a few orders, a few dozen riders), so it solves in milliseconds, and zones run in parallel, so the city scales by adding matchers.

Races
none (one owner)
Choice
whole batch
Extra wait
~1–2 s

Try each load. Numbers are illustrative: a small simulation, not a measurement.

Why not…

  • One batch for the whole city?

    Better choices in theory, but the problem grows with the square of the city and one slow solve delays everyone. Zones keep each solve small and failures local.

  • Longer batches for better matches?

    Each second of batching is a second every order waits. A batch of one to a few seconds catches most of the benefit; the right length is something to test, not guess.

Go deeper:Batching vs latencyConsistent hashing

Harden it

Offers, borders and stale positions

Holds · with timeouts, a conditional update and one owner per zone

Offers, not orders: a rider receives an offer with a short timeout. Declined or expired offers go back into the next batch, so an order never sits on a rider who is not answering.

A safety net anyway: record each assignment with a conditional update (only if the rider is still free and on the version the matcher saw), so a bug or a split-brain matcher cannot double-book silently.

Borders and staleness: riders near a zone border must belong to one zone at a time. Ignore positions older than a few seconds (a rider in a tunnel is not where the map says). If a zone's matcher fails, its zone moves to another one; it must not be matched by two.

Go deeper:Leader election (Raft)Live order tracking (walkthrough)

Putting it together

The final design

Fast candidates from memory, decisions made by exactly one owner per zone, and offers that expire. Batching a second or two trades a little waiting for better choices and no races.

  1. Location ingest

    Takes rider positions every few seconds and updates the geo index.

    Watch out: Positions arrive late or in bursts; drop stale ones rather than trusting them.

  2. Geo index (in memory)

    Riders by map cell, so 'free riders near here' is a few lookups.

    Watch out: It is a cache of reality: rebuild it from the location stream if it is lost.

  3. Road travel time

    Ranks candidates by time to the restaurant on real roads, not straight-line distance.

    Watch out: A slow routing service stalls every match: cache and bound it.

  4. Food-ready prediction

    Estimates when each order will be ready, so riders arrive just in time.

    Watch out: Early riders wait at the restaurant and are unavailable to anyone else.

  5. Zone matcher

    One per zone: every second or two, assigns the batch for the lowest total wait.

    Watch out: Two matchers for one zone after a failover reintroduces races; use leases.

  6. Offer service

    Sends offers with a timeout and returns declined or expired ones to the next batch.

    Watch out: Timeouts too long leave orders waiting on silent phones.

  7. Assignment record

    A conditional update that only succeeds if the rider is still free.

    Watch out: Without it, a bug double-books riders silently.

From boxes to an API

API and data model

Dispatch has two clients with opposite needs: rider apps that send positions often and answer offers quickly, and the matcher, which must never give one rider two orders.

Endpoints

  • POST/v1/riders/me/locationCalled by Rider appPosition every few seconds; updates the in-memory geo index, never the main database.
  • PUT/v1/riders/me/availabilityCalled by Rider appOnline, offline or on a break; a rider who is offline is removed from the geo index at once.
  • POST/v1/dispatch/requestsCalled by Order serviceAn order that will be ready soon, with its predicted ready time; queued for the next batch in its zone.
  • POST/v1/offers/{id}/acceptCalled by Rider appAccepts an offer before it expires. Succeeds only if the offer is still open and the rider still free.
  • POST/v1/offers/{id}/declineCalled by Rider appReturns the order to the next batch straight away instead of waiting for the offer to time out.

Data

  • geo index

    Key: cell:{map cell}

    rider_id, lat, lng, status, updated_at

    In memory, by map cell, so 'free riders near this restaurant' is a few lookups. Rebuilt from rider pings if lost.

  • riders

    Key: rider_id

    rider_id, zone_id, status, active_assignment_id, version

    The durable rider record; the version column lets an assignment succeed only if nothing changed since it was read.

  • offers

    Key: offer_id

    offer_id, order_id, rider_id, expires_at, state

    Each offer once, with an expiry; an expired or declined offer sends the order back to the matcher.

  • assignments

    Key: order_id

    order_id, rider_id, assigned_at; unique active rider_id

    One active assignment per order and per rider, enforced by the database, so a race cannot double-book a rider.

From their own write-ups

How real companies did it

  • Uber describes moving away from matching each rider immediately with the closest driver, which sometimes left others with long waits. It now waits a few seconds so a batch of possible rider-driver pairs accumulates, then pairs them to reduce the average wait for everyone, and notes that closest does not always mean quickest.

    Uber: How matching works (marketplace) ↗
  • Grab's Pharos finds the nearest drivers by driving distance or travel time rather than straight-line distance, with driver positions updated at high frequency (about once a second) and snapped onto road segments. It reports a p99 of 10 ms for a driver update and 50 ms for a nearby-drivers query, and filters out drivers whose positions have expired.

    Grab Engineering: Pharos, searching nearby drivers on road network at scale (2020) ↗
  • Lyft revised its core matching algorithm with an online reinforcement learning approach that estimates drivers' future earnings in real time, so a match accounts for where a driver will be next, not only the current request. Lyft reports rolling it out globally in 2021 and over $30 million a year in incremental revenue.

    Lyft (arXiv): A Better Match for Drivers and Riders, Reinforcement Learning at Lyft (2023) ↗

In the interview

Follow-up questions

A rider declines the offer. What happens to the order, and how long can that take?
The offer has a timeout of a few seconds; a decline or a timeout puts the order back into its zone's next batch, usually with higher priority because it has already waited. Track the time from 'needs a rider' to 'accepted', not just to 'offered', since repeated declines are where orders really get stuck.
A restaurant sits on the border of two zones. Which matcher handles it, and which riders can it use?
Each order and each free rider belongs to exactly one zone at a time, for example the zone of its current cell. Matchers can read candidates from neighbouring cells, but a rider from another zone can only be assigned by asking that zone's owner, or by the conditional update failing safely if both try.
Why not make the batch 30 seconds, for even better matches?
Every order waits for the batch, and riders' positions and food-ready times change within 30 seconds, so the 'better' plan is built on stale data. Short batches capture most of the gain; the length is tuned with experiments on real wait times.

Your turn

Check yourself

In version 2, why are riders sometimes given two orders at once?

What does batching orders for a second or two buy?

Why rank candidate riders by road travel time rather than straight-line distance?

Sources: Uber: How matching works (marketplace) ↗ · Grab Engineering: Pharos, searching nearby drivers on road network at scale (2020) ↗ · Lyft (arXiv): A Better Match for Drivers and Riders, Reinforcement Learning at Lyft (2023) ↗ · Report a problem

A typical design, informed by public write-ups, not any one company's exact system. Diagrams are our own. Numbers are illustrative. All wording is original and paraphrases the linked sources.