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

Backend Development
8 min read

Java Food Delivery Dispatch: Ensuring Exactly-Once Order Assignment with Atomic Updates

This article details building a production-ready food delivery auto-dispatch system using Java 21, Spring Boot, Redis GEO, PostgreSQL, and RabbitMQ, covering rider location tracking, multi-factor scoring, atomic database updates with versioning for concurrency control, timeout handling via delayed messages, and transactional outbox pattern for reliable messaging.

Food delivery auto-dispatch appears simple but involves complex real-time scheduling. This article implements a production-grade system using Java 21, Spring Boot, Redis GEO, PostgreSQL, and RabbitMQ.

1. Auto-Dispatch: More Than Finding the Nearest Rider

Dispatch decisions consider multiple factors beyond distance: rider distance, active order count, current delivery direction, merchant preparation time, estimated delivery time, historical acceptance rate, online status, and remaining capacity.

Rider Distance : Estimate arrival time at merchant

Active Order Count : Avoid rider overload

Current Delivery Direction : Determine if new order is on the way

Merchant Preparation Time : Reduce rider waiting

Estimated Delivery Time : Lower order timeout probability

Historical Acceptance Rate : Reduce invalid dispatches

Online Status : Exclude unavailable riders

Remaining Capacity : Judge if rider can accept more orders

Version 1 uses Redis GEO for nearby search and Java for composite scoring, deferring complex AI scheduling.

2. Using Redis GEO for Real-Time Nearby Rider Search

Rider locations change constantly; writing every update to a relational database would cause excessive load. Redis GEO stores real-time positions while PostgreSQL persists orders and relationships. The RiderLocationService updates locations and searches within 3 km for up to 50 riders. Additional filtering by heartbeat, status, and capacity is required. In production, GEO keys can be sharded by city and delivery zone.

@Service
@RequiredArgsConstructor
public class RiderLocationService {
    private final StringRedisTemplate redisTemplate;
    private static final String GEO_KEY = "rider:location:online";
    public void updateLocation(String riderId, double longitude, double latitude) {
        redisTemplate.opsForGeo().add(GEO_KEY, new Point(longitude, latitude), riderId);
    }
    public List<String> findNearbyRiders(double longitude, double latitude) {
        var result = redisTemplate.opsForGeo().search(
            GEO_KEY,
            GeoReference.fromCoordinate(longitude, latitude),
            new Distance(3, Metrics.KILOMETERS),
            RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().sortAscending().limit(50)
        );
        if (result == null) return List.of();
        return result.getContent().stream()
            .map(item -> item.getContent().getName())
            .toList();
    }
}

3. Implementing Rider Scoring Algorithm in Java

A RiderCandidate record holds riderId, distanceKm, activeOrders, routeMatchRate, and acceptRate. The DispatchScoreCalculator computes a weighted score: distance (35%), load (30%), route match (25%), acceptance rate (10%). An example with four riders shows how a slightly farther rider with fewer orders and better route match can outscore the closest rider.

public record RiderCandidate(
    long riderId,
    double distanceKm,
    int activeOrders,
    double routeMatchRate,
    double acceptRate
) {}
public class DispatchScoreCalculator {
    public double calculate(RiderCandidate rider) {
        double distanceScore = 100.0 / (1 + rider.distanceKm());
        double loadScore = Math.max(0, 100 - rider.activeOrders() * 20);
        double routeScore = rider.routeMatchRate() * 100;
        double acceptScore = rider.acceptRate() * 100;
        return distanceScore * 0.35 + loadScore * 0.30 + routeScore * 0.25 + acceptScore * 0.10;
    }
    public List<RiderCandidate> rank(List<RiderCandidate> riders) {
        return riders.stream()
            .sorted(Comparator.comparingDouble(this::calculate).reversed())
            .toList();
    }
}

Example Scoring Results

Rider A : Distance 0.3 km, Active Orders 4, Route Match 30%, Score 50.92

Rider B : Distance 0.8 km, Active Orders 1, Route Match 90%, Score 75.44

Rider C : Distance 1.2 km, Active Orders 0, Route Match 70%, Score 72.91

Rider D : Distance 0.5 km, Active Orders 3, Route Match 50%, Score 56.83

Weights should be continuously tuned from real data and made dynamically configurable for peak hours, weather, and zones.

4. The Core Concurrency Challenge: Duplicate Order Assignment

The hardest part is guaranteeing an order is never assigned to two riders simultaneously. A scenario: order dispatched to rider A with 15s timeout; if A doesn't respond, system re-dispatches to rider B. But if A clicks accept exactly during re-dispatch, both might succeed. A simple Redis lock cannot detect stale dispatch requests. The solution: assign an incrementing dispatch_version per dispatch; rider must submit this version; database atomic update confirms acceptance.

Dispatch process diagram showing multiple dispatch attempts and rider acceptance race condition
Dispatch process diagram showing multiple dispatch attempts and rider acceptance race condition

5. Atomic Database Updates for Dispatch

The delivery_order table includes status, dispatch_version, dispatch_deadline, and an index on dispatch_deadline for OFFERED orders. The DispatchService.dispatch method uses a single SQL statement with WHERE clauses checking status = 'WAITING' and expected version, then updates rider, status, version, and deadline atomically. RETURNING dispatch_version provides the new version. If zero rows updated, dispatch failed due to concurrent change or stale version. This also prevents delayed scheduling messages from triggering duplicate dispatches after retries.

@Service
@RequiredArgsConstructor
public class DispatchService {
    private final JdbcTemplate jdbcTemplate;
    private final DispatchEventService eventService;
    @Transactional
    public Optional<Long> dispatch(long orderId, long riderId, long expectedVersion) {
        String sql = """
            UPDATE delivery_order
            SET rider_id = ?,
                status = 'OFFERED',
                dispatch_version = dispatch_version + 1,
                dispatch_deadline = clock_timestamp() + INTERVAL '15 seconds',
                updated_at = clock_timestamp()
            WHERE id = ?
              AND status = 'WAITING'
              AND dispatch_version = ?
            RETURNING dispatch_version
            """;
        List<Long> versions = jdbcTemplate.query(sql, (rs, rowNum) -> rs.getLong(1), riderId, orderId, expectedVersion);
        if (versions.isEmpty()) return Optional.empty();
        long version = versions.getFirst();
        eventService.save(orderId, riderId, version, "DISPATCH_CREATED");
        return Optional.of(version);
    }
}

6. Rider Acceptance: Validating Four Conditions Simultaneously

The acceptOrder method first locks the order row with SELECT ... FOR UPDATE to prevent deadline changes during validation. Then it attempts an atomic update requiring: matching orderId, riderId, dispatch_version, status = 'OFFERED', and dispatch_deadline > clock_timestamp(). Using PostgreSQL's clock_timestamp() avoids clock skew across service instances. If update succeeds, an event is recorded. If update fails (e.g., deadline passed), a final check returns true if the order is already in ACCEPTED, PICKED_UP, or DELIVERED for that rider and version, handling duplicate requests due to network retries. Rider ID must come from authenticated context, not client input.

@Transactional
public boolean acceptOrder(long orderId, long riderId, long version) {
    List<Long> locked = jdbcTemplate.query(
        """SELECT id FROM delivery_order WHERE id = ? FOR UPDATE""",
        (rs, rowNum) -> rs.getLong(1), orderId);
    if (locked.isEmpty()) return false;
    int updated = jdbcTemplate.update(
        """
        UPDATE delivery_order
        SET status = 'ACCEPTED',
            accepted_at = clock_timestamp(),
            updated_at = clock_timestamp()
        WHERE id = ?
          AND rider_id = ?
          AND dispatch_version = ?
          AND status = 'OFFERED'
          AND dispatch_deadline > clock_timestamp()
        """,
        orderId, riderId, version);
    if (updated == 1) {
        eventService.save(orderId, riderId, version, "DISPATCH_ACCEPTED");
        return true;
    }
    return Boolean.TRUE.equals(jdbcTemplate.queryForObject(
        """SELECT EXISTS (SELECT 1 FROM delivery_order WHERE id = ? AND rider_id = ? AND dispatch_version = ? AND status IN ('ACCEPTED','PICKED_UP','DELIVERED'))""",
        Boolean.class, orderId, riderId, version));
}

7. Automatic Re-Dispatch on Rider Timeout

Creating a Java timer per order wastes memory and loses tasks on restart. Instead, RabbitMQ delayed messages trigger timeout checks, backed by a database scan for compensation. The expireDispatch method atomically resets status to WAITING, clears rider and deadline, but only if dispatch_version matches and status = 'OFFERED' and deadline passed. This competes with acceptOrder: if rider accepts first, timeout update affects zero rows; if timeout fires first, rider's accept fails version/status check. Retries exclude the timed-out rider and respect a maximum retry limit.

@Transactional
public boolean expireDispatch(long orderId, long version) {
    int updated = jdbcTemplate.update(
        """
        UPDATE delivery_order
        SET status = 'WAITING',
            rider_id = NULL,
            dispatch_deadline = NULL,
            updated_at = clock_timestamp()
        WHERE id = ?
          AND dispatch_version = ?
          AND status = 'OFFERED'
          AND dispatch_deadline <= clock_timestamp()
        """,
        orderId, version);
    if (updated == 0) return false;
    eventService.save(orderId, null, version, "DISPATCH_RETRY");
    return true;
}

8. Ensuring Message Reliability with Transactional Outbox

If the database commits but the service crashes before publishing the RabbitMQ message, the rider never receives the order. The Transactional Outbox pattern solves this: a dispatch_event table stores events within the same transaction. DispatchEventService.save uses Propagation.MANDATORY to enforce participation in the existing transaction. A unique constraint on (order_id, dispatch_version, event_type) prevents duplicates. A separate publisher reads pending events, sends via RabbitMQ with publisher confirms, retries on failure, and marks sent. Consumers must be idempotent using message ID or order version.

CREATE TABLE dispatch_event (
    id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    order_id BIGINT NOT NULL,
    rider_id BIGINT,
    dispatch_version BIGINT NOT NULL,
    event_type VARCHAR(64) NOT NULL,
    status VARCHAR(16) NOT NULL DEFAULT 'PENDING',
    retry_count INT NOT NULL DEFAULT 0,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(order_id, dispatch_version, event_type)
);

@Service
@RequiredArgsConstructor
public class DispatchEventService {
    private final JdbcTemplate jdbcTemplate;
    @Transactional(propagation = Propagation.MANDATORY)
    public void save(long orderId, Long riderId, long version, String eventType) {
        jdbcTemplate.update(
            """
            INSERT INTO dispatch_event (order_id, rider_id, dispatch_version, event_type)
            VALUES (?, ?, ?, ?)
            ON CONFLICT (order_id, dispatch_version, event_type) DO NOTHING
            """,
            orderId, riderId, version, eventType);
    }
}
Transactional outbox pattern diagram
Transactional outbox pattern diagram

9. Production Architecture Overview

Java 21 : Core business and scheduling logic

Spring Boot : APIs, transactions, business services

Redis GEO : Real-time rider location and nearby search

PostgreSQL : Order state, version control, transactions

RabbitMQ : Async messaging and timeout scheduling

WebSocket : Real-time notifications to online riders

Map Service API : Route planning and ETA estimation

Prometheus : Dispatch success rate, latency, anomaly monitoring

For early-stage platforms, a modular monolith with separate modules for orders, riders, delivery, scheduling, and messaging is sufficient. The article covers the core dispatch flow; a full production system adds rider capacity pre-allocation, order cancellation, historical dispatch records, and manual dispatch overrides.

Conclusion

Food delivery dispatch combines real-time computation, business state machines, concurrency control, message reliability, and dynamic resource scheduling. Redis GEO finds riders fast; Java scoring picks the best candidate; database state machine and versioning prevent duplicate assignments; message queue and outbox ensure reliable execution. These patterns apply to ride-hailing, errand services, home services, repair dispatch, logistics, and after-sales. The true test of a backend engineer is not writing an accept endpoint, but ensuring correctness under network failures, duplicate messages, crashes, and concurrent requests.

For attribution, corrections or content rights, contactadmin@besthub.dev

Report an issue with this article

Discussion 0

Write a comment

Sign in to join the discussion

No public comments on this page. Sign in to comment