Live Fleet Proximity Lookup with Eligibility Filters
System DesignModel answerLast updated
Design a service that ingests per-second robotaxi telemetry and answers low-latency radius searches filtered by vehicle eligibility, tolerating late and duplicate packets.
Context
A company runs a driverless ride-hailing fleet across several cities. Dispatchers, remote-assist staff, and routing components must quickly find vehicles close to a point that also satisfy operational conditions such as seat count, charge level, sensor and hardware health, readiness to drive autonomously, or whether the cabin has been cleaned.
Design a fleet proximity lookup service. It continuously consumes live vehicle telemetry and answers geospatial queries restricted to eligible vehicles.
Requirements
Functional
- Telemetry intake: Each vehicle reports every 1-2 seconds. A report contains position (latitude, longitude), heading, speed, a timestamp, and operational state (battery level, status, occupancy, hardware faults).
- Proximity query: The caller provides a center point, a radius (up to 5 km), a result limit
k, and filters such asstatus == IDLE,battery >= 30%,wheelchair_accessible == true. - Freshness reporting: Every returned vehicle carries freshness information (last update time, an estimate of position uncertainty). Vehicles whose data is older than a configurable limit (for example 10 s) are excluded or explicitly flagged.
- Late and reordered packets: Delayed or out-of-order messages (typical on cellular links) must be dropped or reconciled so that vehicle state never goes backwards.
Non-functional
- Scale: 50,000 active vehicles worldwide; up to 10,000 in one dense city.
- Throughput: about 50,000 telemetry updates/s and about 5,000 queries/s.
- Latency: query p95 under 30 ms; time from an event being produced to it being searchable under 500 ms.
- Availability and consistency: 99.99% query availability. The spatial index may be eventually consistent, but a vehicle's state must never regress to an older timestamp.
- Security and privacy: role-based access control over telemetry and passenger-presence data; internal identifiers masked where appropriate.
What to cover
- APIs for streaming ingestion and for the nearby-eligible-vehicles query.
- Spatial indexing and storage: in-memory options (S2, H3, quadtree, geohash on Redis) versus durable storage.
- Architecture from vehicle gateways through to the serving layer.
- Failure modes and hot spots: crowded areas such as an airport queue, dropped cellular connections, node failure, and network partitions.
Hints
Hint 1
Do the sizing first: how many bytes of live state exist for 50,000 vehicles, and for the busiest city? Let the answer decide whether the spatial index needs to be sharded at all.
Hint 2
If a whole city fits in the memory of one machine, consider partitioning by city and replicating the full index to several query nodes instead of splitting a city by cell.
Hint 3
For ordering, avoid trusting wall-clock time alone. Think about a vehicle-generated monotonic key (with a reset marker for reboots) and a compare-and-set rule that makes updates idempotent.
Hint 4
For the query, think of a grid of hexagonal or similar cells: start at the center cell, expand ring by ring, apply cheap categorical filters through per-cell bitmaps, and stop when the next ring cannot beat the current k-th best distance.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size
Questions I would ask: Is cross-city search needed (assume no)? Is "nearby" straight-line or travel-time based (start with straight-line; ETA ranking is a follow-up)? Who calls the API and what may each role see? Do parked or charging vehicles still send heartbeats (assume yes)?
| Item | Estimate |
|---|---|
| Ingest | 50k vehicles x ~1 msg/s = ~50k msg/s, ~300 B each, so ~15 MB/s globally |
| Live state | ~1 KB per vehicle, so ~50 MB globally and ~10 MB for the densest city |
| Queries | 5k QPS, p95 < 30 ms |
| Freshness | event to searchable < 500 ms |
Key insight: the live dataset is tiny. A whole city fits in RAM on one node, and even scanning 10k vehicles linearly costs well under a millisecond. So I do not shard the spatial index by cell. I partition by city/region and fully replicate each region's index across N query replicas. This eliminates scatter-gather, cross-node consistency problems, and hot shards. Capacity scales by adding replicas.
2. API
Ingestion: bidirectional gRPC stream (or MQTT) over mTLS, one client certificate per vehicle.
TelemetryUpdate {
vehicle_id, boot_epoch, seq, // ordering key
gnss_time_ns, lat, lng, heading, speed, h_accuracy_m,
status, battery_pct, occupancy, capabilities, faults[], autonomy_ready
}
-> Ack { last_applied_seq }
Query:
POST /v1/vehicles:searchNearby
{ center, radius_m, k, filters{...}, max_staleness_s, include_stale }
-> { results:[{ vehicle_ref, lat, lng, distance_m, heading,
last_update_ts, age_ms, position_confidence_m, stale }],
index_watermark_ts }
vehicle_ref is a per-caller masked token such as HMAC(client_key, vehicle_id), so raw IDs never leave the system. index_watermark_ts tells the caller how current the answering replica is.
3. Architecture
Vehicles -mTLS-> Telemetry gateways (stateless, per region)
| authenticate, validate, stamp server receive time
v
Kafka (topic per region, keyed by vehicle_id, RF=3)
| |
v v
Geo-index replicas x N Persistence consumers
(each reads ALL partitions - last-known-state KV (conditional writes)
of its region) - history lake (Parquet) for replay/analytics
^
Query gateway (RBAC, masking, region routing, load balancing)
^
Dispatch / remote assistance / routing
- Keying by
vehicle_idkeeps per-vehicle order in the normal case. - A region produces at most ~10k msg/s, which one consumer handles easily. Every replica consumes the whole region stream, so replicas are independent.
- Latency budget: gateway ~20 ms + Kafka produce/consume 50-100 ms + index apply under 1 ms, comfortably inside 500 ms.
- Persistence is off the hot path. The KV serves "where is vehicle X" and replica cold starts; the lake serves incident review and ML.
4. The in-memory index
vehicles: map from vehicle id to latest state.cells: map from H3 cell (res ~8) to the set of vehicles inside. S2 works equally well; H3 gives uniform neighbor rings. Geohash is a weaker choice because of edge and distortion artifacts.- Per-cell Roaring bitmaps for categorical flags (IDLE, wheelchair, autonomy_ready). Equality filters become bitmap ANDs; numeric predicates such as battery are checked on candidates.
Update: run the ordering check, move the vehicle between cells if it crossed a boundary, flip bitmap bits. O(1).
Query:
- Find the center cell.
- Expand rings (
gridDisk). - Per ring: AND the filter bitmaps, compute haversine distance, discard anything beyond the radius or staleness limit, and push into a size-k max-heap.
- Stop early once the minimum possible distance of the next ring exceeds the current k-th best.
A 5 km radius at this resolution is around 100 cells, so compute is tens of microseconds; the p95 is dominated by the network.
5. Ordering and staleness
- Order by
(boot_epoch, seq), generated by the vehicle. The epoch handles counter resets after reboot. - Apply an update only if its key is strictly greater than the last applied one; otherwise drop it and bump a metric.
- GNSS time is a sanity check and tiebreaker, not the primary key, since clocks jump and GNSS glitches.
- The same rule is enforced in the KV through a conditional write, so replays and duplicates are idempotent and state cannot regress.
age = now - gnss_time, with skew bounded against server receive time.position_confidence_m = h_accuracy + speed * age. Vehicles older thanmax_staleness_sare excluded by default, or returned withstale: truewhen requested.
6. Failure modes and hot spots
- Hot spot (airport queue, 800 vehicles in a cell): replication spreads query load across replicas. For dense cells, keep a pre-filtered or battery-sorted structure, or adaptively use a finer resolution. Pre-aggregate per-cell counts for dashboards, and coalesce identical hot queries with a 100-200 ms micro-cache.
- Connection drops: vehicles buffer locally and flush on reconnect. The ordering rule applies only the newest packet to live state; older buffered points go to history.
- Node failure: at least 3 replicas per region across availability zones. A health check removes replicas whose consumer lag exceeds ~300 ms, degrading capacity rather than serving stale answers. A new replica bootstraps from the KV snapshot and then replays Kafka from a saved offset.
- Network partition: a replica cut off from Kafka stops advancing its watermark; it should fail its health check and leave rotation, or return results flagged with an old
index_watermark_ts. Because vehicle updates are idempotent, catching up after the partition heals is safe. - Security: RBAC at the query gateway controls which fields each role sees (for example, occupancy only for remote assistance), per-client masked IDs, mTLS everywhere, and audit logs for sensitive queries.
7. Trade-offs and common mistakes
- Mistake: starting with a sharded Redis geohash cluster. At ~10 MB per city it adds scatter-gather and hot-shard problems with no benefit.
- Mistake: ordering by wall-clock timestamp only, which lets a clock jump freeze or regress a vehicle.
- Mistake: returning stale vehicles silently. Always expose age and confidence.
- Trade-off: full replication costs more memory and Kafka read fan-out, but both are tiny here, and it buys simplicity and availability.
- Follow-ups: ETA-based ranking via a routing service applied to the top few dozen straight-line candidates; cross-region queries via a thin fan-out layer; multi-region disaster recovery by mirroring Kafka topics.