Live Courier Fleet Tracking and ETA Platform Design
System DesignModel answerLast updated
Design an end-to-end platform that streams courier GPS, computes routes and ETAs, manages order assignment, and powers live maps for dispatchers and customers.
Problem
A logistics company wants a platform that shows dispatchers, operations staff, and end customers where each courier is, which route they are following, and when they will arrive. Design the whole system, from the phone in the courier's hand to the pixels on a map.
Scope
Walk through these areas and explain the trade-offs you choose:
- Architecture. Clients, gateway, core services, event bus, and datastores. Justify an event-driven approach and say where a split between write and read models (CQRS) helps.
- Courier app publishing. Sampling policy, batching, compression, sequence numbers, authentication, and defenses against fake locations.
- Ingestion and stream processing. Validation, deduplication, ordering, map matching, smoothing, geofence events, and fan-out.
- Routes and ETAs. Incremental updates for the current leg, estimates for later stops, and multi-stop planning with time windows (VRP/TSP variants).
- Orders and assignment. Data model, state transitions, and how to prevent one order from being given to two couriers.
- Map delivery. Live and historical views for dispatcher consoles and customer pages: push transport, tiles, path simplification, throttling by zoom level.
- Storage. Latest position, time-series traces, and cold archive for playback.
- APIs. At least: create order, assign order, post courier locations, fetch courier trace, fetch order ETA, subscribe to live order updates.
- Capacity. Estimate request rates, storage, and connection counts, scaling from tens of thousands of concurrent couriers to millions of deliveries per day.
- Consistency vs. latency. Where you require strong consistency and where eventual consistency is acceptable.
- Mobile constraints. Offline operation and battery use.
- Privacy and access control. Data minimization, role- and attribute-based access, expiring tracking links, location blurring, retention.
- Reliability. Failure modes, disaster recovery, SLOs, alerting, and synthetic checks.
What to deliver
A structured design with a diagram or data-flow description, concrete numbers for your estimates, and explicit reasoning for each major decision. State any assumptions you make up front.
Hints
Hint 1
Start with numbers. Concurrent couriers times sampling rate gives ingest rate, but order writes are tiny by comparison. Work out which part (fan-out, freshness, correctness) is actually hard before choosing components.
Hint 2
Treat location as an append-only stream keyed by courier ID so per-courier ordering is preserved, and let separate consumers handle map, ETA, geofencing, archive, and fraud. Keep orders and assignments in a transactional store and build read views from events.
Hint 3
For double-assignment, use a conditional update (status and version check) in one transaction rather than distributed locks. For the live map, accept eventual consistency, send only the latest position per courier, and throttle by viewport and zoom.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and sizing
Targets
| Concern | Target |
|---|---|
| Live map freshness | p99 of 2–3 s, device to screen |
| Assignment | Strongly consistent, no double-assignment |
| Availability | 99.95% tracking and ingest, 99.99% order writes |
| Privacy | Customer sees only their own courier, only during an active delivery |
Estimates (assume 50k concurrent couriers typical peak, 200k design ceiling)
- Sampling every 4 s while moving gives about 12.5k points/s at 50k couriers. Clients batch every 10–15 s, so roughly 4k requests/s.
- Storage: 50k couriers x 10 h x 900 points/h is about 450M points/day. At about 40 B compressed per point that is about 18 GB/day, roughly 6.5 TB/year before downsampling.
- Orders: 2M/day is about 23 writes/s average, about 150/s at peak. Tiny.
- Connections: about 60k customer streams (30% of 200k active orders) plus about 5k dispatcher consoles.
Conclusion: raw write volume is modest. The hard parts are fan-out, freshness, and correctness of assignment.
2. Architecture
Courier app -> API gateway (auth, rate limit) -> Ingest service -> Kafka locations.raw (key = courier_id)
Kafka -> Stream processor: validate, dedupe, map-match, smooth, geofence
-> locations.matched -> Redis (last known + geo index) -> Realtime gateway (WS/SSE) -> clients
-> time-series store -> object-store archive (Parquet)
-> ETA service -> eta.updates
Order service (Postgres) -> outbox -> order.events -> optimizer, notifications, ETA
Why event-driven: location is high-volume, append-only, and has many independent consumers. A log decouples them and enables replay after a bug. Partitioning by courier keeps per-courier order.
Why CQRS: orders need transactions; map reads need cheap, denormalized, high-fan-out views. Build read models (for example an order-tracking view in Redis) from events so map traffic never touches the transactional DB.
3. Mobile publishing
- Adaptive sampling: 3–5 s when moving, 30–60 s when stationary (activity recognition), denser near pickup and dropoff. Use the fused provider and discard fixes worse than about 50 m accuracy.
- Batching: flush every 10–15 s or immediately on key events such as "arrived". Protobuf, delta-encoded coordinates and timestamps, then compression; four points fit in about 100 B.
- Sequence numbers: each point carries a monotonic
seqper device, enabling dedupe, gap detection, and safe buffer trimming when the server acks the highest acceptedseq. - Offline: persist the buffer to local storage, retry with backoff, and upload oldest-first; the server handles late data via event time.
- Battery: batch radio use, lower sampling when idle, and avoid wake-ups.
- Auth and anti-spoofing: short-lived tokens bound to courier and device, device attestation, mock-location detection, and server plausibility checks (implied speed, teleports, cross-checks with network location). Flag suspicious traces rather than silently dropping them.
4. Ingestion and stream processing
The ingest service is stateless: authenticate, validate schema and bounds, publish to Kafka, return 202 with the highest accepted seq.
A keyed stream job then does:
- Dedupe on
(courier_id, seq)and reorder within a roughly 10 s watermark. - Drop physically impossible outliers.
- Map-match with an HMM/Viterbi over the road graph using the last N points.
- Smooth for display (Kalman filter).
- Geofence with a hex-grid index (such as H3) and hysteresis so
ARRIVED_PICKUPandNEAR_DROPOFFdo not flap. - Fan out to the matched topic, Redis, the trace store, and the ETA service.
5. Routes and ETA
- Live leg: a routing engine (OSRM, Valhalla, or contraction hierarchies with live traffic weights). Incrementally subtract the traveled portion and scale by observed vs. expected speed; re-route only on deviation (about 50 m) or material traffic change.
- Future legs: sum of leg drive times plus predicted dwell. A gradient-boosted correction model using time of day, area, merchant, and courier history reduces error. Publish a confidence band.
- Display stability: push a new customer ETA only when it moves by more than about 1 minute.
- Dispatch planning: a capacitated VRP with time windows and pickup-before-dropoff precedence, which is NP-hard. Use cheapest-insertion construction plus local search (2-opt, relocate, or-opt) or OR-Tools, batched per zone every 15–30 s under a time budget. Insert new orders into existing plans and re-optimize globally less often.
6. Orders and assignment
- Tables:
orders(id, status, pickup, dropoff, window, courier_id, version),assignments, append-onlyorder_events. - State machine:
CREATED -> ASSIGNED -> PICKED_UP -> IN_TRANSIT -> DELIVERED, withCANCELLEDandFAILEDbranches. Validate every transition server-side. - No double-assignment: one conditional write:
UPDATE orders SET courier_id=$c, status='ASSIGNED', version=version+1
WHERE id=$o AND status='CREATED' AND version=$v;
Zero rows updated means someone else won; retry or pick another order. Protect courier capacity with a row lock or constraint on a courier-load row.
- Use idempotency keys on mutations and a transactional outbox so events are published exactly once from the DB's point of view.
7. Map delivery
- Transport: WebSocket or SSE through a realtime gateway that subscribes to Redis pub/sub or a stream. Customers subscribe to one order; dispatchers subscribe to viewport regions.
- Throttling: send only the latest position per courier, at lower rates when zoomed out, and cluster markers at low zoom.
- Rendering: vector tiles for the base map, simplified polylines (Douglas-Peucker) for routes and playback.
- Reconnects: clients send last-seen sequence and receive a snapshot, then deltas.
8. Storage
- Hot: Redis with last known position, geo index, and tracking views (TTL on inactive couriers).
- Warm: a time-series or wide-column store partitioned by courier and day for recent traces.
- Cold: Parquet in object storage, downsampled after a retention window, for playback and analytics.
9. APIs
POST /orders, POST /orders/{id}/assign, POST /couriers/{id}/locations, GET /couriers/{id}/trace?from&to, GET /orders/{id}/eta, GET /orders/{id}/live (SSE/WS). All writes accept an idempotency key.
10. Consistency trade-offs
Orders and assignments: strong consistency in a relational store with single-region leader writes. Live map and ETA: eventual consistency, last-write-wins by sequence or event time; a few seconds of staleness is acceptable and cheaper.
11. Privacy
Collect only what is needed; track customers' view only while the order is active. RBAC for roles plus ABAC for "this order belongs to this customer". Use expiring, unguessable tracking links, blur or round the courier location far from the destination, hide it after delivery, encrypt in transit and at rest, and enforce retention (for example raw traces for 30–90 days, then downsample or delete).
12. Reliability and monitoring
- Multi-AZ Kafka, Redis replicas, and Postgres with failover; cross-region backup and a documented RTO/RPO.
- Stream jobs checkpoint state; consumers replay from Kafka after failure.
- Degrade gracefully: if ETA is down, show last ETA with a stale flag; if the realtime gateway is overloaded, shed to polling.
- SLOs on end-to-end freshness, ingest success rate, assignment latency. Watch golden signals (latency, traffic, errors, saturation), consumer lag, and fix-to-screen delay. Run synthetic couriers that emit known paths and verify they appear on a test map.
Common mistakes
- Sizing for write throughput and ignoring fan-out.
- Using distributed locks for assignment instead of a conditional update.
- Pushing every point to every viewer regardless of zoom.
- Trusting client timestamps and sequence without server validation.
- Showing raw ETA jitter to customers.
- Forgetting retention and access limits on location data.