Live Courier Tracking and Dispatch Platform

Hard · System Design · Software Engineer · Onsite

Prompt

Architect an end-to-end live courier tracking and dispatch visibility platform used by customers, merchants, city dispatchers, and support teams to follow each driver's real-time street location, planned multi-stop route, and arrival window. Scale the system from tens of thousands of simultaneous on-shift drivers today up to millions of completed deliveries per day.

Your design should address the full lifecycle across mobile clients, streaming pipelines, transactional services, and map viewers:

  • End-to-end topology & paradigm: Lay out mobile apps, viewer clients, API/streaming gateways, backend services, event buses, and persistence layers, explaining why an event-driven pipeline—paired with Command Query Responsibility Segregation (CQRS) between transactional writes and live read views—fits this domain.
  • Courier mobile telemetry, battery & dead zones: Explain how driver phones sample sensors, batch and binary-compress fixes, assign sequence numbers, authenticate hardware/sessions against GPS spoofing, conserve battery over full shifts, and buffer updates offline through tunnels or cellular outages.
  • Stream ingestion & spatial processing: Detail how incoming telemetry is validated, deduplicated across out-of-order replays, smoothed, snapped onto road segments (map matching), checked against stop geofences, and fanned out to subscribers.
  • Routing, ETAs & multi-stop dispatch: Show how routes and arrival estimates are maintained incrementally for both the current leg and queued stops, and how automated dispatch solves multi-stop pickup/drop-off routing with time windows (VRP/TSP heuristics).
  • Order & assignment workflows: Define the data schema and conflict-free mutations for creating orders, assigning or unassigning couriers without double-booking, and advancing delivery states.
  • Live & historical map delivery: Describe how customer tracking screens and multi-courier dispatcher consoles receive live markers and historical trip replays via SSE/WebSockets, vector map tiles, polyline simplification, and zoom-aware update throttling.
  • Multi-tier storage & APIs: Cover hot last-known courier state, time-series trace storage, and cold compliance archives, and sketch REST plus streaming contracts for endpoints such as POST /orders, POST /orders/{id}/assign, POST /couriers/{id}/locations, GET /couriers/{id}/trace, GET /orders/{id}/eta, and GET /orders/{id}/live.
  • Consistency, privacy & reliability: Contrast strong consistency for order/assignment state against eventual consistency for live maps; enforce data minimization, RBAC/ABAC, short-lived tracking URLs, stacked-order coordinate blurring, and retention limits; and specify component failovers, regional disaster recovery, SLOs, golden signals, and synthetic probes.

Scope & Expectations

  • Capacity & consistency boundaries: Back your architecture with concrete throughput, bandwidth, storage-tier, routing-CPU, and open-socket estimates, cleanly separating low-volume strongly consistent order mutations from high-frequency eventually consistent telemetry.
  • Core spatial & algorithmic mechanics: Go beyond box-drawing to explain urban GPS map matching, hysteresis/dwell geofencing, incremental multi-stop ETA updates, bounded-time VRP dispatch, and race-free SQL assignment transactions.
  • Client & viewer constraints: Show how mobile upload cadences respect cellular radio/battery physics and offline gaps, and how map push gateways scale across zoom levels without melting browsers or leaking stacked-delivery addresses.
  • Production readiness: Cover access-control enforcement, graceful degradation when individual stores or routing engines fail, and end-to-end observability.

Step-by-step walkthrough

  1. Clarify requirements and scope

    A live courier tracking and dispatch platform brings together two fundamentally different kinds of data:

    • Orders and assignments are low-volume (~1,000 writes/s at peak) and high-stakes: one order must have at most one active courier, and a completed delivery can never vanish. They require strong consistency (every read immediately sees the latest committed write, enforced by atomic database transactions).
    • GPS locations are high-volume (~100,000 points/s at peak) and perishable: losing one 1-second ping matters far less than stalling the pipeline. They belong on an eventually consistent streaming path (updates propagate asynchronously within a few seconds without locking a central database).

    Keeping these two paths cleanly separated drives almost every architectural decision below.

    Functional requirements

    • Mobile GPS publishing: courier apps collect and upload location fixes while on shift, surviving tunnels and cellular dead zones.
    • Order & assignment lifecycle: create orders, assign/unassign couriers without double-booking, support stacked multi-stop runs (up to 4 active orders per courier), and track state transitions (CREATED -> ASSIGNED -> ACCEPTED -> AT_PICKUP -> PICKED_UP -> AT_DROPOFF -> DELIVERED).
    • Live & multi-stop ETAs: continuously update travel routes and promised arrival windows across the active leg and queued future stops, paired with automated city-level dispatch optimization.
    • Live & historical maps: stream live positions and ETAs to customers, merchants, and multi-city dispatchers, and support full historical route playback for support investigations.

    Non-functional requirements & assumptions

    • Latency: device GPS fix to customer tracking page or street-level dispatcher map p95 < 10 s; order assignment API p99 < 300 ms.
    • Availability: order APIs 99.95%; live map 99.9% (degrading gracefully to "last seen 2m ago" markers rather than failing hard).
    • Scale: ~20,000 concurrent couriers today, designed for 130,000 concurrent couriers (100k on an active job + 30k idle online) and 3 million deliveries/day (5M on holiday peaks).
    • Battery & BYOD: couriers use their own iOS/Android phones over 10-hour shifts (battery efficiency and anti-spoofing both matter) across car, bike, scooter, and walking profiles, with regional data residency (e.g., EU data stays in EU regions).
  2. Back-of-the-envelope numbers and capacity planning

    Let's size throughput, storage tiers, routing compute, and open network sockets at the 130k-courier / 3M-delivery/day target.

    1. Fleet & order write rates
       Daily deliveries             3,000,000 / day (5M holiday peak)
       Active courier-hours         ~2.5 deliveries / active hour -> 1,200,000 on-job courier-hours/day
       Concurrent couriers          Average: 1.2M / 24 = 50k on-job
                                    Dinner peak: 100k on-job + 30k idle online = 130k concurrent couriers
       Active orders at peak        100k couriers x ~1.3 stacked orders/courier = ~130,000 active orders
       Order state writes           ~10 transitions/order -> 30M writes/day (~350/s avg, ~1,000 writes/s peak)
    
    2. Location ingestion bandwidth & QPS
       Sampling rate                On-job: 1 fix/s;  Idle online: <= 1 fix / 15 s
       Raw GPS points at peak       (100k x 1/s) + (30k / 15 s) = ~102,000 points/s (~4.4B points/day)
       Batched HTTP/2 uploads       On-job every 5 s, idle every 30 s -> (100k / 5) + (30k / 30) = 21,000 req/s
       Wire size per batch          5 delta-compressed points x ~12 B + ~100 B header/sig = ~160 B body
                                    -> ~3.4 MB/s payload (~10 MB/s including TLS & HTTP/2 framing)
    
    3. Storage across hot, warm, and cold tiers
       Hot state (Redis)            130k couriers x ~300 B + 130k ETAs x ~100 B = ~52 MB raw (< 250 MB w/ overhead)
       Warm 30-day traces           4.4B pts/day x ~16 B (1-min compressed chunks) = ~70 GB/day
                                    -> 2.1 TB logical for 30 days (x3 replication = ~6.3 TB across SSDs)
       Per-order trip summary       3M orders/day x ~3 KB (matched polyline + timestamps) = 9 GB/day (~3.3 TB/yr)
       Relational orders + events   3M orders/day x ~2 KB = ~6 GB/day (~2.2 TB/yr, partitioned by month/city)
    
    4. Routing CPU & live push sockets
       Worst-case ETA routing       130k active orders / 10 s = 13,000 route queries/s
                                    At ~5 ms/query = 65 CPU-seconds/s -> ~100 cores with headroom
       Concurrent live viewers      ~65k customers (50% watching) + ~20k merchant tablets + ~3k dispatchers = ~88k
                                    -> Provision for 250,000 open sockets across 9 gateway VMs (3 per AZ, 50k/VM;
                                       losing 1 AZ leaves 6 x 50k = 300k capacity)
       Outbound push messages       Customers (1 / 3 s) = ~22k msgs/s; Consoles (1 frame/s) = ~3k frames/s
    

    Three takeaways anchor the design: 1. Network bandwidth is tiny (~10 MB/s), and live fleet state (< 250 MB) fits in one Redis node's RAM. The real work is per-point CPU processing (102k map-matches/s), 250k stateful push connections, and strict assignment correctness. 2. 1,000 order writes/s easily fit on one regional PostgreSQL primary—provided we never write the 102k/s location stream into PostgreSQL. 3. Chunking trace writes into 1-minute blobs cuts wide-column store writes by ~60× (1,700 chunk writes/s instead of 102,000 single-point writes/s).

  3. APIs

    Order endpoints enforce strong consistency using an Idempotency-Key (a client UUID ensuring network retries never execute an action twice) and expected_version (optimistic concurrency so conflicting edits fail cleanly with 409 Conflict). Location uploads use Protocol Buffers (Protobuf)—a compact binary serialization format—with E5 integer coordinates (latitude × 100,000, giving ~1.1 m resolution) and delta-varint encoding (storing small integer differences from the previous point in 1–2 bytes instead of verbose JSON text).

    1. Strongly consistent Order & Lifecycle APIs
    POST /v1/orders                            Headers: Idempotency-Key: <uuid>
      {"merchant_id": "m_52", "pickup": {"lat": 30.267, "lon": -97.743, "ready_at": "..."},
       "dropoff": {"lat": 30.251, "lon": -97.754, "window": ["19:00Z", "19:30Z"]}, "items": [...]}
      -> 201 Created {"order_id": "ord_84", "state": "CREATED", "version": 1}
    
    POST /v1/orders/{id}/assign                {"courier_id": "c_31", "expected_version": 1}
      -> 200 OK      {"order_id": "ord_84", "state": "ASSIGNED", "courier_id": "c_31", "version": 2}
      -> 409 Conflict (ALREADY_ASSIGNED | VERSION_CONFLICT | COURIER_AT_CAPACITY | COURIER_OFFLINE)
    
    POST /v1/orders/{id}/unassign              {"expected_version": 2, "reason": "courier_timeout"}
    POST /v1/orders/{id}/transitions           {"to": "PICKED_UP", "at": "...", "proof_id": "...", "expected_version": 4}
    GET  /v1/orders/{id}/eta                   -> {"eta": "19:12Z", "p10": "19:09Z", "p90": "19:17Z",
                                                   "stops_before": 1, "quality": "normal"}
    POST /v1/orders/{id}/tracking-links        -> {"url": "https://track.example/t/<128-bit-token>", "expires_at": "..."}
    
    2. Eventually consistent Courier Telemetry & Trace APIs
    POST /v1/couriers/{id}/locations           Content-Type: application/x-protobuf
      LocationBatch {
        session_id, first_seq, is_backfill,
        base_ts_ms, base_lat_e5, base_lon_e5,
        // Packed columnar arrays for points 1..N (1 protobuf tag per column, not per point):
        dt_ms[], dlat_e5[], dlon_e5[], accuracy_m[], speed_mps[], heading_deg3[], flags[],
        device_signature
      }
      -> 200 OK {"acked_range": [first_seq, last_seq],
                 "config": {"sample_ms": 1000, "upload_ms": 5000, "mode": "on_job"}}
    
    GET  /v1/couriers/{id}/trace?from=...&to=...&tolerance_m=10   (RBAC/ABAC restricted & audited)
      -> 200 OK {"polyline": "_p~iF~ps|U...", "timestamps": [...], "map_matched": true}
    
    3. Real-time Streaming Subscriptions
    GET  /v1/orders/{id}/live?token=<ephemeral_token>   (Server-Sent Events for customers: 1-way HTTP push)
      event: snapshot | position | eta | state
    
    WS   /v1/stream                                     (WebSocket for dispatchers & merchants: 2-way channel)
      client -> {"op": "viewport", "bbox": [-97.82, 30.20, -97.68, 30.33], "zoom": 13}
      server <- {"type": "positions", "items": [["c_31", 3026720, -9774310, 180, 2], ...]}
      server <- {"type": "clusters",  "items": [["8726a9c1affffff", 42], ...]}
    

    Notice two clean protocol choices: - SSE (Server-Sent Events) for customers vs. WebSockets for dispatchers: a customer tracking page only receives updates for one order, so SSE works over standard HTTP/2 with built-in browser Last-Event-ID reconnects. A dispatcher console pans and zooms constantly, requiring a two-way WebSocket to update its subscribed map bounding box without opening new connections. - Server-driven config inside every 200 OK upload reply: the backend can speed uploads to every 2 s when a courier nears drop-off or throttle uploads to 10 s during a holiday traffic spike—zero app store deploy needed.

  4. Data model and three-tier storage

    Because transactional correctness, live millisecond lookups, 30-day trace scans, and 13-month dispute playback have completely different read/write shapes, we store each in the right engine:

    Tier 1 — Transactional Truth: PostgreSQL (1 primary + sync standby per region, partitioned by city)
      orders          order_id PK, city_id, merchant_id, pickup_json, dropoff_json,
                      state, courier_id NULL, version INT, created_at, updated_at
      assignments     assignment_id PK, order_id, courier_id, assigned_at, ended_at NULL, ended_reason
                      CREATE UNIQUE INDEX one_active_courier ON assignments (order_id) WHERE ended_at IS NULL;
      couriers        courier_id PK, city_id, status (OFFLINE | IDLE | ON_JOB), vehicle,
                      active_orders INT, max_orders INT, version INT
      courier_plans   courier_id PK, plan_version INT, stops_json [(order_id, PICKUP|DROPOFF, planned_eta)]
      order_events    (order_id, seq) PK, from_state, to_state, actor, at, idempotency_key UNIQUE
      outbox          outbox_id PK, aggregate_id, event_type, payload_json, created_at
      tracking_links  token_sha256 PK, order_id, scope, expires_at, revoked
    
    Tier 2 — Hot Last-Known State: Redis Cluster (reconstructible cache; overwritten per batch = ~21k/s)
      courier:{id}    Hash: {lat, lon, heading, speed, ts, road_seg_id, status, active_order_ids}
      cell:{h3_res8}  Set of courier_ids currently inside that ~0.74 km^2 hexagonal H3 cell
      eta:{order_id}  Hash: {eta, p10, p90, stops_before, computed_at, quality}
    
    Tier 3 — Warm 30-Day Traces: ScyllaDB / Cassandra (TTL = 30 days, ~1,700 chunk writes/s)
      trace_chunks    PRIMARY KEY ((courier_id, day_bucket), minute_start)
                      points_blob (up to 60 delta-compressed 1 Hz fixes + matched road_seg_ids)
    
    Tier 4 — Cold Archive: S3 / GCS Object Storage
      trips/{date}/{city}/{order_id}.pb     Simplified matched polyline + timestamps + state events (~3 KB, 13 mos)
      traces/{date}/{city}/part-*.parquet   Raw 1 Hz traces aged out from ScyllaDB (days 31-90, then purged)
      traffic_agg/{date}/{h3_cell}.parquet  Anonymized hourly road/cell speeds for ETA training (kept long-term)
    

    Here H3 is an open-source hierarchical spatial index that tiles the globe into nested hexagonal cells (for example, resolution 7 averages ~5.2 km² per hexagon; resolution 8 averages ~0.74 km²), turning expensive radius/bounding-box geometry queries into O(1) cell-ID lookups.

  5. Service architecture, event streaming, and CQRS

    We structure the backend around event-driven streaming and CQRS (Command Query Responsibility Segregation)—separating the strict transactional write model (PostgreSQL) from read-optimized views (Redis, SSE/WebSocket push, ScyllaDB traces) updated asynchronously via Kafka events:

      Courier Apps                    Customer Pages (SSE)          Dispatcher Consoles (WS)
           | HTTPS Protobuf batches            |                                |
           v                                   v                                v
      [ Edge API Gateway ]            [ Stateful Live Gateways (9 VMs across 3 AZs) ]
           |                                              ^
           v                                              | pub/sub (courier:{id}, cell:{h3_7})
      [ Stateless Location Ingest ]                       |
           |                                      [ Fan-Out & Privacy Filter ]
           v                                        ^         ^          ^
      Kafka: location.raw (256 parts, key=courier)  |         |          |
           |                                        |         |          |
           v                                        |         |          |
      [ Stateful Stream Processor (Flink, 64 tasks) ]         |          |
        dedupe -> validate -> Kalman -> HMM match -> geofence |          |
           |                  |                     |         |          |
           |                  |                     +--> location.matched|
           |                  +------------------------> Redis Hot State |
           v                                                  |          |
      [ Trace Chunker ] -> ScyllaDB (30d) -> S3 Archive       |          |
                                                              v          |
      [ ETA Service ] <------> [ Routing Engine (MLD graph + 5m live speeds) ]
           |                              ^                   |          |
           +----------------------------->|-------------------+----------+ (eta.updates)
                                          | travel-time matrix
                               [ City Dispatch Optimizer (every 30 s) ]
                                          | CAS assign proposals (expected_version)
                                          v
      [ Order API ] ---------> [ Order Service ] ---> [ PostgreSQL Primary + Outbox ]
                                                              | (outbox relay)
                                                              +---> Kafka: order.events ---+
    

    Why streaming + CQRS wins here: 1. Decoupled consumers & burst absorption: map matching, live fan-out, ETA calculation, trace archival, and anti-spoofing all read location streams independently. When 5,000 couriers emerge from a subway/tunnel outage and flush buffered locations at once, Kafka absorbs the spike without slowing ingestion or order checkout. 2. Guaranteed per-courier ordering: partitioning location.raw by courier_id routes every packet from Courier c_31 to the exact same Flink task in order, keeping smoothing, map-matching, and geofence timers purely in local task memory. 3. Isolated failure domains: 100,000 customers refreshing tracking pages read only from Live Gateways + Redis; PostgreSQL stays quiet and fast (< 1,000 writes/s) for money-critical order transitions.

    Scaling cleanly from 20k to 130k couriers: we create location.raw upfront with 256 partitions so our Flink job can scale from 16 tasks (at 20k couriers) to 64 tasks (at 130k couriers, ~1,600 pts/s and ~2,000 couriers of RAM state per task) and all the way to 256 tasks during surges without repartitioning keys mid-flight.

  6. Mobile GPS publishing, battery life, and offline mode

    Adaptive sampling: burn GPS battery only when precision matters. Running continuous 1 Hz GPS + cellular uploads drains a courier's personal phone if left on all day. We adapt both sensor choice and upload cadence to the courier's live state:

    Courier State                          Sensor & Sampling Rate        Upload Cadence   Why
    -------------------------------------  ----------------------------  --------------   -----------------------------
    Off shift                              Off                           None             Privacy & zero battery drain
    Online, idle, stationary (OS motion)   Cell/Wi-Fi + 60 s heartbeat   Every 60 s       Radio sleeps; confirms alive
    Online, idle, moving                   Fused network, 1 fix / 15 s   Every 30 s       City-block precision for dispatch
    On job, > 500 m from next stop         High-accuracy GPS, 1 fix / s  Every 5 s        Smooth trace + live route ETA
    On job, <= 500 m from pickup/dropoff   High-accuracy GPS, 1 fix / s  Every 2 s        Tight arrival UX & geofencing
    Battery < 15% (or server load-shed)    GPS, 1 fix / 5 s              Every 15 s       Survives remainder of shift
    

    Why cellular radio physics matters: after transmitting a packet, an LTE/5G modem stays in a high-power "connected tail" state for ~10 seconds before sleeping. That means batching 1 Hz fixes into 5-second uploads cuts HTTP requests and CPU wake-ups by 5×, not cellular tail energy (since 5 s < 10 s keeps the radio awake during active jobs anyway). True radio power savings come from the 15–60 s intervals during idle waiting and low-battery mode!

    Idempotent sequence numbers with out-of-order offline recovery. When a courier enters an underground garage or dead zone, fixes write to a local SQLite ring buffer (12 hours × 3,600 pts × ~20 B ≈ 0.9 MB), and manual taps (PICKED_UP, DELIVERED + photo) queue locally with idempotency keys and device timestamps. When signal returns, what order should the phone upload?

    Phone offline for seq 51..200, then reconnects at seq 201..205:
      Step 1: Upload [201..205] FIRST (is_backfill=false)  -> Live map & ETA snap to reality immediately!
      Step 2: Replay queued order transitions (with original device timestamps & idempotency keys)
      Step 3: Upload [51..200] in chunks (is_backfill=true) -> Routed ONLY to ScyllaDB traces, skipping live map!
    
    Why a naive "acked_up_to = 205" counter would break:
      If the server recorded max_seq = 205 at Step 1, it would mistakenly discard [51..200] as duplicates!
      Instead, Flink tracks compact SEEN INTERVALS per session:
        After Step 1: seen = [(1, 50), (201, 205)]
        After Step 3: seen = [(1, 205)]   --> Exact deduplication with out-of-order priority!
    

    What if a dispatcher reassigned the order while the courier was offline, after the courier had already picked up the bag at the restaurant? The Order Service rejects the late PICKED_UP transition (409) and raises a high-priority physical-possession conflict alert on the dispatcher console rather than silently dropping it, because the first courier physically has the food!

    Authentication & anti-spoofing. At sign-in, the app passes hardware attestation (Play Integrity on Android, App Attest on iOS) and generates a private key inside the hardware Secure Enclave / Keystore. Short-lived 15-minute bearer tokens bind to that key, and every LocationBatch is signed over (session_id, first_seq, payload_hash). The stream processor flags mock-location OS flags, broken attestation, impossible velocity jumps (> 60 m/s), synthetic zero-jitter paths, and GPS-vs-cell-tower mismatches—downgrading suspicious sessions to low-trust (blocking auto-geofence payouts and queueing ops review rather than auto-banning urban-canyon multipath glitches).

  7. Deep dive 1: Stream ingestion, map matching, and geofencing

    Inside each Flink task (keyed by courier_id), live points pass through a fast per-courier pipeline: 1. Deduplicate & validate: check session seen-intervals; drop timestamps >30 s in the future or >24 h old; if horizontal accuracy_m > 50 m, update "last seen" timestamp only without moving the road pin; drop teleportation spikes (implied_speed > 60 m/s). 2. Smooth with a Kalman filter: a lightweight 4-state (x, y, vx, vy) estimator that blends the noisy new GPS reading with the courier's predicted position from their prior velocity, weighted by accuracy_m. 3. Snap to streets via Hidden Markov Model (HMM) map matching.

    How HMM map matching fixes urban-canyon jitter. Between tall buildings, GPS signals bounce off glass and place a car 20 meters sideways—inside a building or on a parallel one-way alley. Computing ETAs from the wrong street triggers false U-turns! An HMM (Hidden Markov Model) treats the true road segment at each second as a hidden state and balances two probabilities:

                    Parallel Alley (one-way west):  seg A1 <--- seg A2
         raw GPS * (12m from Alley, 18m from Main)              * raw GPS (eastbound 12 m/s)
                    Main Avenue (eastbound):        seg M1 ---> seg M2 ---> seg M3
    
      1. Emission probability P(gps_point | segment):
           Gaussian falloff in perpendicular distance (sigma ~ 7 m). Point 1 is slightly closer to Alley A1,
           so naive "nearest road" snapping wrongly puts the car on Alley A1!
      2. Transition probability P(seg_t | seg_{t-1}):
           exp( - |shortest_road_distance - straight_line_gps_step| / beta ).
           Moving east from A1 -> A2 against a one-way alley requires a 400 m block detour vs 12 m moved!
           Moving M1 -> M2 along Main Ave is 12 m road distance vs 12 m moved -> high probability!
      3. Sliding-window Viterbi decoding (10-point lag):
           Finds the highest-scoring path across candidate segments within 50 m:
             - Newest point -> emitted immediately as current best guess for the live dot
             - Point t - 10 -> finalized and written to ScyllaDB trace + ETA route progress
    

    If no road exists within 50 m (a walking courier cutting through a campus courtyard or mall), the matcher gracefully falls back to the Kalman-smoothed coordinate.

    Per-courier geofencing without flap or drive-by false alarms. A point only needs to check its own courier's next 2–8 planned stops (stored right in the Flink task's per-courier state—zero global spatial index needed!), plus O(1) H3-cell lookups for city-wide restricted zones. A naive distance < 75 m check flickers in and out when GPS wobbles between 73 m and 77 m, and fires falsely when a courier drives past a restaurant on the way elsewhere. Combining hysteresis (separate enter vs. exit radii) and dwell time (requiring 20 continuous seconds inside) eliminates both bugs:

    ENTER_RADIUS_M = 75   # Must come within 75 m to start counting arrival dwell
    EXIT_RADIUS_M = 150   # Must move past 150 m to count as departed (hysteresis gap = 75 m)
    DWELL_SECONDS = 20    # Must remain near for 20 s so driving past does not trigger arrival
    
    
    def update_stop_geofence(fence_state, distance_m, now_ts):
        """Update one stop's geofence state {'inside': bool, 'near_since': int | None}.
    
        Returns 'ARRIVED', 'DEPARTED', or None.
        """
        if not fence_state["inside"]:
            # Outside the stop: reset timer if courier moves outside the 75 m entry circle
            if distance_m > ENTER_RADIUS_M:
                fence_state["near_since"] = None
                return None
            if fence_state["near_since"] is None:
                fence_state["near_since"] = now_ts
            # Fire ARRIVED only once the courier stays within 75 m for 20 full seconds
            if now_ts - fence_state["near_since"] >= DWELL_SECONDS:
                fence_state["inside"] = True
                return "ARRIVED"
            return None
    
        # Already inside: only fire DEPARTED once beyond the wider 150 m exit circle
        if distance_m > EXIT_RADIUS_M:
            fence_state["inside"] = False
            fence_state["near_since"] = None
            return "DEPARTED"
        return None
    

    Geofence events act as advisory hints to the Order Service (for example, sending the customer "Courier is arriving!" or alerting ops if DEPARTED fires from a restaurant without PICKED_UP), never bypassing PostgreSQL state validation.

  8. Deep dive 2: Incremental ETAs and multi-stop VRP optimization

    Fast road routing + incremental live-leg progress. Standard Dijkstra search across millions of road segments takes hundreds of milliseconds—far too slow for 13,000 queries/s. Our regional routing engine uses Multi-Level Dijkstra (MLD) (partitioning the road network into nested cells and precomputing boundary-to-boundary shortcuts; re-customizing edge weights with fresh 5-minute live fleet speeds takes < 2 seconds without redoing graph partitioning), answering point-to-point routes in ~1–5 ms.

    Even better, we do not call the router on every 1 Hz ping! When a leg starts, the ETA Service caches its sequence of road segments; on each matched ping, it simply subtracts completed segment travel time in O(1) arithmetic, re-querying the routing engine only when: 1. Two consecutive matched segments deviate off the cached route, 2. 60 seconds have elapsed (picking up fresh live traffic speeds), or 3. The courier's stop list or order state changes.

    Full delivery ETA = drive time + prep wait + building handoff. Pure driving time systematically under-predicts urban deliveries. For each stop we add learned per-merchant prep times (ready_at) and per-H3-cell / building-type parking-and-elevator handoff times (service_s), plus a gradient-boosted quantile residual model outputting calibrated p10 and p90 bounds ("7:09–7:17 PM"). Along a multi-stop plan, restaurant wait time absorbs upstream traffic delays:

    Timeline for Pickup P (food ready_at = 1600) -> Dropoff D1:
      Normal traffic:  now=1000 --(300s drive)--> arrives P at 1300 ... waits 300s for food! ... ready 1600 + 120s pack = departs 1720
      +2 min jam:      now=1000 --(420s drive)--> arrives P at 1420 ... waits 180s for food! ... ready 1600 + 120s pack = departs 1720!
      Notice: D1's ETA does NOT move at all because the 120s traffic delay was absorbed by the 300s kitchen wait!
    
    def compute_stop_etas(now_ts, live_leg_seconds, stops, inter_stop_drive_seconds):
        """Compute arrival timestamps along a courier's remaining planned stops.
    
        stops[i]: {'ready_at': int, 'service_s': int}
        inter_stop_drive_seconds[i]: drive time from stops[i - 1] to stops[i] (index 0 unused).
        """
        arrival_etas = []
        cur_time = now_ts + live_leg_seconds
    
        for idx, stop in enumerate(stops):
            if idx > 0:
                cur_time += inter_stop_drive_seconds[idx]
            arrival_etas.append(cur_time)
            # If the courier arrives before food is ready, departure waits until ready_at
            service_start = max(cur_time, stop["ready_at"])
            cur_time = service_start + stop["service_s"]
    
        return arrival_etas
    

    To prevent an anxiety-inducing jumping clock on the customer's phone, the displayed ETA updates only when the predicted minute shifts by ≥ 1 minute for two consecutive ticks (or ≥ 3 minutes immediately).

    Multi-stop dispatch optimization (Pickup & Delivery VRPTW). Every 30 seconds per city zone, the Dispatch Optimizer matches unassigned orders to nearby couriers and sequences each courier's stops—an NP-hard Vehicle Routing Problem with Time Windows (VRPTW) solved heuristically within a 3-second compute budget: 1. Fetch one batch many-to-many travel-time matrix from the routing engine (e.g., 300 couriers + 400 open stops = 700 × 700 matrix in < 200 ms). 2. Greedy insertion construction: sort unassigned orders by urgency, and test inserting (pickup, dropoff) into every feasible slot pair of couriers within 3 km:

    def cheapest_order_insertion(future_stops, pickup_stop, dropoff_stop, evaluate_cost):
        """Find the lowest-cost valid way to insert (pickup, dropoff) into future_stops.
    
        The courier's active live leg is kept frozen so directions never flip mid-intersection.
        evaluate_cost(plan) returns float cost (drive + lateness penalty), or None if invalid.
        """
        best_plan = None
        best_cost = None
        num_stops = len(future_stops)
    
        # Try every insertion index i for pickup, and every j > i for dropoff
        for pickup_idx in range(num_stops + 1):
            for dropoff_idx in range(pickup_idx + 1, num_stops + 2):
                candidate = list(future_stops)
                candidate.insert(pickup_idx, pickup_stop)
                candidate.insert(dropoff_idx, dropoff_stop)
                cost = evaluate_cost(candidate)
                if cost is not None and (best_cost is None or cost < best_cost):
                    best_plan = candidate
                    best_cost = cost
    
        return best_plan, best_cost
    

    With ≤ 8 future stops (9 × 10 / 2 = 45 candidate pairs per courier), evaluating 20 nearby couriers takes microseconds. 3. Local search & stability rules: spend the remaining ~2.5 s running relocate/swap/2-opt improvements, never altering a courier's active live leg and only reassigning an already-assigned order if cost drops by > 15%. Finally, submit assignments to the Order Service with expected_version; any race lost (409) simply re-enters the next 30-second cycle.

  9. Deep dive 3: Atomic assignments, consistency, and live map rendering

    Eliminating double-assignment races in PostgreSQL. Suppose the automated optimizer and a human dispatcher click "Assign ord_84" at the exact same millisecond—or two dispatchers simultaneously assign two orders to Courier c_31 who currently has 3 of 4 allowed orders. Application-level "SELECT then UPDATE" check-then-act logic double-books under concurrency! We make capacity checking, order claiming, event logging, and Kafka publishing one atomic SQL transaction:

    BEGIN;
    
    -- 1. Lock the courier row FIRST (global lock order: couriers -> orders prevents deadlocks!).
    --    Serializes concurrent assignments to the same courier so active_orders never exceeds max_orders.
    SELECT status, active_orders, max_orders
      FROM couriers
     WHERE courier_id = $courier_id
       FOR UPDATE;
    -- Application checks: status IN ('IDLE', 'ON_JOB') AND active_orders < max_orders; else ROLLBACK -> 409.
    
    -- 2. Atomic Compare-And-Set (CAS) on the order row.
    --    Under PostgreSQL READ COMMITTED, if another transaction just claimed this order,
    --    this UPDATE waits on the row lock, re-evaluates WHERE, sees 0 matching rows, and updates 0 rows!
    UPDATE orders
       SET state = 'ASSIGNED',
           courier_id = $courier_id,
           version = version + 1,
           updated_at = now()
     WHERE order_id = $order_id
       AND state = 'CREATED'
       AND version = $expected_version;
    -- If affected_rows == 0 -> ROLLBACK and return 409 ALREADY_ASSIGNED / VERSION_CONFLICT.
    
    -- 3. Update courier load, enforce partial unique index safety net on assignments, and write outbox.
    UPDATE couriers
       SET active_orders = active_orders + 1, status = 'ON_JOB', version = version + 1
     WHERE courier_id = $courier_id;
    
    INSERT INTO assignments (assignment_id, order_id, courier_id, assigned_at)
    VALUES ($assign_id, $order_id, $courier_id, now());
    
    INSERT INTO order_events (order_id, seq, from_state, to_state, actor, at, idempotency_key)
    VALUES ($order_id, $expected_version + 1, 'CREATED', 'ASSIGNED', $actor, now(), $idemp_key);
    
    INSERT INTO outbox (aggregate_id, event_type, payload_json)
    VALUES ($order_id, 'OrderAssigned', $payload_json);
    
    COMMIT;
    

    Latency vs. consistency summary across the platform:

    Data Domain               Consistency Choice                   Why & Mechanism
    ------------------------  -----------------------------------  -----------------------------------------------------
    Order state & assignment  Strong (linearizable per order)      Double-assigning costs money & trust -> Postgres CAS,
                                                                   courier FOR UPDATE lock, sync AZ standby
    Customer state badge      Eventual, strictly monotonic         Never show "Delivered" then revert to "Picked Up" ->
                                                                   client drops any event with version < highest_seen
    Live courier map pins     Eventual (p95 < 10 s, latest wins)   3-second lag is invisible; blocking on consensus hurts
                                                                   availability -> Kafka + Redis + dead-reckoning UI
    Historical route traces   Eventual (seconds to minutes)        Queried post-trip -> 1-min ScyllaDB chunks + backfill
    

    Live map rendering, zoom-aware throttling, vector tiles, and polyline simplification. Pushing 100,000 1 Hz coordinates to 3,000 dispatcher browsers would melt browsers and NICs (300M points/s). Instead: 1. Viewport H3 pub/sub + zoom throttling: a dispatcher's bounding box maps to H3 res-7 hexagons; the Live Gateway subscribes only to those channels and throttles by zoom: - Zoom ≥ 15 (street): individual couriers + heading + active route polyline at 1 update/s (1e-5° precision). - Zoom 12–14 (city): courier dots at 1 update / 5 s (1e-4° precision, ~4 KB/s for 500 couriers); the browser smoothly animates icons along their matched road vector between ticks! - Zoom < 12 (region, or >2,000 couriers in view): aggregated H3 hexagon courier counts every 10 s. 2. Vector tiles vs. live push overlay: static base maps (streets, buildings) and slow-changing operational layers (delivery zones, nightly H3 speed heatmaps) are served via CDN-cached vector tiles; live moving couriers are rendered as a lightweight WebGL symbol layer fed by WebSocket deltas, because re-baking vector tiles every second would be prohibitively wasteful. 3. Douglas–Peucker polyline simplification for route playback: a 10-hour shift produces 36,000 raw 1 Hz points. Before sending GET /v1/couriers/{id}/trace, we recursively drop interior points that deviate less than tolerance_m (1 m zoomed in, 20 m zoomed out) from the straight chord connecting the endpoints—shrinking 36,000 points to ~800 points with zero visual loss:

    import math
    
    
    def point_to_segment_distance_m(pt, seg_start, seg_end):
        """Perpendicular distance in meters from planar point pt=(x, y) to segment [seg_start, seg_end]."""
        seg_dx = seg_end[0] - seg_start[0]
        seg_dy = seg_end[1] - seg_start[1]
        if seg_dx == 0.0 and seg_dy == 0.0:
            return math.hypot(pt[0] - seg_start[0], pt[1] - seg_start[1])
    
        # Project (pt - seg_start) onto segment and clamp fraction to [0.0, 1.0]
        proj = ((pt[0] - seg_start[0]) * seg_dx + (pt[1] - seg_start[1]) * seg_dy) / (
            seg_dx * seg_dx + seg_dy * seg_dy
        )
        clamped = max(0.0, min(1.0, proj))
        closest_x = seg_start[0] + clamped * seg_dx
        closest_y = seg_start[1] + clamped * seg_dy
        return math.hypot(pt[0] - closest_x, pt[1] - closest_y)
    
    
    def simplify_polyline(points, tolerance_m):
        """Douglas-Peucker simplification: keep only vertices deviating > tolerance_m."""
        if len(points) < 3:
            return list(points)
    
        start_pt = points[0]
        end_pt = points[-1]
        farthest_idx = 0
        max_dist = -1.0
    
        # Find the interior vertex farthest from the straight chord [start_pt, end_pt]
        for idx in range(1, len(points) - 1):
            dist = point_to_segment_distance_m(points[idx], start_pt, end_pt)
            if dist > max_dist:
                max_dist = dist
                farthest_idx = idx
    
        # If every interior point lies within tolerance_m, collapse the whole run to [start_pt, end_pt]
        if max_dist <= tolerance_m:
            return [start_pt, end_pt]
    
        left_simplified = simplify_polyline(points[: farthest_idx + 1], tolerance_m)
        right_simplified = simplify_polyline(points[farthest_idx:], tolerance_m)
        return left_simplified[:-1] + right_simplified
    

    (In production on 36k-point arrays, run the exact same split loop with an explicit Python/Go stack rather than call-stack recursion.)

  10. Privacy, access control, failure recovery, and observability

    Privacy by design & access control. - Stacked-order location blurring: if Courier c_31 drops off Customer A's order before Customer B's, showing Customer B a street-accurate pin during Stop A reveals Customer A's home address! The Fan-Out Filter checks courier_plans: until c_31 begins the direct final leg to Customer B, Customer B sees "1 stop before you" and the courier's H3 resolution-8 cell center (~0.74 km² blur), unlocking exact street coordinates only on the leg to B and terminating access 30 minutes after delivery. - Ephemeral tracking links: customer URLs carry a 128-bit cryptographic random token stored only as SHA-256(token) in tracking_links, scoped to one order_id, auto-expiring at delivered_at + 30 min (max 24 h), and exposing zero customer PII (first name + vehicle type of courier only). - RBAC + ABAC enforcement: RBAC (Role-Based Access Control) defines coarse job capabilities while ABAC (Attribute-Based Access Control) restricts access by live context attributes: - Dispatchers can view live/historical couriers only where courier.city_id IN user.assigned_cities during active shift hours. - Support agents can call GET /trace only for an order linked to an open support ticket assigned to them, with every access written to an immutable audit log. - Redaction & retention: couriers can configure personal geofences (e.g., home) dropped at ingest; customer addresses mask behind proxy phone numbers and tokenize 1 hour post-delivery; raw 1 Hz traces purge after 90 days (30 d ScyllaDB + 60 d S3), keeping only the 3 KB per-order trip summary for 13 months and courier-less H3 speed aggregates.

    Failure recovery, disaster recovery, and observability.

    Component Failure User Impact Automated Recovery
    Redis hot-state cluster wiped Live map momentarily blank Seeded from compacted Kafka topic courier.last-position, and active phones naturally repopulate 100% of active couriers within 2–5 seconds on their very next upload!
    Flink task crash ~2k couriers pause matching for seconds Restores 10-second RocksDB checkpoint from S3 and replays from committed Kafka offset.
    Routing engine outage Exact road ETAs unavailable ETA Service switches to haversine distance × city detour factor (~1.3) ÷ historical cell speed, marks quality: "degraded", and pauses auto-optimizer so dispatchers manage exceptions.
    Live Gateway VM lost ~28k sockets disconnect Clients reconnect with 0.5–5.0 s random jitter (preventing thundering-herd reconnect storms) and receive a fresh Redis snapshot on connect.
    PostgreSQL primary crash Order writes pause briefly Synchronous cross-AZ standby promotes in < 30 s (RPO = 0 lost transactions); clients retry safely with Idempotency-Key while live maps keep running unaffected.
    Full regional disaster Entire cloud region unreachable Fail over to DR region (RTO ~ 15 min) holding async Postgres replica (RPO ~ a few seconds) + mirrored Kafka. Courier apps reconcile the few-second async gap on reconnect by replaying any locally stored transitions from the past hour with their original Idempotency-Keys!

    Here RPO (Recovery Point Objective) is the maximum age of committed data that could be lost in a disaster, and RTO (Recovery Time Objective) is the maximum time required to restore service.

    SLOs, golden signals, and synthetic probes. Alongside service golden signals (latency, traffic, error rate, CPU/memory saturation) and SLOs (p95 < 10 s fix-to-glass freshness, 99.95% Order API availability, 0 double assignments verified by a continuous invariant query), we monitor Kafka consumer lag in seconds, % of on-job couriers silent > 60 s, sequence-gap loss rate, and p10–p90 ETA calibration (~80% target coverage). Finally, synthetic probes run every 2 minutes in every region: virtual test couriers replay recorded GPS traces through POST /locations while headless clients watch GET /live, paging on-call if end-to-end fix-to-screen latency breaches 10 seconds even at 3 AM when real traffic is quiet.

Intuition & how it works

Think of a live courier tracking and dispatch platform like an airport ticket counter paired with a radar tower. At the ticket counter (orders and courier assignments), every seat contract is rare and high-stakes: two couriers must never be dispatched to pick up the exact same meal, so every state change goes through one strict ledger with row locks (strong consistency). Up in the radar tower (100,000 courier phones beaming 1-second GPS fixes), readings are noisy, high-volume, and disposable: if one radar blip arrives 2 seconds late or bounces off a glass skyscraper onto a parallel street, pausing the entire tower to lock a relational database would cause instant gridlock—so location blips flow continuously through a partitioned event stream (eventual consistency) that smooths noise, snaps positions onto real streets, updates arrival estimates, and pushes throttled frames to viewers.

A naive single-database design fails quickly in three places. First, writing 102,000 raw GPS points per second into PostgreSQL swamps its write-ahead log and lets a spike of customers refreshing tracking links take down order creation. Second, implementing assignment as "read order; if unassigned, write courier_id" in application code lets the auto-dispatcher and a human operator double-assign the same order milliseconds apart. Third, streaming raw GPS coordinates directly to customer maps makes the courier icon jump across rooftops, miscalculates ETAs from parallel streets, and exposes earlier customers' home addresses when one courier carries stacked deliveries!

Follow one stacked order (Order #84) through the architecture from creation to drop-off:

  1. Atomic assignment (< 50 ms): the city optimizer proposes assigning #84 (expected_version = 1) to Courier Maya (c_31), who already carries #83. Inside one PostgreSQL transaction, the Order Service locks Maya's courier row (active_orders: 1 -> 2 of 4), atomically updates #84 WHERE state = 'CREATED' AND version = 1 (version -> 2), and writes an OrderAssigned row to the transactional outbox (an event table committed in the exact same transaction and relayed to Kafka so database state and events never drift).
  2. Batched GPS upload & road snapping (2–5 s): Maya's phone samples 1 Hz GPS and uploads 5 delta-compressed fixes (~160 B of binary Protobuf) every 5 seconds. Partitioned by courier_id, Maya's Flink worker deduplicates sequence intervals, runs a Hidden Markov Model (HMM) map matcher to snap noisy city fixes onto Maya's true eastbound avenue, checks hysteresis/dwell geofences (within 75 m for 20 s) against Maya's next stops, and updates Redis hot state.
  3. Incremental ETA & privacy-safe push (< 1 s): the ETA Service subtracts Maya's road progress along the cached route (letting kitchen prep wait max(arrival, ready_at) absorb minor traffic delays), while the Fan-Out Filter pushes #84's customer a blurred H3 hexagon ("1 stop before you, arriving 7:09–7:17 PM") over Server-Sent Events (SSE) until Maya completes #83—switching smoothly to street-accurate pins only on the final leg to #84.

Key trade-offs

  • Strong consistency for orders vs. eventual consistency for telemetry. Routing order transitions through one regional PostgreSQL primary with compare-and-set (expected_version) and FOR UPDATE courier locks prevents double-assignment and capacity overflow, trading ~30 seconds of write unavailability during a rare primary failover. Keeping locations on Kafka + Redis lets the live map scale linearly, never block ingest, and degrade gracefully to "last seen 2m ago" markers.
  • CQRS (Command Query Responsibility Segregation) + event log vs. shared database queries. Building specialized read projections (Redis hot state, 1-minute ScyllaDB trace chunks, live SSE/WebSocket streams) asynchronously from Kafka decouples 250,000 live viewers and 6 backend consumers from PostgreSQL, at the cost of 1–5 seconds of projection lag (hidden from dispatchers via client-side version gating).
  • Adaptive upload batching vs. battery life and sub-second freshness. Uploading every 5 seconds on an active job cuts HTTP request QPS by 5× (21k req/s instead of 102k/s) while adding at most 5 s of display lag (tightened to 2 s within 500 m of a stop). Because an LTE/5G radio stays in its high-power tail for ~10 seconds after any packet, real battery savings come from turning off 1 Hz GPS off-job and widening idle/battery-saver intervals to 15–60 seconds.
  • Fixed-lag (10-point) HMM map matching vs. instant greedy nearest-road snapping. Decoding a 10-second sliding Viterbi window eliminates parallel-street and intersection jumps for historical traces and ETA distance tracking, while emitting the newest point's current best state immediately so the live map never waits an extra 10 seconds.
  • Incremental route-progress ETAs vs. full re-routing on every ping. Subtracting segment progress in memory keeps routing CPU well under 100 cores, re-running Multi-Level Dijkstra only on route deviation, state changes, or every 60 seconds (trading up to 60 s of delay in noticing a sudden new traffic jam downroad).
  • Bounded-time heuristic VRP with stability rules vs. continuous re-optimization. Solving city dispatch every 30 s via cheapest insertion + 3-second local search while freezing active live legs produces near-optimal multi-stop routes without confusing couriers by flipping turn-by-turn directions mid-drive.
  • Zoom-aware throttling + client interpolation vs. raw 1 Hz firehose. Throttling city-zoom consoles to 1 update per 5 s (animated smoothly along matched road vectors) and region-zoom consoles to 10-second H3 hexagon counts cuts outbound bandwidth by >5–20× while keeping street-zoom (>= 15) at full 1 Hz precision.

Common mistakes

  • Writing 100,000 GPS fixes/s into the transactional PostgreSQL orders database (or writing 1 row per second instead of 1-minute compressed chunks in ScyllaDB), crushing database I/O and coupling map traffic to order checkout.
  • Using non-atomic check-then-write assignment logic without WHERE state = 'CREATED' AND version = $v—or locking only the orders row without locking couriers first, which allows concurrent requests to assign 5 orders to a 4-order courier or deadlock when locking in inconsistent order.
  • Dual-writing to PostgreSQL and Kafka without a transactional outbox, risking phantom or lost assignment events whenever a process crashes between COMMIT and kafka.send().
  • Deduplicating mobile uploads with a single last_seq_seen integer while prioritizing newest-point-first uploads after an offline tunnel, which mistakenly drops the entire backfilled route trace (seq 51..200) as "already seen" because 205 arrived first; track seen sequence intervals instead.
  • Triggering arrival geofences with a single radius (distance < 75 m) and no dwell timer, causing rapid ARRIVED/DEPARTED flapping on noisy urban GPS and false arrivals whenever a courier drives past a restaurant on a main road.
  • Equating delivery ETA with pure driving time (ignoring kitchen prep ready_at slack absorption and high-rise parking/elevator handoff minutes) or updating the customer's displayed minute on every jittery tick.
  • Re-baking map tiles for live couriers or exposing unblurred stacked routes, either wasting massive CPU re-rendering tiles every second or leaking Customer A's home address to Customer B via a permanent unauthenticated tracking URL.

Follow-up questions

  • How can the platform spot an at-risk delivery before it misses its promised window, and what automated interventions should run? The ETA Service continuously compares each order's p90 arrival prediction against its promised drop-off window, while the Flink stream processor runs a parallel stall detector flagging any on-job courier whose remaining route distance hasn't decreased for 3 minutes (catching flat tires, stuck elevators, or dead phones before p90 even crosses the deadline). If the order has not been picked up yet, emitting an OrderAtRisk event lets the next 30-second optimizer cycle cleanly reassign the order (expected_version) to a closer free courier. If the courier already holds the food, the system queues an exception card for city dispatchers, triggers an automated check-in prompt on the courier app, and sends the customer a proactive, honest ETA update (plus an automatic credit if severely delayed), which sharply reduces support contacts compared to silent lateness.
  • How does the system absorb a sudden 4–5x spike in active couriers and viewers during severe weather or a major holiday? Stateless ingestion, ETA workers, and Live Gateways autoscale horizontally, while location.raw was pre-partitioned with 4× task headroom (256 partitions for 64 baseline Flink tasks) so Flink scales out to 256 tasks immediately without repartitioning keys or breaking per-courier ordering. Even faster, our dynamic config inside every POST /locations response gives us an instant graceful load-shedding dial: shifting cruising on-job uploads from 5 s -> 10 s halves HTTP ingestion QPS on the very next response, shifting sampling from 1 s -> 2 s halves Flink map-matching CPU across the fleet, and widening re-route cadence from 60 s -> 120 s for orders >20 minutes away protects the routing cluster—all while keeping final-approach (< 500 m) tracking sharp.
  • How would you measure accuracy and safely roll out an upgraded ETA prediction model to production? Snapshot predictions at milestone anchors (order_created, assigned, picked_up, and 5_min_away) and join them offline against actual DELIVERED timestamps to measure three distinct metrics: Mean Absolute Error / p90 error (overall accuracy), interval calibration (confirming ~80% of deliveries actually land inside the displayed p10–p90 window), and directional bias (since arriving 5 minutes after the window triggers far more customer frustration and "where is my order?" tickets than arriving 5 minutes early). After passing offline replay slices across rain, rush hour, and high-rise cells, shadow-score live traffic to verify p99 latency, then run a city-stratified A/B test tracking realized lateness rate, customer support contact rate, and courier idle wait at restaurants.

Follow-up questions

Similar questions

More Motive interview questions

All 4 Motive questions →