Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Real-Time Dispatch System Design: Spring Boot, Redis GEO, Concurrency & Timeout Handling

This article details the design of a real-time ride-hailing dispatch system using Spring Boot, Redis GEO for driver location, two-phase candidate selection, time-bound dispatch invitations, database transaction-based concurrency control for order acceptance, timeout-based redispatch rounds, WebSocket location tracking, and cancellation handling, emphasizing data consistency over raw proximity.

1. Core Data Models: Order, Driver Runtime, Dispatch Offer

The article argues against storing only a driver_id on the order table because that loses the distinction between an invitation sent and an invitation accepted. It proposes three tables:

ride_order : stores order status, dispatch_round, version for optimistic locking, and timestamps.

driver_runtime : tracks driver work_status (AVAILABLE/BUSY), current_order_id, city_id, vehicle_type, and last update time.

dispatch_offer : records each invitation with order_id, driver_id, dispatch_round, status (PENDING/ACCEPTED/REJECTED/EXPIRED/CANCELLED), estimated distance/arrival, expires_at, and responded_at. A unique key on (order_id, dispatch_round, driver_id) prevents duplicate invitations in the same round.

Order statuses: WAITING_DISPATCH, DISPATCHING, ACCEPTED, DRIVER_ARRIVING, IN_PROGRESS, COMPLETED, CANCELLED, NO_DRIVER. Offer statuses: PENDING, ACCEPTED, REJECTED, EXPIRED, CANCELLED. This separation preserves the full dispatch history for auditing and timeout handling.

2. Driver Location Storage: Redis GEO over MySQL

With 20,000 drivers uploading location every 5 seconds (4,000 writes/sec), updating MySQL each time is impractical. The solution uses Redis GEO (GEOADD) keyed by city_id. Driver location updates call

redisTemplate.opsForGeo().add(geoKey, new Point(lng, lat), driverId)

. Passenger requests use GEOSEARCH with FROMLONLAT, BYRADIUS 3 KM, ASC COUNT 50 WITHDIST to retrieve nearest candidates.

Redis GEO members lack TTL, so the system also stores last valid location timestamp, device session, and sequence number. A Lua script atomically checks sequence and updates GEO plus metadata to prevent stale updates. A background job removes expired GEO members after verifying last active time. Importantly, Redis GEO is only a retrieval entry point; driver work_status must be re-verified at assignment time because a driver in the index may already be busy.

3. Two-Phase Driver Selection: Distance vs. ETA

Straight-line distance from Redis GEO can be misleading (e.g., driver on opposite side of a road). The article demonstrates a scenario where driver A is 300m away but 6 min ETA, while driver B is 800m away but 3 min ETA. The solution:

Phase 1 (low-cost recall) : Redis GEO returns top 50 candidates; filter out stale locations, vehicle mismatch, paused drivers, and those already on a trip.

Phase 2 (high-precision ranking) : For the top 10 filtered candidates, call a map routing service to compute actual ETA, then score using a weighted formula: etaScore (65%), distanceScore (15%), idleScore (20%). The scoring function normalizes each factor against caps (900s ETA, 5000m distance, 1800s idle).

Code defines a DriverCandidate record and a DispatchScoreCalculator class. The article notes weights should be continuously tuned based on acceptance rate, wait time, deadhead distance, and fairness.

4. Dispatch as Time-Bound Invitations

Dispatching is not direct assignment but sending an invitation with a TTL (e.g., 15 seconds). The invitation JSON includes offerId, orderId, dispatchRound, estimatedDistance, estimatedArrivalSeconds, expiresAt. The dispatcher creates a dispatch round in a short database transaction: it locks the order (SELECT ... FOR UPDATE), verifies status and version, increments dispatch_round, inserts dispatch_offer rows, and writes outbox events for reliable WebSocket notification. The transactional outbox pattern ensures invitations survive application restarts. The message publisher filters expired offers before sending.

This model supports multiple strategies: sequential single-driver, small-batch simultaneous, or open grab, all reusing the same invitation schema.

5. Concurrency Control: Conditional Updates in a Single Transaction

When multiple drivers tap "accept" simultaneously, the system must guarantee one order → one driver and one driver → one order. The article shows a flawed check-then-update approach and then the correct solution using conditional UPDATE statements inside a single @Transactional method:

Reserve driver:

UPDATE driver_runtime SET work_status='BUSY', current_order_id=?, updated_at=NOW(3) WHERE driver_id=? AND work_status='AVAILABLE' AND current_order_id IS NULL

Accept order:

UPDATE ride_order SET driver_id=?, status='ACCEPTED', accepted_at=NOW(3), version=version+1 WHERE id=? AND status='DISPATCHING' AND dispatch_round=? AND driver_id IS NULL

Mark offer accepted:

UPDATE dispatch_offer SET status='ACCEPTED', responded_at=NOW(3) WHERE id=? AND status='PENDING' AND expires_at > NOW(3)

Cancel other pending offers for the same order.

Insert OrderAcceptedEvent into outbox.

The service method validates offer existence, matching order/driver/round, offer status PENDING, and expiry before attempting the updates. All business exceptions extend RuntimeException to trigger rollback. The author prefers database transactions over Redis distributed locks for core consistency.

6. Timeout Redispatch with Dispatch Rounds

If no driver accepts within the TTL, the system must launch a new round with wider radius and more candidates. Example strategy:

Round 1: 2 km, 3 drivers, 15 sec

Round 2: 5 km, 5 drivers, 15 sec

Round 3: 8 km, 8 drivers, 20 sec

Expired offers are tracked in a Redis Sorted Set (ZADD dispatch:timeout timestamp offerId). A @Scheduled task (every 500ms) scans scores ≤ current time, calls a timeout service, and removes from the set. The timeout service uses a conditional UPDATE to mark the offer EXPIRED only if still PENDING and expired. After all offers in a round are EXPIRED/REJECTED, a transaction locks the order, confirms it is still DISPATCHING with no valid offers, resets status to WAITING_DISPATCH, and triggers the next round.

The dispatch_round field is critical: a late acceptance from round 1 must be rejected when round 2 has started, because the offer's round no longer matches the order's current round. A fallback MySQL scan (status + expires_at index) handles cases where Redis data is lost.

7. Real-Time Location Tracking: WebSocket with Sequence Numbers

After acceptance, the driver continues sending location. The backend distinguishes high-frequency, loss-tolerant location updates from critical business events (accept, arrive, start, complete). Location updates are stored in Redis (latest state) and pushed via Spring's SimpMessagingTemplate to the passenger's WebSocket queue (/queue/ride/location). The DriverLocationEvent record includes orderId, driverId, longitude, latitude, heading, speed, sequence, serverTime.

Clients must compare sequence numbers to discard out-of-order messages (e.g., seq 107 arriving after 108). Sequence numbers are bound to the device session; re-login resets the session epoch. Update frequency can be dynamic: lower while waiting, higher during active trips. For WebSocket clusters, a cross-node message bus routes location events to the instance holding the passenger's connection. Location data is sensitive; subscriptions are stopped when the order ends or is cancelled.

8. Cancellation Concurrency: Unified State Machine and Locking

Passenger cancellation and driver acceptance can race. Both use the same order lock (SELECT ... FOR UPDATE). The cancellation method checks passenger ownership, allows cancellation only in WAITING_DISPATCH or DISPATCHING, updates order status to CANCELLED, cancels all pending offers, and emits OrderCancelledEvent. If cancellation wins the lock, the driver's accept attempt fails because order status is no longer DISPATCHING. If accept wins, cancellation follows the "already accepted" flow (possible fee, driver compensation, release driver). Driver-initiated cancellation after acceptance also runs in a transaction that verifies current_order_id before setting work_status back to AVAILABLE.

9. Deployment Architecture and Operational Metrics

The recommended first-version architecture is a modular Spring Boot monolith with Redis, MySQL, RabbitMQ, and a map service. Components: API/WebSocket gateway, Order Service, Dispatch Service (candidate search, routing, scoring), Location Service. Data stores: MySQL for orders, state machines, offers, outbox; Redis GEO for driver index, timeout sorted set, latest location, heartbeats; RabbitMQ for reliable business events and cross-node notifications.

Beyond technical metrics (latency, CPU), the article stresses business metrics: first-dispatch success rate, average dispatch rounds, passenger wait time, driver pickup time, cancellation rate, offer timeout rate, driver deadhead distance, regional supply-demand. These reveal issues invisible to infrastructure monitoring (e.g., wait time rising due to stale driver locations or poor scoring).

Pre-launch testing should cover: 100 drivers concurrently accepting one order (only one succeeds), one driver accepting two orders (only one succeeds), expired round 1 offer rejected in round 2, passenger cancel vs driver accept race, Redis restart/message redelivery/service crash recovery, delayed location messages not overwriting newer ones.

Conclusion

The core challenge of real-time dispatch is not finding the nearest person but guaranteeing that the right order reaches the right person at the right time under high concurrency. The presented architecture — separating order state, driver state, and invitation state; using Redis GEO for recall and map routing for precision; modeling dispatch as expiring invitations with rounds; enforcing consistency via database conditional updates; and handling timeouts with a dual Redis/MySQL mechanism — applies equally to food delivery, on-demand repair, home services, and can be extended with priority, demand prediction, and ML scoring without changing the consistency foundation.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

System DesignSpring BootMySQLConcurrency ControlWebSocketTimeout HandlingReal-time TrackingRedis GEOdispatch system

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion