Asynchronous Courier Location Tracking Backend

Medium · System Design · Software Engineer · Technical Screen

Prompt

Architect the backend telemetry and tracking system for an on-demand meal-delivery marketplace, supporting millions of simultaneous active deliveries with low-latency updates to diners' mobile apps.

Your system should satisfy the following functional and operational requirements:

  • Core capabilities:
    • Ingest periodic coordinate pings (latitude, longitude, device timestamp, plus motion metadata) uploaded by driver apps roughly every 5 seconds while on shift.
    • Serve a low-latency query endpoint for diners to read their assigned driver's latest map position and estimated arrival time (ETA).
    • Serve a route-history endpoint returning the ordered trajectory traveled by the driver for a specific delivery.
  • Scale, freshness & delivery semantics:
    • Absorb millions of coordinate writes per minute while keeping live tracking reads fast and highly available under an eventually consistent model.
    • Reconcile delayed, out-of-sequence, and duplicate mobile uploads cleanly so retried packets never regress a driver's displayed position or duplicate trajectory points.
  • Architectural focus areas:
    • Choose appropriate mobile upload protocols and stateless/stateful load-balancing layers.
    • Guarantee that the stored "latest" driver coordinate stays accurate when telemetry arrives out of timestamp order or across skewed device clocks.
    • Separate ephemeral live-position storage from append-heavy trajectory history, comparing relational SQL databases, wide-column/key-value NoSQL stores (such as Cassandra or DynamoDB), and in-memory stores (such as Redis).
    • Present the end-to-end architecture diagram, data schemas, and API contracts, and mitigate hot-key stampedes ("thundering herds") when thousands of viewers simultaneously track a single driver (such as during a viral promo or large office drop).

Scope & Expectations

  • Quantitative sizing: Estimate peak write QPS, streaming bandwidth, hot in-memory footprint, 30-day trajectory storage, and viewer read QPS to justify each infrastructure tier.
  • APIs & storage schemas: Define mobile upload and diner query contracts alongside schemas that make out-of-order insertion and retry deduplication idempotent.
  • Ordering & consistency mechanics: Detail the atomic mechanism that prevents delayed packets from moving live map pins backward, while addressing device clock drift and noisy GPS fixes.
  • Storage trade-offs & herd protection: Contrast SQL, NoSQL, and in-memory engines across live vs. historical workloads, and show how layered caching/coalescing shields hot drivers from read stampedes.

Step-by-step walkthrough

  1. Clarify requirements and scope

    Accepting GPS coordinates is easy at small scale; what makes food-delivery tracking hard at millions of active deliveries is three competing problems:

    1. Out-of-order and duplicate mobile events: Phones ride through elevators, garages, and subway tunnels, retrying timed-out requests and flushing buffered points minutes later. A delayed upload must never overwrite a newer coordinate and make the courier's pin jump backward on the customer's map.
    2. Two completely different storage patterns ("hot" vs. "cold"): Live tracking overwrites one tiny "where is Courier X right now?" record every 5 seconds and reads it in milliseconds, whereas path history appends billions of immutable trajectory points per day and reads them in chronological slices per order.
    3. The "thundering herd" on popular couriers: When hundreds or thousands of viewers track the same courier (a batched pickup from a viral restaurant, an office group order, or a shared tracking link), naive reads can hammer a single cache key.

    Functional requirements

    • Ingest driver coordinate pings: Receive (latitude, longitude, timestamp) alongside GPS accuracy, ground speed, and heading from driver apps roughly every 5 seconds while active.
    • Serve live position & ETA: Expose a fast read endpoint for diners to query their driver's latest position and estimated arrival time (ETA).
    • Serve delivery route playback: Return the chronological sequence of coordinates traveled by the driver for a given order (used for trip receipts, support reviews, and payout checks).

    Non-functional requirements

    • Sustained write volume: Millions of coordinate pings per minute during dinner rush (~200,000 writes/second).
    • Fast viewer queries: Tracking endpoint p99 < 100 ms, keeping displayed driver markers within ~15 seconds of real time.
    • High availability under eventual consistency: Eventual consistency lets read replicas trail the newest GPS fix by a few seconds while replicas converge, provided a viewer's displayed timestamp never jumps backward.
    • Idempotent out-of-sequence & retry handling: Delayed or retried uploads never overwrite newer live positions and never insert duplicate rows into route history.

    Clarifying assumptions

    • Peak scale: 1,000,000 active couriers on shift sending 1 update every 5 seconds, carrying 1,500,000 concurrent orders (some couriers carry batched 2-order drops), with ~30% of customers actively watching the live map.
    • Privacy boundary: A customer may view a courier's location only for their own order, only between pickup and drop-off (and if a courier drops off Order A before Order B, Order A's exact doorstep stop is hidden from Customer B).
    • History retention: 30 days in fast online storage for customer/support views, then archived to compressed columnar files in object storage per privacy policy.
    • Regional locality: Couriers and customers for an order live in the same metro area, allowing independent regional deployments.
  2. Back-of-the-envelope numbers

    Running the arithmetic exposes why no single database fits both live state and historical paths:

    Write volume
      Peak courier updates          1,000,000 couriers / 5 s         = 200,000 updates/s (12M updates/minute!)
      Daily total (~40% avg load)   80,000/s x 86,400 s/day          ≈ 6.9 billion points/day
      Points per 30-minute order    30 min x 12 updates/min          = ~360 points/order
    
    Event streaming log (Kafka, ~100 B protobuf event + headers)
      Peak ingress                  200,000/s x 100 B                = 20 MB/s logical (60 MB/s across 3 replicas)
      3-day replay retention        80k/s x 100 B x 86,400 x 3 x 3   ≈ 6.2 TB disk across the cluster
    
    Hot current state (Redis in-memory hashes)
      1M courier keys (`cur:{id}`)  1,000,000 x ~200 B               ≈ 200 MB
      1.5M order keys (`trk:{id}`)  1,500,000 x ~300 B               ≈ 450 MB  -> < 2 GB total even with overhead!
      Peak Redis ops/s              200k conditional writes + 180k reads + 50k ETA updates ≈ 430,000 ops/s
    
    Cold path history (Cassandra, ~50 B/point compressed on disk)
      Daily storage                 6.9B points x 50 B = 345 GB/day logical -> ~1.0 TB/day across 3 replicas
      30-day online window          30 x ~1.0 TB                     ≈ 31 TB
      Peak replica writes           200,000/s x 3 replicas           = 600,000 row writes/s
    
    Read volume & end-to-end freshness budget
      Active map viewers            1,500,000 orders x 30%           = 450,000 open apps
      Polling every 5 seconds       450,000 / 5 s                    = 90,000 read requests/s
      ETA recomputations            1,500,000 orders / 30 s          = 50,000 updates/s
      Typical staleness seen        GPS interval (0-5 s, avg 2.5 s) + pipeline (~1 s)
                                    + API cache (0-1 s, avg 0.5 s) + client poll (0-5 s, avg 2.5 s)
                                    = ~6.5 s average, ~12 s worst-case (well within 15 s target!)
    

    What the numbers tell us:

    1. Hot current state is tiny (< 2 GB) but write-intense (200k/s): It belongs in an in-memory store (Redis) where atomic updates take microseconds.
    2. Path history is massive (~31 TB/month) and append-heavy: It belongs in a partitioned wide-column store (Cassandra or DynamoDB) optimized for sequential disk writes and time-range scans.
    3. Kafka belongs in the middle: Buffering the 20 MB/s stream in Kafka decouples mobile ingestion from downstream databases so a slow Cassandra compaction never blocks couriers' phones or delays live map updates.
  3. API design

    1. Courier mobile app -> Ingestion gateway

    POST /v1/locations                      Protocol: HTTPS over persistent HTTP/2 connection
      Authorization: Bearer <jwt bound to courier_id + device_id>
      Body: {
        "points": [
          {
            "ts_ms": 1764691200150,         // GPS measurement time on device (UTC epoch ms)
            "seq": 91042,                   // monotonic per-device integer counter (+1 per GPS fix)
            "lat": 41.88183,
            "lon": -87.62317,
            "acc_m": 7,                     // horizontal GPS accuracy radius in meters
            "speed_mps": 6.8,
            "heading_deg": 180,
            "live": true                    // true = just sampled; false = flushed from offline buffer
          }
        ]                                   // 1 point normally; up to 500 points after reconnecting
      }
      202 Accepted    {"accepted": 1, "next_interval_s": 5}
      429 / 503       Retry-After: 5        // phone keeps points in local ring buffer and retries
    

    2. Customer mobile app -> Tracking & History APIs

    GET /v1/orders/{order_id}/tracking
      200 OK {
        "status": "EN_ROUTE",
        "courier": {
          "lat": 41.88183, "lon": -87.62317, "heading_deg": 180,
          "as_of_ms": 1764691200150         // lets client smoothly animate & show "Updated 6s ago"
        },
        "eta": {"arrive_at_ms": 1764691920000, "computed_at_ms": 1764691190000},
        "poll_after_ms": 5000               // server-controlled polling dial
      }
    
    GET /v1/orders/{order_id}/path?max_points=200
      200 OK {
        "points": [[1764690100000, 41.87540, -87.62980], ...],
        "complete": true                    // false if delivered recently & still inside offline-flush grace window
      }
    

    Why each API field earns its place:

    • (courier_id, ts_ms, seq) as a natural key: A natural key is a unique identifier formed from real event attributes so that uploading the exact same GPS reading twice maps to the identical key and overwrites harmlessly. Pairing seq with ts_ms breaks ties if two GPS fixes share the same millisecond.
    • live: bool flag: Tells downstream consumers whether a point was sampled right now or replayed from a tunnel buffer—preventing stale buffer flushes from firing false "your courier is 500 m away!" push alerts.
    • next_interval_s and poll_after_ms: Give the backend dynamic dials to slow down idle couriers (saving phone battery) or shed customer read load during incidents without shipping an app update.
  4. Data model

    Each store holds only the shape of data it excels at:

    1. Kafka stream (courier-locations, 128 partitions, 3-day retention) A Kafka partition is an ordered, append-only log file on disk; hashing by courier_id routes every event from Courier X to the same partition while letting up to 128 worker processes consume in parallel. (Size partitions generously up front, because changing partition count later briefly hashes a courier's old and new events to two different partitions!)

    LocationEvent {
      courier_id, device_id, ts_ms, seq, lat, lon, acc_m, speed_mps, heading_deg, live,
      recv_ms   // stamped by the ingestion gateway's server clock upon receipt
    }
    

    Notice LocationEvent intentionally omits order_id: looking up active orders inside the gateway would add 200,000 database reads/second to ingestion! Downstream consumers join courier updates with order events in memory.

    2. Redis (hot live state with automatic TTL—time-to-live expiration so off-shift couriers vanish from RAM)

    cur:{courier_id}  -> Hash {ts, seq, lat, lon, speed, heading, acc, recv}     (TTL: 1 hour)
    trk:{order_id}    -> Hash {courier_id, customer_id, status, dest_lat,
                               dest_lon, eta_ms, eta_computed_ms}                (TTL: 24 hours post-delivery)
    

    3. Cassandra (cold trajectory history, 30-day TTL) In Cassandra, the partition key (courier_id, day) chooses which storage nodes hold the data (grouping one courier's ~7,200 daily points = ~360 KB into one tidy partition, where day is the UTC date derived from ts_ms), while the clustering key (ts_ms, seq) keeps rows physically sorted on disk by timestamp:

    CREATE TABLE courier_points (
        courier_id  bigint,
        day         date,       -- UTC calendar date of `ts_ms` (e.g. '2026-12-02')
        ts_ms       bigint,
        seq         int,
        lat         double,
        lon         double,
        acc_m       smallint,
        speed_mps   float,
        heading_deg smallint,
        recv_ms     bigint,
        PRIMARY KEY ((courier_id, day), ts_ms, seq)
    ) WITH CLUSTERING ORDER BY (ts_ms ASC, seq ASC)
      AND default_time_to_live = 2592000
      AND compaction = {
        'class': 'TimeWindowCompactionStrategy',
        'compaction_window_unit': 'DAYS',
        'compaction_window_size': 1
      };
    
    • Zero-cost deduplication & sorting: Writing a delayed point from 2 minutes ago slots it directly into sorted (ts_ms, seq) order, and writing a duplicate point overwrites the exact same row without reading first!
    • TimeWindowCompactionStrategy: Groups each day's writes into daily disk files so when the 30-day TTL expires, Cassandra deletes whole files instantly instead of scanning row-level tombstones.

    4. PostgreSQL (orders system of record) Stores orders(order_id, customer_id, courier_id, status, picked_up_at, delivered_at, dest_lat, dest_lon, path_polyline) and publishes order lifecycle events (ASSIGNED, PICKED_UP, DELIVERED) that populate trk:{order_id}.

  5. High-level architecture and mobile ingestion

    WRITE PATH (Asynchronous Ingestion & State Fan-Out)
    
      Courier Apps (1M on shift)
           |  HTTPS over persistent HTTP/2: POST /v1/locations (every ~5 s, or batch <= 500)
           v
      [ L7 Load Balancer ] ---> [ Stateless Ingestion Gateways x60 ]
                                   auth JWT, validate coords, stamp `recv_ms`,
                                   produce key=courier_id (acks=all) -> return 202 Accepted
                                           |
                                           v
                 [ Kafka: `courier-locations` (128 partitions, 3-day retention) ]
                   |                       |                        |                      |
                   v                       v                        v                      v
      [ Current-Location ]     [ History Writer ]      [ Stream Processor ]     [ ETA Service ]
      [ Updater          ]       batch upserts           geofence (500 m),        snap-to-route every 30 s
        atomic Redis Lua CAS            |                stopped/silent alerts    (full re-route if >100 m off)
                   |                    v                        |                      |
                   v           [ Cassandra x36 ]                 v                      v
      [ Redis `cur:{courier}` ]  `courier_points`      [ Notification Service ] [ Redis `trk:{order}` ]
    
    READ PATH (Low-Latency Customer Queries)
    
      Customer Apps (450k active viewers)
           |  GET /v1/orders/{id}/tracking                      |  GET /v1/orders/{id}/path
           v                                                    v
      [ L7 Load Balancer ] ---> [ Tracking API x30 ]       [ History API ]
                                   verify order owner,       /         \
                                   1 s local RAM cache +    / active    \ completed (>1 h)
                                   single-flight coalescing v            v
                                           |           [ Cassandra ]  [ Postgres `path_polyline` ]
                                           v
                           [ Redis `trk:{order}` + `cur:{courier}` ]
    

    Choosing the mobile ingestion protocol:

    Protocol Strengths Drawbacks Verdict
    HTTPS over HTTP/2 (chosen) Keeps connections warm (1 TLS handshake), multiplexes requests, works with standard stateless L7 load balancers and easy rolling deploys Slightly larger framing than raw binary sockets Best default for 5-second courier uploads
    MQTT Tiny 2-byte headers, built-in QoS retries, supports server-to-courier push Requires stateful broker cluster holding 1M open sessions and sticky L4 load balancing Great if two-way courier push is unified on MQTT; heavier ops
    WebSockets Full-duplex low-overhead frames Stateful gateways cause reconnect storms whenever servers deploy or autoscale Unnecessary for one-way 5 s GPS pings
    Raw UDP Zero connection state, lowest packet overhead Dropped packets, NAT/firewall blocks, must build custom encryption & batch replay Poor fit when trajectory history must be complete

    Keeping ETA cheap (50,000/s, not 200,000/s): Calling a full street-graph routing engine on every 5-second ping would require 200,000 expensive graph searches per second. Instead, the ETA Service computes the full road route once at pickup, caches the polyline, and every 30 seconds snaps the courier's latest coordinate onto that route to compute remaining road distance / live segment speeds—triggering a full re-route only if the courier deviates more than ~100 meters off-route.

  6. Deep dive 1: accurate "current" location under out-of-order and duplicate events

    Why Kafka partition order does NOT guarantee measurement order. Even though Kafka preserves the order gateways produce messages for courier_id, events still arrive out of measurement order whenever:

    1. A courier exits a subway tunnel and uploads 24 buffered points after sending a fresh live ping,
    2. Packet 10 times out over cellular while Packet 11 succeeds on a second gateway, and Packet 10's retry arrives 4 seconds later, or
    3. A crashed consumer restarts from its last checkpointed offset and replays the last few seconds of events.
    What happens WITHOUT timestamp ordering (blind overwrite bug):
      18:10:05  Phone measures Point A (State & 1st) -> cellular stall, retrying...
      18:10:10  Phone measures Point B (State & 3rd) -> arrives at server -> Redis = State & 3rd
      18:10:12  Delayed retry of Point A arrives!    -> blind HSET overwrites Redis = State & 1st (JUMPS BACKWARD!)
    

    Atomic Compare-and-Set (CAS) in Redis. To fix this, we update cur:{courier_id} only if the incoming (ts_ms, seq) is strictly newer than the stored (ts, seq). Crucially, reading the old timestamp and writing the new one cannot be two separate network calls from Python/Go, or two worker threads could race! Instead, we execute a Redis Lua script—Redis runs each Lua script single-threaded from start to finish with zero commands interleaved, making the check and write 100% atomic.

    We also defend against three real-world phone clock and GPS hazards:

    • Future-skewed phone clock (ts_ms > recv_ms + 30_000): If a phone's clock is accidentally set 2 hours ahead, storing that futuristic ts_ms would reject every valid update once the clock is fixed! The updater drops points > 30 seconds ahead of server recv_ms from hot state (still logging them to history with a flag).
    • Phone clock jumped backward (NTP reset): Suppose a phone's clock was 40 seconds fast and suddenly snaps back to real time—every new ts_ms now looks "older" than the stored timestamp! Look at the stale escape hatch in the Lua script below: if the stored record has not been updated for > 60 seconds of server recv time AND the incoming point has live == true, we accept the update anyway. That caps any backward clock jump freeze at 60 seconds while preventing live == false offline tunnel flushes from ever triggering the override!
    • Wild GPS multipath bounce (acc_m > 100): Urban canyon reflections with accuracy radius worse than 100 meters are still saved in Cassandra for diagnostics, but skipped before updating cur:{courier_id} so the map pin does not teleport across blocks.
    -- Atomic Redis Lua CAS for `cur:{courier_id}`
    -- KEYS[1] = cur:{courier_id}
    -- ARGV    = {ts_ms, seq, lat, lon, speed, heading, acc, recv_ms, is_live ("1" or "0")}
    local cur = redis.call('HMGET', KEYS[1], 'ts', 'seq', 'recv')
    local ts, seq = tonumber(ARGV[1]), tonumber(ARGV[2])
    local recv, is_live = tonumber(ARGV[8]), (ARGV[9] == '1')
    
    if cur[1] then
      local server_age_ms = recv - tonumber(cur[3])
      local clock_reset_override = (is_live and server_age_ms > 60000)
    
      if not clock_reset_override then
        local cur_ts, cur_seq = tonumber(cur[1]), tonumber(cur[2])
        -- Reject older points AND exact duplicates (seq <= cur_seq at equal timestamp).
        if ts < cur_ts or (ts == cur_ts and seq <= cur_seq) then
          return 0
        end
      end
    end
    
    redis.call('HSET', KEYS[1],
      'ts', ARGV[1], 'seq', ARGV[2], 'lat', ARGV[3], 'lon', ARGV[4],
      'speed', ARGV[5], 'heading', ARGV[6], 'acc', ARGV[7], 'recv', ARGV[8])
    redis.call('EXPIRE', KEYS[1], 3600)
    return 1
    

    Before calling Redis on a Kafka batch (especially when a courier flushes 24 offline points at once), the updater filters invalid points first and collapses each courier's remaining points to the single newest (ts_ms, seq)—turning 24 Redis calls into 1:

    MAX_FUTURE_SKEW_MS = 30_000
    MAX_GPS_ACCURACY_M = 100
    
    
    def select_newest_valid_per_courier(events):
        """Filter noisy/futuristic points first, then keep only the newest (ts_ms, seq) per courier in the batch."""
        newest_by_courier = {}
        for ev in events:
            # Filter BEFORE collapsing so an invalid newest point cannot hide a valid slightly-older point!
            if ev.acc_m > MAX_GPS_ACCURACY_M:
                continue
            if ev.ts_ms > ev.recv_ms + MAX_FUTURE_SKEW_MS:
                continue
    
            current_best = newest_by_courier.get(ev.courier_id)
            if current_best is None or (ev.ts_ms, ev.seq) > (current_best.ts_ms, current_best.seq):
                newest_by_courier[ev.courier_id] = ev
    
        return newest_by_courier
    
  7. Deep dive 2: hot vs. cold storage and SQL vs. NoSQL vs. Redis

    Putting hot current status and cold trajectory history side by side shows why each store is chosen:

    Workload PostgreSQL (Relational SQL) Cassandra / DynamoDB (Wide-Column NoSQL) Redis (In-Memory Cache/Store)
    Hot current location (1M keys, 200k overwrites/s, 90k reads/s) Possible (ON CONFLICT DO UPDATE WHERE ...), but Postgres MVCC writes a dead tuple + WAL on every 5 s overwrite -> heavy VACUUM & sharding pain Possible (DynamoDB conditional write or Cassandra USING TIMESTAMP), but costs 2–5 ms latency and high per-write cost Ideal: < 1 ms atomic Lua CAS in RAM; losing 1–2 s of updates on rare primary failover self-heals on the very next 5 s ping
    Cold trajectory history (~6.9B rows/day, ~31 TB/30 days, sequential appends, range reads) Requires manual daily partitioning + multi-node sharding + heavy B-tree index maintenance at 200k inserts/s Ideal: Uses LSM trees (Log-Structured Merge trees, which buffer writes in RAM and flush sorted files sequentially to disk), linear horizontal scaling, built-in 30-day TTL Wrong fit: 31 TB of RAM is prohibitively expensive and volatile
    Orders & payments (orders lifecycle, ownership) Ideal: Strong ACID transactions, relational constraints, low write rate Awkward multi-table consistency Not durable system of record

    Serving GET /v1/orders/{order_id}/path cleanly and privately:

    • Active or just-finished orders: Query Cassandra courier_points across the 1 (or 2, if crossing 00:00 UTC) day partitions between picked_up_at and now. If the courier carried a batched order and dropped off Order A on the way to Order B, slice Customer B's path starting from the waypoint after Order A's drop-off (and coarsen doorstep pins during active batch drops) so Customer A's home address is never exposed!
    • Polyline simplification: 360 raw points for a 30-minute ride are noisy and wasteful on mobile data; run Douglas-Peucker simplification (an algorithm that drops nearly straight-line intermediate points within a ~10 m tolerance while preserving street turns) to return ~50–150 crisp points.
    • Compacting completed orders: One hour after DELIVERED (leaving a grace window for any offline courier buffer to finish uploading), a background worker writes the simplified compressed polyline into orders.path_polyline in PostgreSQL. All subsequent receipt views read a single column from Postgres in 1 ms!
  8. Deep dive 3: handling the thundering herd on hot couriers

    Suppose a celebrity promotion or a massive office building batch causes 10,000 viewers to watch Courier 88 at the same time. At 1 poll every 5 seconds, that generates 10,000 / 5 = 2,000 requests/second all targeting the single Redis key cur:88 on one Redis shard!

    We absorb hot-courier herds—and post-outage reconnect storms—with three layered defenses:

    10,000 viewers polling Courier 88 every 5 s  -->  2,000 req/s arriving across 30 Tracking API servers (~67 req/s each)
                                                            |
       Layer 1: 1-second local RAM cache + single-flight    |  (66 of 67 req/s served from local process memory!)
                request coalescing inside each API server   v
                                                      At most 30 reads/s total reach Redis `cur:88` (98.5% reduction!)
    
    1. 1-second in-process cache + request coalescing ("single-flight"): Each of the 30 stateless Tracking API servers caches cur:{courier_id} in local process memory for 1,000 ms. When that 1-second entry expires, request coalescing (single-flight) ensures that if 20 concurrent requests for Courier 88 arrive while the Redis read is in flight, one request calls Redis and all 20 share its response. Across 30 servers, Redis sees at most 30 reads/second on cur:88 whether 100 or 1,000,000 people are watching!
    2. Server-paced polling (poll_after_ms) + client jitter: Clients wait poll_after_ms plus random jitter (±20% random offset, e.g., 4.0–6.0 s) so viewers never synchronize on the exact same second; under extreme cluster load, the API raises poll_after_ms to 10,000 ms to cut read QPS in half instantly.
    3. Optional Server-Sent Events (SSE) push tier for ultra-hot deliveries: For viral promo events (authenticated via signed read-only share tokens—never cache private order responses on a public CDN URL!), clients can open a one-way HTTP Server-Sent Events (SSE) stream; each streaming gateway subscribes once to Redis 7+ sharded pub/sub for cur:88 and fans updates out in memory, cutting average staleness from ~6.5 s to ~3.5 s.
    4. Surviving reconnect & failover stampedes: If a network blip drops connections, mobile apps retry with exponential backoff (doubling wait times 1s, 2s, 4s, 8s... plus random jitter). If a Redis shard fails over and wakes up cold, Tracking APIs never fall back to scanning Cassandra on every miss—single-flight returns "courier": null ("Updating location...") for a few seconds until the courier's next 5-second ping repopulates Redis naturally.
  9. Scaling, failure modes, and trade-off summary

    Horizontal scaling levers:

    • Regional cell architecture: Deploy independent stacks per metro region (e.g., us-west-sf, us-east-nyc). Because couriers and diners share a city, zero hot-path traffic crosses regions and blast radius stays local.
    • Shard by courier_id, never by geography (geohash): Hashing courier_id spreads downtown lunch rush evenly across all 128 Kafka partitions, 8+ Redis shards, and 36 Cassandra nodes, whereas partitioning by city block turns busy restaurant districts into scorching hot partitions.
    • Adaptive ping intervals: Returning next_interval_s = 30 when a courier has no active order (or hasn't moved > 10 m, while still sending a 30-second heartbeat so we know their app is alive!) cuts total daily writes and phone battery drain by ~28%.

    Failure modes and graceful degradation:

    Failure scenario User impact Recovery mechanism
    Courier enters tunnel (offline 2 min) Map shows "Updated 45s ago" App buffers up to ~720 points (1 hr); on reconnect, sends newest live: true point first (snapping map to present) + live: false batch for Cassandra history
    Redis primary shard fails over 1–5 s of cur:{id} lost for ~1/8 of couriers Replica promotes; single-flight blocks stampedes; next 5 s courier ping self-heals live state
    Cassandra node down or slow compaction History writer consumer lags slightly Writes use LOCAL_QUORUM across 3 replicas; Kafka buffers up to 3 days; live Redis tracking is 100% unaffected
    Stream processor or updater crashes Seconds of consumer replay on restart Lua CAS ignores older (ts_ms, seq) in Redis; Cassandra primary key upserts idempotently; alert notifications carry idempotency keys
    Kafka cluster degraded Gateways return 503 + Retry-After Courier apps buffer locally on device until Kafka recovers, losing zero trajectory points

Intuition & how it works

Think of tracking meal-delivery drivers like keeping a single sticky note on the kitchen fridge ("Jordan is at State & Lake as of 18:14:10") alongside a permanent paper logbook in a filing cabinet that records every street corner Jordan passed all shift. Whenever a hungry diner opens the app to ask "where is my order right now?", we read the tiny sticky note from memory in under a millisecond. And if an old text message from 18:12:00 arrives late because Jordan rode through a subway tunnel, we compare its timestamp against 18:14:10 on the sticky note, leave the sticky note alone so Jordan's pin never jumps backward on the map, and file the 18:12:00 point into its proper chronological line in the logbook.

A naive design skips that separation: it writes every incoming GPS ping directly into one relational SQL table, blindly overwrites couriers.current_location with whichever request arrives last, and queries that same database whenever customers refresh the tracking screen. Under 1,000,000 couriers pinging every 5 seconds (200,000 writes/second, or ~6.9 billion rows/day), synchronous SQL index updates and row vacuuming choke the database, delayed mobile retries overwrite newer coordinates and make couriers teleport backward, and thousands of viewers watching a busy courier hammer a single database row.

Here is how our decoupled architecture processes a concrete out-of-order tunnel sequence for Courier 14:

  1. Normal ping (seq=1 at 18:00:00): Courier 14's app sends (lat1, lon1, ts=18:00:00, seq=1, live=true) over HTTP/2. A stateless gateway stamps recv_ms, publishes to Kafka keyed by courier_id = 14, and returns 202 Accepted. The Current-Location Updater runs an atomic Redis Lua script setting cur:14 to (lat1, lon1, ts=18:00:00), while the History Writer inserts row ((14, '2026-12-02'), 18:00:00, 1) into Cassandra.
  2. Tunnel delay (seq=2 at 18:00:05 stalls; seq=3 at 18:00:10 arrives first): Upon exiting the tunnel, seq=3 (18:00:10) lands first. Redis Lua sees 18:00:10 > 18:00:00 and advances cur:14 to (lat3, lon3), so diners immediately see Courier 14's latest position.
  3. Delayed retry arrives (seq=2 at 18:00:05 lands at 18:00:13): Redis Lua compares 18:00:05 < 18:00:10 and rejects the overwrite, keeping the live map steady at (lat3, lon3). Meanwhile, Cassandra inserts ((14, '2026-12-02'), 18:00:05, 2) sorted right between seq=1 and seq=3 by its clustering key—and if seq=2 is uploaded twice, the identical primary key overwrites itself with zero duplicates.

Key trade-offs

  • Kafka event log between gateways and storage vs. synchronous direct database writes. Placing Kafka behind the ingestion gateways adds a streaming cluster to operate, but decouples mobile uploads from storage latency: four independent consumers (Redis updater, Cassandra history writer, ETA service, geofence alerts) read at their own pace, and a slow Cassandra node never stalls courier uploads or live map updates.
  • Ordering by device (ts_ms, seq) vs. server receipt time (recv_ms). Server clocks are trustworthy, but ordering by recv_ms treats a 2-minute-old buffered tunnel point as "newest" when flushed. Ordering by device ts_ms (with seq breaking millisecond ties) reflects true physical movement, while a 30-second future clamp and a 60-second live-only staleness override bound any misconfigured phone clock to at most 1 minute of impact.
  • Redis for hot current location vs. durable SQL/NoSQL rows. Redis serves 200,000 atomic Lua compare-and-set updates (checking the stored timestamp and overwriting in one indivisible step) and 90,000 reads/second in sub-millisecond RAM, at the cost of potentially losing 1–5 seconds of updates during an asynchronous primary failover—an acceptable trade-off ONLY because every active courier re-sends its position 5 seconds later.
  • Cassandra (or DynamoDB) vs. PostgreSQL for 30-day trajectory history. Cassandra's log-structured merge (LSM) trees (sequential append files on disk) and (courier_id, day) partitioning handle 600,000 replica writes/second, ordered range scans, and file-level 30-day TTL expiration linearly, whereas PostgreSQL would require heavy manual time-partitioning, sharding, and VACUUM overhead without needing relational joins on raw GPS points.
  • 5-second client polling with 1-second API caching vs. persistent WebSockets/SSE for all viewers. Stateless HTTP polling + a 1-second local API cache + request coalescing (single-flight) is dramatically simpler to autoscale and deploy than holding 450,000 stateful sockets open, trading ~3 extra seconds of average staleness (~6.5 s vs. ~3.5 s) while reserving SSE push for ultra-hot promotional deliveries.
  • Snap-to-route ETA every 30 seconds vs. full graph routing on every ping. Caching the pickup route polyline and snapping coordinates every 30 seconds (re-routing only when > 100 m off-course) cuts expensive map-routing calls by more than 95%, trading at most a 30-second lag when a driver first takes an unexpected detour.

Common mistakes

  • Blindly overwriting cur:{courier_id} with the latest message to arrive. Cellular retries, multi-gateway races, and offline buffer flushes routinely deliver older measurements after newer ones, making the courier's icon jump backward on the map.
  • Doing "read timestamp in app code, then write Redis" in two round trips. Two worker processes can both read 12:00:00 and race so the older timestamp overwrites the newer one; the comparison and HSET must execute atomically inside a Redis Lua script (or DynamoDB conditional expression).
  • Trusting device timestamps unconditionally without clock-skew guards. Without rejecting futuristic timestamps (ts_ms > recv_ms + 30 s) and allowing recovery after backward NTP clock jumps, one buggy phone clock can freeze a courier's live pin for the entire shift.
  • Storing full path trajectories in Redis or reading every 5-second customer poll from Cassandra. Mixing hot and cold patterns either blows up RAM costs (~31 TB of history) or hammers disk storage with point reads that belong in memory.
  • Sharding Kafka, Redis, or Cassandra by geographic tile (geohash) instead of courier_id. Downtown lunch districts and stadiums concentrate thousands of couriers into a few city blocks, creating severe hot-partition bottlenecks, whereas courier_id hashes uniformly across all shards.
  • Caching GET /orders/{id}/tracking on a shared CDN keyed by courier_id, or triggering live alerts on live: false backlog points. A shared courier CDN key leaks private tracking data across unauthorized callers, and running geofence alerts on replayed offline buffers notifies customers about where the driver was minutes ago.

Follow-up questions

  • How would you trigger an automated customer push alert once the driver comes within 500 meters of the drop-off address without firing duplicate or false notifications? Geofencing fires an automated action when a tracked device enters a virtual geographic zone. A stateful Stream Processor consumes courier-locations (keyed by courier_id), joins each driver's active order drop-off coordinates from order lifecycle events, and on each live == true ping with reliable GPS accuracy (acc_m <= 100) evaluates the haversine distance (great-circle surface distance between two latitude/longitude coordinates on Earth). To filter out single-ping urban GPS bounce and duplicate pushes, require two consecutive fixes <= 500 m, persist a per-order notified_500m = true flag in checkpointed worker state (re-arming only if the driver moves past 700 m—known as hysteresis), and attach idempotency key f"{order_id}:near_500m" when calling the Notification Service.

```python import math

def haversine_meters(lat1, lon1, lat2, lon2): """Compute great-circle distance in meters between two WGS84 (lat, lon) coordinates.""" earth_radius_m = 6_371_000.0 phi1 = math.radians(lat1) phi2 = math.radians(lat2) d_phi = phi2 - phi1 d_lambda = math.radians(lon2 - lon1)

  a = (
      math.sin(d_phi / 2.0) ** 2
      + math.cos(phi1) * math.cos(phi2) * math.sin(d_lambda / 2.0) ** 2
  )
  return 2.0 * earth_radius_m * math.asin(math.sqrt(a))

```

  • Suppose a driver loses cellular signal for two minutes inside a tunnel and then comes back online—how should the app and backend handle the buffered coordinates? Across the two-minute blackout, the driver app writes ~24 fixes (120 s / 5 s, under 4 KB) into an on-device circular buffer. As soon as connectivity returns, the app uploads its freshest current coordinate with live: true first so cur:{courier_id} and the diner's ETA jump straight to real time, then sends a batch (POST /v1/locations) containing the 24 buffered points tagged live: false. Our Redis Lua CAS rejects the older live: false timestamps so the live marker never winds backward, the Stream Processor skips proximity alerts on live: false records, and the History Writer batch-upserts all 24 points into Cassandra under ((courier_id, day), ts_ms, seq) so the delivery route polyline has zero gaps or duplicates.
  • How can the platform detect an unresponsive device ('dead-man's switch') or a driver who remains unexpectedly stationary mid-delivery? A dead-man's switch is a watchdog timer that triggers an alert automatically unless reset by periodic healthy heartbeats. Inside the Stream Processor (partitioned by courier_id), run two parallel checks for drivers carrying an active delivery: (1) a 90-second server wall-clock silence timer reset on every received ping—relying on server processing time rather than device event time because a dead battery or crashed app emits zero events—publishing COURIER_SILENT upon expiry; and (2) a movement anchor (anchor_lat, anchor_lon, anchor_since_ms) refreshed whenever displacement exceeds 50 meters, publishing COURIER_STOPPED if the driver stays within a 50-meter circle for over 5 minutes outside a 100-meter radius around the pickup merchant or drop-off address. Escalation starts with an in-app check-in prompt ("Need help with your order?") before paging live dispatch support to update the diner's ETA or reassign an uncollected order.

Follow-up questions

Similar questions

More Nash AI interview questions

All 4 Nash AI questions →