When a rider taps "Request", a dispatch system has a few seconds to answer three questions: which drivers are nearby, who gets the offer, and what happens when two of them accept at the same moment.

This post builds a small but realistic dispatch loop with Redis for driver locations and PostgreSQL for trip state. It is not a production system, but every piece maps to something real ride-hailing apps have to get right.

The dispatch loop

1. Keep a live index of available drivers

Every online driver app sends its position every few seconds. We only need the latest point per driver for matching, so a Redis geo set per vehicle type is enough:

import redis, time r = redis.Redis() def update_location(driver_id: str, vehicle_type: str, lon: float, lat: float, available: bool): key = f"drivers:{vehicle_type}" if available: r.geoadd(key, (lon, lat, driver_id)) r.hset("driver:last_seen", driver_id, int(time.time())) else: r.zrem(key, driver_id) # a geo set is a sorted set underneath 

Two details that bite later:

  • Stale positions. A phone that loses signal stops sending, but its last point stays in the set. Store a last-seen timestamp and skip drivers older than, say, 30 seconds.
  • Status changes. Remove a driver from the set the moment they accept a trip, not when the trip starts. Otherwise they keep receiving offers on the way to a pickup.

2. Search in rings, not one big circle

A small radius keeps pickups short but may find nobody. A large radius always finds someone, often on the other side of a river. The common compromise is rings: search close first, widen only if nobody accepts.

RINGS_KM = [2.0, 5.0] MAX_AGE_S = 30 def candidates(vehicle_type: str, lon: float, lat: float, radius_km: float, exclude: set[str]): hits = r.geosearch( f"drivers:{vehicle_type}", longitude=lon, latitude=lat, radius=radius_km, unit="km", sort="ASC", count=20, withdist=True, ) now = int(time.time()) out = [] for member, dist_km in hits: driver_id = member.decode() seen = r.hget("driver:last_seen", driver_id) if driver_id in exclude or not seen or now - int(seen) > MAX_AGE_S: continue out.append((driver_id, dist_km)) return out 

This is straight-line distance. It is free to compute and good enough to build a short list. If you want to rank by real driving time, call a routing or matrix API only for those few candidates, never for every driver in the city. That is also where most of a map API bill comes from.

3. Make trip assignment atomic

The bug every dispatch system meets eventually: two drivers tap "Accept" within a few milliseconds of each other, and both think they got the trip.

The fix is to let the database decide, with one conditional update:

CREATE TABLE trips ( id bigserial PRIMARY KEY, status text NOT NULL DEFAULT 'searching', -- searching | assigned | cancelled | ... driver_id text, assigned_at timestamptz ); -- Only one of two concurrent accepts can match status = 'searching' UPDATE trips SET status = 'assigned', driver_id = $2, assigned_at = now() WHERE id = $1 AND status = 'searching' RETURNING id; 

If the statement returns a row, that driver won. If it returns nothing, the trip was already taken or cancelled, and the app should show "This trip is no longer available". No locks in application code, no "check then write" race.

The same pattern protects every transition in the trip state machine: arrived only from assigned, started only from arrived, and so on. Most of the strange bugs in ride apps (double charges, drivers paid for cancelled trips) come from transitions that were not guarded this way.

4. Run offer rounds with a countdown

Now the loop itself. Each round offers the trip to a few candidates, waits for an accept or a timeout, and moves to the next ring if nobody bites.

import asyncio OFFER_TIMEOUT_S = 15 OFFERS_PER_ROUND = 3 async def dispatch(trip_id: int, vehicle_type: str, lon: float, lat: float): offered: set[str] = set() for radius in RINGS_KM: pool = candidates(vehicle_type, lon, lat, radius, exclude=offered) while pool: batch, pool = pool[:OFFERS_PER_ROUND], pool[OFFERS_PER_ROUND:] ids = [d for d, _ in batch] offered.update(ids) await push_offer(trip_id, ids, expires_in=OFFER_TIMEOUT_S) winner = await wait_for_assignment(trip_id, timeout=OFFER_TIMEOUT_S) await close_offers(trip_id, ids, winner) if winner: return winner await mark_no_driver_found(trip_id) return None 

wait_for_assignment can simply poll the trip row or subscribe to a Redis channel that the accept endpoint publishes to after the atomic UPDATE succeeds. close_offers tells the losing drivers' apps to remove the offer screen. Skip it and they keep tapping a dead button.

5. Choose an offer strategy on purpose

The loop above offers to three drivers at a time, nearest first. Changing that one decision changes how the marketplace feels:

Strategy Good at Cost
Nearest first, one at a time Short pickups, easy to explain Slow when drivers decline; nearest drivers get most work
Broadcast to everyone in the ring Fast acceptance in busy areas Drivers race; quieter drivers get little work
Balanced rounds (least work so far first) Spreads earnings, helps keep drivers Slightly slower
Batched matching Best total pickup times at high volume Complexity, added delay, needs volume

A balanced variant is a small change: sort the pool by today's completed trips before slicing the batch, then fall back to distance. In a new market with few drivers, speed matters most. Once supply exceeds demand, fairness keeps drivers from leaving.

6. Edge cases worth a test each

  • The rider cancels while an offer round is running: the atomic update must fail for any accept that arrives afterwards.
  • A driver accepts, then loses connectivity: decide how long before the trip goes back to searching.
  • The same driver appears in two concurrent searches: mark them as "offered" in Redis with a short expiry, so they don't get two offers at once.
  • Scheduled bookings: use longer timeouts and wider rings, because there is time.

Wrapping up

A dispatch loop is mostly bookkeeping: a fresh location index, a bounded search, guarded state transitions and clear timeouts. The clever parts, like batching or demand prediction, only pay off once the boring parts are correct.

If you want the non-code version, with offer strategies, radius trade-offs and more edge cases, there is a longer write-up on how ride-hailing matching works.

This post was drafted with AI assistance (Claude). The code is a simplified illustration, not production code. #abotwrotethis