Design a Low-Latency Airspace Conflict Detector for Drone Operations
Medium · System Design · Software Engineer · Other
Prompt
Design an airspace conflict-warning service that monitors cooperative unmanned aerial vehicles (UAVs) operating in shared low-altitude airspace and warns flight crews before two aircraft violate safe separation. Each airborne vehicle periodically transmits telemetry over a wireless network containing its unique vehicle identifier, onboard measurement timestamp, 3D coordinates (latitude, longitude, and altitude), and 3D velocity vector. For instance, if two cargo drones (uav_304 and uav_719) fly opposite directions along a shared delivery corridor on a converging path, the service must project their trajectories over a short look-ahead window and alert both operators well ahead of closest approach.
Anchor your architecture around these baseline assumptions (confirming concrete numerical bounds with your interviewer):
- Cooperative telemetry stream: Participating drones transmit periodic position and velocity packets, though cellular or radio links may deliver packets late, duplicated, out of order, or drop connectivity mid-flight.
- Proactive separation prediction: Warnings must fire over a look-ahead horizon before horizontal and vertical separation minimums are simultaneously breached, rather than only detecting violations already in progress.
- Advisory baseline: Notifications go to human remote pilots and ground-control station (GCS) software; issuing automated evasive flight commands directly to aircraft is outside the initial scope.
- Safety-critical reliability: Missing an actual conflict is unacceptable, yet frequent false alarms train operators to ignore alerts. Pipeline outages must never masquerade as safe skies, and spoofed telemetry must be rejected.
Scope & Expectations
- Authenticated ingestion and per-vehicle tracking: How telemetry bursts, duplicates, and out-of-order packets are handled; how vehicle timestamps are reconciled against clock faults versus network delay; and how stale or silent tracks expand in position uncertainty.
- Sub-quadratic 3D conflict detection: How spatial indexing bounded by separation rules, maximum airspeed, and look-ahead horizon avoids all-pairs checks; how pairwise predicted relative motion is tested; and how geographic sharding handles tile borders and evaluation cadence.
- Alert lifecycle and fail-safe delivery: How raw detections become severity-tiered, deduplicated, hysteresis-stabilized alerts with delivery receipts, operator acknowledgments, escalation timers, an end-to-end latency budget, and explicit fail-safe degradation under component failures.
Step-by-step walkthrough
Clarify requirements and safety assumptions
A drone conflict-alerting service is a safety-critical real-time system: qualitative terms like "unsafe proximity" or "prompt warning" must become concrete numbers before we draw a single box. Every threshold below is an explicit engineering assumption to confirm with the interviewer first.
Functional requirements
- Ingest live telemetry from cooperative drones: unique drone ID, sequence number, timestamp, 3D position, 3D velocity, and measurement accuracy. (Telemetry simply means automated position and health measurements sent remotely by a vehicle.)
- Maintain per-drone state for every airborne drone, including drones whose reports are delayed, stale, or missing.
- Predict future loss of separation over a short look-ahead window so operators are warned before two drones get too close, not after.
- Deliver lifecycle-managed alerts to both drones' operators via their ground-control software (GCS) (the flight-control app on the operator's laptop or tablet) and a central web console, updating severity, tracking human acknowledgments, escalating ignored warnings, and marking conflicts resolved.
- Advisory only in v1: the system warns humans and GCS software, rather than sending autonomous steering commands directly to drones (covered in the follow-ups).
Assumptions to confirm
- Scale and density: 100,000 drones airborne nationally at peak; the busiest metro area holds 10,000 drones inside 50 km x 50 km (2,500 km², or 4 drones per km²). Each drone reports at 1 Hz (once per second; up to 5 Hz for fast-maneuvering models).
- Conflict definition: Two drones are in conflict at time
tif they violate both separation minimums at the same instant: less than 50 m horizontally AND less than 15 m vertically (a hockey-puck-shaped safety cylinder around each drone). Look-ahead horizon: 60 seconds. - Speed limit: Maximum airspeed
v_max = 30 m/s(~108 km/h), recorded per drone model at registration. - Accuracy and freshness: Drones measure position and time using GNSS (Global Navigation Satellite Systems such as GPS or Galileo), which gives meter-level position accuracy and microsecond-accurate clocks. A drone silent for
> 3 sis markedSTALE; silent for> 10 sis markedLOST. - Alert latency target: End-to-end 2.5 seconds at p99 from position measurement to alert on the operator's screen.
Non-functional requirements
- High recall without alert fatigue: Missing a real collision course is unacceptable, so uncertainty margins must be conservative—but constant false alarms train operators to ignore warnings.
- Fail safe (never fail silent): If any pipeline stage is down or lagging for a drone, its GCS must immediately display
"NOT PROTECTED". Silence must never be indistinguishable from clear airspace. - Authenticated telemetry and full auditability: Spoofed reports could hide real drones or inject phantom collisions, and every report and alert event must be archived for incident replay.
Back-of-the-envelope numbers
Before picking data structures, let's check where the actual compute and bandwidth bottlenecks live.
1. Telemetry ingestion Report rate (1 Hz) 100,000 drones x 1 msg/s = 100,000 msg/s (500,000 msg/s at 5 Hz) Wire size ~200 bytes (signed binary/protobuf) -> ~20 MB/s (~100 MB/s at 5 Hz) Raw archive (at 24/7 peak) 20 MB/s x 86,400 s/day = ~1.7 TB/day (much less off-peak) 2. Why naive all-pairs fails in one busy metro (10,000 drones) All unordered pairs 10,000 x 9,999 / 2 = ~50,000,000 pair checks every second 3. Physical reach bound (maximum closing distance within 60 s) Horizontal separation S 50 m Max closing distance 2 x v_max x T = 2 x 30 m/s x 60 s = 3,600 m Position uncertainty u(T) u_now (<= 50 m for normal live tracks) + 2 m/s x 60 s = 170 m Max starting distance b S + 2 x v_max x T + 2 x u(T) = 50 + 3,600 + 340 = 3,990 m (< 4 km) 4. Spatial grid filtering in the busiest metro (4 drones/km², recomputed at 1 Hz) Simple 4 km grid cell Own cell + 8 neighbors = 3x3 cells = 12x12 km (144 km²) -> ~576 neighbors/drone Finer 1 km grid cell 4-cell radius = 9x9 cells = 9x9 km (81 km²) -> ~324 neighbors/drone Pair tests (all tiers) ~3,000,000 pair tests/s across the metro CPU cost per pair test ~50 float ops + 2 square roots -> ~1.5 x 10^8 ops/s (2-4 CPU cores!) 5. Outbound alerts and protection heartbeats Active conflict pairs ~1% of drones in a conflict episode -> ~500 active pair alerts (push updates only on state/tier changes -> tens of messages/s) Fail-safe status stream 1 heartbeat/drone/s -> 100,000 msg/s outbound (largest push stream)Three takeaways shape the entire architecture:
- Ingestion is modest: 100,000 small messages per second (20 MB/s) fits comfortably in a standard partitioned log like Apache Kafka.
- Physics kills the O(N²) problem: Two normal drones more than 4 km apart cannot close to within 50 m inside 60 seconds even if they fly straight at each other at
30 m/s. Indexing drones on a metric grid cuts 50M pair checks down to ~3M cheap algebraic checks per second. - Work grows quadratically with local density: If a region gets
10xmore drones in the same area, both the drone count and the neighbors per drone grow10x, multiplying pair checks by100x. That is the bottleneck to design around.
API and fail-safe contract
Drones (or their GCS) stream telemetry over persistent mutual TLS (mTLS) connections—a TLS handshake where both the server and each drone present cryptographic certificates, proving the sender actually owns
drone_id.Telemetry ingest (gRPC stream or MQTT over mTLS, 1 Hz per drone) Report { drone_id: "uav_304", seq: 9412, // monotonic counter per flight t_gnss_ms: 1764259200450, // measurement time from onboard GNSS clock lat: 37.3861, lon: -122.0839, alt_wgs84_m: 80.0, // height above WGS-84 reference ellipsoid vel_e_mps: 16.0, vel_n_mps: 0.0, vel_u_mps: 0.0, h_acc_m: 4.0, v_acc_m: 5.5, // 95% horizontal and vertical accuracy radii signature: "<ed25519-bytes>" // end-to-end signature when relayed via GCS }We intentionally do not acknowledge every single telemetry packet: if packet
9412drops on a cellular link, packet9413arrives one second later with fresher coordinates, making retries of old positions counterproductive. Instead, the gateway sends a lightweight link-health frame every 3 seconds containing the latestseqreceived and measured clock offset.For operators and GCS software, the server maintains a bidirectional push stream plus REST endpoints for history and console views:
Operator / GCS push stream Client -> Subscribe { operator_id, drone_ids, resume_after_version? } Server -> AlertUpdate { alert_id, version, state: ACTIVE | RESOLVED, severity: ADVISORY | WARNING | CRITICAL, own_drone, other_drone, t_conflict_s, t_cpa_s, miss_distance_m, computed_at_ms, confidence: NORMAL | LOW } Server -> Protection { drone_id, status: PROTECTED | DEGRADED | NOT_PROTECTED, covered_until_ms } // pushed every 1 s Client -> Delivered { alert_id, version } // automatic: GCS app got it Client -> Ack { alert_id, version, operator_id } // human clicked acknowledge Console & audit REST endpoints GET /v1/alerts?area_bbox=...&state=ACTIVE GET /v1/drones/{drone_id}/track?from_ms=...&to_ms=... POST /v1/alerts/{alert_id}/ackWhy three details in this contract matter for safety:
- Separate
DeliveredfromAck:Deliveredis sent automatically by the GCS socket the millisecond an alert arrives (proving network delivery);Ackrequires a human action (proving situational awareness). MissingDeliveredtriggers a backup phone call in 3 seconds; missingAckescalates to the airspace supervisor. - 1 Hz
Protectionlease: If a detector crashes or the operator's cellular connection drops,covered_until_msexpires within 3 seconds and the GCS automatically raises a red"COLLISION WARNING UNAVAILABLE"banner. - Relative countdowns (
t_conflict_s+computed_at_ms): Sending relative seconds anchored tocomputed_at_mslets the UI count down accurately even after 400 ms of network transit.
- Separate
Data model
We separate fast-changing flight positions (kept in memory and backed by a replayable log) from durable alert lifecycles (stored in a relational database).
1. Registry & raw log drones (Postgres) drone_id PK, operator_id, cert_fingerprint, model, v_max_mps, phone_fallback, status telemetry (Kafka) topic "telemetry", partitioned by drone_id, 7-day retention; compacted hourly into Parquet files in object storage for replay 2. Live per-drone state (in-memory inside Track Service, no DB writes on the hot path) track drone_id, seq, t_gnss_ms, lat, lon, alt_wgs84_m, vel_e_mps, vel_n_mps, vel_u_mps, h_acc_m, v_acc_m, last_received_ms, state (LIVE | STALE | LOST | ENDED), trust (OK | SUSPECT) 3. Ephemeral detector output (emitted each cycle, not persisted long-term) observation cycle_ms, shard_id, drone_a, drone_b (ordered: drone_a < drone_b), severity, t_conflict_s, t_cpa_s, miss_distance_m, confidence 4. Alert lifecycle & audit (Postgres) alerts alert_id PK, drone_a, drone_b, state (ACTIVE | RESOLVED), severity, version, opened_at, last_seen_cycle_ms, clear_streak, lower_streak, t_conflict_s, t_cpa_s, miss_distance_m, resolved_at UNIQUE (drone_a, drone_b) WHERE state = 'ACTIVE' alert_events (alert_id, version) PK, event_type, severity, payload_json, at deliveries (alert_id, version, recipient_id) PK, delivered_at, acked_by, acked_at, escalation_levelWhy this storage split works cleanly:
- Zero database bottleneck on telemetry: Updating a relational row 100,000 times per second is unnecessary because conflict detection only needs each drone's latest kinematics. If a Track Service node restarts, it replays the last 2 minutes of its Kafka partition to rebuild memory in seconds. (Why 2 minutes instead of 10 seconds? Because a silent drone stays in conflict testing for
10 sbefore turningLOSTplus60 swhileLOST=70 stotal; a shorter replay window would silently erase the exact lost drones operators cannot see!) - Canonical pair ordering (
drone_a < drone_b): Sorting the two IDs alphabetically plus the partial unique indexWHERE state = 'ACTIVE'guarantees at the database level that two drones can never open duplicate simultaneous alerts.
- Zero database bottleneck on telemetry: Updating a relational row 100,000 times per second is unnecessary because conflict detection only needs each drone's latest kinematics. If a Track Service node restarts, it replays the last 2 minutes of its Kafka partition to rebuild memory in seconds. (Why 2 minutes instead of 10 seconds? Because a silent drone stays in conflict testing for
High-level architecture
Cooperative Drones / GCS (100,000 airborne, 1 Hz telemetry over mTLS) | v +-------------------------------------------------------------------+ | Regional Ingest Gateways (stateless) | | mTLS cert == drone_id, signature check, WGS-84 check, recv_ms | +-----------------------------+-------------------------------------+ | key = drone_id v [ Kafka: telemetry ] -------------------------> [ Object Storage Archive ] | v +-------------------------------------------------------------------+ | Track Service (partitioned by drone_id) | | dedup/order by GNSS time, staleness & uncertainty, tile routing | +-----------------------------+-------------------------------------+ | key = area_shard_id (owner + border halo copies) v [ Kafka: tracks-by-shard ] | v +-------------------------------------------------------------------+ | Conflict Detectors (sharded by 25x25 km tiles, 2 active replicas) | | every 1 s (0.5 s urgent): extrapolate -> 1 km grid -> pair math | +-----------------------------+-------------------------------------+ | observations (key = pair) + shard "cycle_done" markers v +-------------------------------------------------------------------+ | Alert Manager (partitioned by canonical pair: drone_a < drone_b) | | dedup replicas/halos, hysteresis streaks, state <-> [ Alerts DB ]| +-----------------------------+-------------------------------------+ | AlertUpdate + 1 Hz Protection status v +-------------------------------------------------------------------+ | Delivery Service ---> WebSockets/gRPC to GCS & Operator Console | | ---> Automated voice/SMS fallback & Supervisor | +-------------------------------------------------------------------+Notice that the pipeline switches partitioning keys once, on purpose:
- Partitioned by
drone_idfirst (Ingest -> Track Service) so every packet fromuav_304lands on the same consumer in order, no matter where the drone flies. - Partitioned by geographic
area_shard_idsecond (Track Service -> Conflict Detectors) because two drones can only be compared if their states sit in memory on the same detector machine. - Partitioned by canonical pair
(drone_a, drone_b)third (Detectors -> Alert Manager) so every observation of that encounter—even across shard borders or active-active replicas—converges to one state machine.
- Partitioned by
Deep dive 1: telemetry ingestion, clocks, and stale tracks
Authentication and plausibility. At the gateway, mTLS binds each TLS client certificate to one
drone_idso Drone X cannot impersonate Drone Y. If telemetry hops through a multi-drone GCS relay, the drone's onboard flight controller also signs the payload (signature). Next, the gateway enforces basic physics and coordinate hygiene:- Single altitude reference: Every altitude must be height above the WGS-84 ellipsoid (the standard mathematical surface GPS satellites measure against). Mixing barometric pressure altitude with GPS ellipsoid height can easily introduce
20–50 mvertical offsets—wider than our15 mvertical separation! Non-WGS-84 reports are converted at the gateway using a geoid table or rejected. - Plausibility checks: Coordinates on Earth, speed
<= 1.2 x v_max(allowing slight GPS Doppler noise), and sane accuracy numbers. Impossible jumps (teleporting 2 km in 1 s) do not drop the drone; instead the track is markedtrust = SUSPECTwith an inflated uncertainty radius and flagged to the supervisor, because deleting a real drone with a glitching GPS receiver would be unsafe.
Ordering, duplicates, and broken clocks vs. delayed packets. The Track Service orders reports per drone using
(t_gnss_ms, seq):- Any packet with
seq <= stored.seqort_gnss_ms <= stored.t_gnss_msis a retry duplicate or out-of-order late arrival; it stays in the raw archive for audit, while live state keeps the newer report. - If a consumer lags behind a network burst by
> 1 s, it compacts the batch perdrone_idand jumps straight to the newest report—in collision warning, freshness beats processing stale intermediate points. - Clock fault vs. network delay: The gateway tracks a rolling baseline of
offset = recv_ms - t_gnss_ms(normally100–300 msof cellular transit).- If
t_gnss_msis> 1 sin the future, oroffsetshifts abruptly and stays shifted across consecutive packets, the drone's clock is faulty: stamp time usingrecv_ms - baseline_offset, widen uncertainty, and markSUSPECT. - If a single packet arrives with
recv_ms - t_gnss_ms = 6,000 ms, that is a delayed cellular packet, not a clock shift! Keep its truet_gnss_ms(6 seconds ago). Re-dating a delayed packet torecv_mswould pretend a 6-second-old position is where the drone sits right now—a classic, dangerous bug.
- If
Extrapolating aged reports into uncertainty cylinders. Between reports—or when a link drops—a drone keeps moving and may turn or accelerate. At detection cycle
t_cycle, a report measuredage = t_cycle - t_gnssseconds ago is extrapolated forward, and its point position expands into an uncertainty cylinder:t = 0 s (fresh report) age = 5 s (STALE) age = 15 s (LOST) ( * ) ( .---. ) ( .-------. ) p0, u = 5 m p0 + v*5s grows at v_max (30 m/s) u = 5 + 2*5 = 15 m because drone could turn anywhere! Extrapolated center at cycle time: p_now = p_report + v_report * age Horizontal uncertainty at +tau s: u_h(tau) = h_acc + 2.0 m/s * (age + tau) [LIVE / STALE] Vertical uncertainty at +tau s: u_v(tau) = v_acc + 0.5 m/s * (age + tau) [LIVE / STALE] Track state transitions by report age: LIVE (age <= 3 s) Normal testing, confidence = NORMAL. STALE (3 s < age <= 10 s) Larger radius from age; alerts tagged confidence = LOW. LOST (10 s < age <= 70 s) Velocity assumption breaks down -> radius grows by v_max * (age - 10 s); notify lost drone's operator + nearby operators; keep in grid for 60 s. ENDED Operator closed flight plan or landed confirmation received.- Single altitude reference: Every altitude must be height above the WGS-84 ellipsoid (the standard mathematical surface GPS satellites measure against). Mixing barometric pressure altitude with GPS ellipsoid height can easily introduce
Deep dive 2: spatial grid and area shards with halos
Deriving the spatial search bound from kinematics. Over a look-ahead window
Hseconds, each normalLIVEdrone travels at mostv_max * Hfrom its extrapolated cycle positionp_now. For normalLIVEGNSS reports (h_acc <= 30 m,age <= 3 s), current horizontal uncertaintyu_now = h_acc + 2 * age <= 36 msits comfortably below50 m, so at the end of windowHeach drone's uncertainty is at most50 + 2 * Hmeters. Two normal drones can violate horizontal separationS = 50 mwithinHseconds only if their current centersp_noware within distanceb_H:b_H = S + 2 * (v_max * H) + 2 * (50 + 2 * H) Tier window H Max reach distance b_H 1 km grid search radius Candidates (at 4/km²) 10 s (CRITICAL) 50 + 600 + 2 * (50 + 20) = 790 m 1 cell -> 3x3 km ( 9 km²) ~36 drones 30 s (WARNING) 50 + 1,800 + 2 * (50 + 60) = 2,070 m 3 cells -> 7x7 km (49 km²) ~196 drones 60 s (ADVISORY) 50 + 3,600 + 2 * (50 + 120) = 3,990 m 4 cells -> 9x9 km (81 km²) ~324 dronesWhy a 1 km uniform metric grid (projected into local meters, such as UTM coordinates) beats both a coarser 4 km grid and complex trees:
- A 4 km grid (
ceil(3,990 / 4,000) = 1cell radius ->3 x 3cells of 4 km =12 x 12 = 144 km²) checks 78% more area than a 1 km grid (9 x 9 = 81 km²), and cannot shrink the search box for the urgent 10 s tier (9 km²vs144 km²—a 16x saving!). - Unlike k-d trees or R-trees, inserting 10,000 drones into a flat 2D hash/array grid takes
O(N)array writes (~0.2 ms) every cycle and gives a provable zero-miss guarantee: any drone withinb_His mathematically guaranteed to sit withinceil(b_H / 1,000)cells along bothxandy. - Out-of-bound drones (
STALE,LOST,h_acc > 44 m, or speed in30..36 m/s): If a drone's own speed or uncertainty exceeds the normal50 m/30 m/sassumption, the detector computes that specific drone's personalb_Hand scans the wider cell ring around that drone, so abnormal tracks never slip through the grid filter. - Swept-box pre-filter: Most drones cruise at
10 m/s, not30 m/s. Before running square roots on a candidate pair, we check whether the axis-aligned bounding boxes of their[0, H]trajectory segments (inflated by uncertainty +S/2) overlap. Six float comparisons reject > 85% of grid candidates immediately.
Sharding across machines with border halos. We partition airspace into 25 km x 25 km tiles (dense metros assign 1 tile per detector shard; rural regions group many tiles onto 1 shard). What if Drone A is
100 mwest of a shard border and Drone B is100 meast of it?Shard West (owns Tile W) | Shard East (owns Tile E) +----------------------------------------+----------------------------------------+ | :<--- 4 km --->:<--- 4 km --->: | | : East's halo : West's halo : | | : * A | * B : | +----------------------------------------+----------------------------------------+We surround each shard's owned tiles with a 4 km border halo—a read-only boundary strip where the Track Service sends duplicate track updates of neighboring drones within 4 km of the border (wider for
LOSTdrones with larger radii).- Each shard tests
(owned drone, owned drone)and(owned drone, halo drone). - Notice that for normal drones
AandBacross the border, both Shard West and Shard East will detect(A, B)and emit an observation! That is intentional: the downstream Alert Manager is keyed by(drone_a, drone_b)and deduplicates observations per cycle. Trying to be clever with"only the shard owning the smaller drone_id emits"fails whenAisLOST(huge radius, copied far into East) whileBis normal (only copied 4 km, so West never seesB!). Letting any shard that sees the conflict emit it—and deduplicating by pair—is unconditionally safe.
- A 4 km grid (
Deep dive 3: pairwise trajectory math and recompute cadence
Why current distance is the wrong test. Two drones
1,000 mapart flying head-on at20 m/seach collide in25 seconds, whereas two drones80 mapart flying parallel along a delivery corridor never get closer. We must test predicted relative motion.Hold Drone A still at the origin
(0, 0, 0)and look at Drone B's relative positionr = p_b - p_aand relative velocityw = v_b - v_a. Attseconds into the future, their relative offset isr + w * t:- Horizontal separation lost when
(rx + wx * t)² + (ry + wy * t)² <= reach_h², wherereach_h = sep_h + unc_h_a + unc_h_b. Expanding the left side gives a standard quadratic inequalitya * t² + b * t + c <= 0:a = wx² + wy²(always>= 0)b = 2 * (rx * wx + ry * wy)c = rx² + ry² - reach_h²
- Vertical separation lost when
(rz + wz * t)² <= reach_v², wherereach_v = sep_v + unc_v_a + unc_v_b—the exact same quadratic helper witha = wz²,b = 2 * rz * wz,c = rz² - reach_v². - Conflict occurs if and only if the horizontal violation time interval
[t_h_start, t_h_end]and the vertical violation time interval[t_v_start, t_v_end]overlap inside[0, horizon_s].
import math from collections import namedtuple from typing import Optional, Tuple # Positions in local meters (x=east, y=north, z=up WGS-84), velocities in m/s, # and uncertainties already evaluated at the end of the tier window being tested. Track = namedtuple("Track", "x y z vx vy vz unc_h unc_v") def times_inside_quadratic( a: float, b: float, c: float, horizon_s: float ) -> Optional[Tuple[float, float]]: """Return the sub-interval (start, end) of [0, horizon_s] where a*t^2 + b*t + c <= 0.""" # Near-zero relative speed: gap stays essentially constant over the window. if a < 1e-12: if c <= 0.0: return (0.0, horizon_s) return None discriminant = b * b - 4.0 * a * c if discriminant < 0.0: # Trajectory never enters the protected distance. return None root = math.sqrt(discriminant) # Clamp both roots to the look-ahead window [0, horizon_s]. enter_t = max((-b - root) / (2.0 * a), 0.0) exit_t = min((-b + root) / (2.0 * a), horizon_s) if enter_t > exit_t: # Crossing happened entirely in the past (< 0) or after horizon_s. return None return (enter_t, exit_t) def first_conflict_time( drone_a: Track, drone_b: Track, horizon_s: float, sep_h_m: float = 50.0, sep_v_m: float = 15.0, ) -> Optional[float]: """Earliest time in [0, horizon_s] when BOTH horizontal and vertical separation fail.""" rx = drone_b.x - drone_a.x ry = drone_b.y - drone_a.y rz = drone_b.z - drone_a.z wx = drone_b.vx - drone_a.vx wy = drone_b.vy - drone_a.vy wz = drone_b.vz - drone_a.vz reach_h = sep_h_m + drone_a.unc_h + drone_b.unc_h reach_v = sep_v_m + drone_a.unc_v + drone_b.unc_v horiz_window = times_inside_quadratic( wx * wx + wy * wy, 2.0 * (rx * wx + ry * wy), rx * rx + ry * ry - reach_h * reach_h, horizon_s, ) if horiz_window is None: return None vert_window = times_inside_quadratic( wz * wz, 2.0 * rz * wz, rz * rz - reach_v * reach_v, horizon_s, ) if vert_window is None: return None # Conflict starts when the second dimension also enters violation. overlap_start = max(horiz_window[0], vert_window[0]) overlap_end = min(horiz_window[1], vert_window[1]) if overlap_start > overlap_end: return None return overlap_startWhy this closed-form quadratic beats discrete time-stepping: at
60 m/shead-on closing speed, two drones cross30 mevery0.5 s, so steppingt = 0.0, 0.5, 1.0, ...can literally jump straight across a corner clip of the 50 m cylinder without noticing! We also compute the closest point of approach (CPA)—the momentt_cpa = clamp(-(rx*wx + ry*wy) / (wx² + wy²), 0, horizon_s)when horizontal separation reaches its minimummiss_distance_m—for display on the operator's screen.Mini-trace on a concrete corridor encounter. Suppose
uav_304is at(0, 0, 80 m)flying east at+16 m/sanduav_719is at(d, 20 m, 86 m)flying west at-16 m/s(32 m/sclosing speed,20 mlateral pass <50 mlimit,6 mvertical offset <15 mlimit), both fresh (age = 0) withh_acc = 10 m:Tier H End-of-window unc_h reach_h = 50 + 2*unc_h Fires when x-gap d <= sqrt(reach_h² - 20²) + 32*H 60 s 10 + 2*60 = 130 m 310 m sqrt(310² - 400) + 1,920 = 309.4 + 1,920 = ~2,229 m (ADVISORY, ~70 s to CPA) 30 s 10 + 2*30 = 70 m 190 m sqrt(190² - 400) + 960 = 188.9 + 960 = ~1,149 m (WARNING, ~36 s to CPA) 10 s 10 + 2*10 = 30 m 110 m sqrt(110² - 400) + 320 = 108.2 + 320 = ~428 m (CRITICAL, ~13 s to CPA)Testing each tier with its own end-of-window uncertainty (
30 mfor 10 s rather than130 mfrom 60 s) keeps urgentCRITICALalerts razor-sharp while giving earlyADVISORYheads-up further out.Recompute cadence. Each shard runs a full synchronous snapshot tick every 1.0 second (extrapolating all tracks to the exact same
t_cyclebefore building the 1 km grid), plus a lightweight 0.5-second sub-tick for the inner3x3cell ring (10 sCRITICAL tier), cutting worst-case scheduling wait in half for imminent collisions while keeping CPU load steady and detectors completely stateless.- Horizontal separation lost when
Deep dive 4: alert lifecycle, hysteresis, and latency budget
Managing multi-tick alert state machines. A head-on pair stays in conflict across 30–70 consecutive 1-second detector ticks. If every tick paged the operator, 50 notifications would drown the console. Instead, stateless detectors emit raw
observationrecords, and the stateful Alert Manager (partitioned by(drone_a, drone_b)) maintains one alert state machine per pair:conflict seen [ No Active Alert ] -------------> [ ACTIVE (v1): push + sound ] ^ | ^ | 3 confirmed-clear | tier rises | conflict returns | cycles in a row | (immediate!) | within 30 s | v | (reopen, v+1) +------------------------ [ ACTIVE (v2+): silent metric refresh; ] [ downgrade tier only after 3 cycles ]Three rules prevent noise and silent false-clears:
- Hysteresis against flapping: Hysteresis means requiring a stronger or sustained change to step down an alert than to step it up. Escalating (
ADVISORY -> WARNING -> CRITICAL) fires immediately on a single cycle; downgrading severity or transitioning toRESOLVEDrequires 3 consecutive cycles at the lower state, so GPS jitter near1,149 mnever flickers the alarm on and off every second. Re-entering conflict within 30 seconds reopens the samealert_id(version + 1) rather than spawning a brand-new incident. - Confirmed clear vs. missing shard:
clear_streakincrements only when the Alert Manager receives the"cycle_done"marker from the shard(s) owning both drones for cycleTand neither emitted the pair. If a shard crashes or stalls,clear_streakfreezes—missing data means unknown, never clear. - Tiering by conflict entry time (
t_conflict_s), not onlyt_cpa_s: Two drones converging at a shallow 5-degree angle may cross inside 50 m horizontal separation 25 seconds before their closest point of approach. Tiering ont_conflict_s(<= 60 sADVISORY,<= 30 sWARNINGwith 10 s human-ack timer,<= 10 sCRITICALwith immediate supervisor alert) warns before separation is first lost.
End-to-end p99 latency budget (target <= 2,500 ms):
Stage p99 budget 1. Drone GNSS measurement -> regional gateway (LTE/5G) 500 ms 2. Gateway mTLS, checks, Kafka append 50 ms 3. Track Service update + shard/halo routing 100 ms 4. Wait for next detector tick <= 1,000 ms (<= 500 ms for 10 s CRITICAL ring) 5. Detector grid build + pair math (capped <= 30% CPU) 300 ms 6. Alert Manager DB upsert + Delivery Service push 300 ms 7. GCS UI render + audio alarm trigger 200 ms ------------------------------------------------------------------ Total end-to-end p99 2,450 ms (500 ms faster on CRITICAL sub-tick)- Hysteresis against flapping: Hysteresis means requiring a stronger or sustained change to step down an alert than to step it up. Escalating (
Scaling, failure handling, and trade-off summary
Handling a 10x regional traffic surge. Ingestion and Track Service scale linearly (
O(N)) by adding Kafka partitions. Detection scales asO(N * local_density):10xdrones in the same metro means10xdrones times10xneighbors =100xpair checks (~3M/s -> ~300M/s), saturating that region's Conflict Detector shards first. Our three-step defense:- Prioritize inner rings (load shedding with transparency): Each cycle evaluates the
10 sCRITICAL3x3ring first (~6% of pair work), then30 s, then60 s. If the60 sring hits the cycle deadline, affected drones receiveProtection: DEGRADED(never silent drops) whileCRITICALandWARNINGstay 100% live. - Dynamic tile splitting + swept-box pre-filter: Split hot
25 x 25 kmtiles into12.5 x 12.5 kmsub-tiles across pre-warmed spare detector nodes (4 km halos keep borders exact). - Upstream airspace flow control: At 40 drones/km², physical conflicts become constant; feed shard saturation back to the flight-authorization system to pause new takeoffs into that sector.
Fail-safe behavior and pipeline monitoring:
Component failure System response (always recovery or NOT_PROTECTED, never silence)Single detector replica dies Zero gap: each shard runs 2 active-active replicas in separate availability zones; Alert Manager deduplicates (pair, cycle_ms).Both replicas of a shard fail covered_until_msexpires within 3 s -> GCS displays redNOT_PROTECTEDbanner + tone; active alerts stay open; on-call paged.Track Service node crashes Standby consumer replays last 2 minutes of Kafka telemetry(recoveringLIVE,STALE, andLOSTtracks) in < 5 s.GCS link drops during WARNINGMissing DeliveredACK after 3 s triggers automated voice call + SMS to registered operator phone; missing humanAckat 10 s pages supervisor.To verify the live pipeline continuously, synthetic canary pairs—two virtual test drones flying a scripted head-on collision course—are injected through the real ingest gateway into every shard once per minute; if a canary alert does not arrive within
2.5 s, on-call is paged before a real drone ever needs it.Key trade-offs recap
- Conservative growing margins vs. precision: Expanding uncertainty with report age and window length prevents missed collisions on late telemetry, while tiered windows (
10/30/60 s) and 3-cycle hysteresis prevent alert spam. - Dual partitioning (by
drone_idthen byarea_shardwith 4 km halos): Costs one extra Kafka routing hop and duplicate border evaluations, but gives ordered per-drone state AND horizontally scalable local pair checks with zero missed cross-border collisions. - 1 s snapshot cycles + 0.5 s urgent sub-ticks vs. per-packet event-driven checks: Adds up to 0.5–1.0 s of tick wait, in exchange for predictable CPU budgets, exact same-instant trajectory comparisons, and stateless active-active detector replicas.
- Prioritize inner rings (load shedding with transparency): Each cycle evaluates the
Intuition & how it works
Think of each flying drone as carrying an invisible safety flashlight beam pointed along its current flight path, plus a protective uncertainty bubble that swells whenever its radio goes quiet or we look further into the future. Two drones are headed for trouble only if their beams pass through the same patch of sky at the same moment within the next 60 seconds. And because silence from a safety system looks identical to safe skies, the monitor also sends each operator a 1-second "still watching you" heartbeat—if that heartbeat ever stops, a warning banner lights up immediately.
A naive design would compare every airborne drone against every other drone every second using only their current GPS coordinates. That fails in two ways: in a busy metro with 10,000 drones, checking all 10,000 x 9,999 / 2 = 50 million pairs every second wastes massive CPU on drones 40 km apart, while checking current distance misses two fast drones 800 m apart hurtling head-on at 30 m/s and falsely nags two slow drones flying safely in parallel 90 m apart. Worse, if a drone loses cellular reception for 8 seconds, a naive tracker that either freezes its old point or deletes it hides a moving hazard.
Walk through a concrete 3-drone snapshot at t = 0:
uav_304sits at(0, 0, 80 m)flying east at+16 m/s;uav_719sits at(960 m, 20 m, 86 m)flying west at-16 m/s;uav_812sits 6 km north.- Spatial grid filter: Because max speed is
30 m/s, no pair more than~4 kmapart can meet within 60 s. Placing drones into a1 km x 1 kmgrid immediately rules outuav_812without running any trajectory math, while pairinguav_304anduav_719inside the30 ssearch ring. - Quadratic relative-motion test: Holding
uav_304still,uav_719closes horizontally at32 m/s(960 m / 32 m/s = 30 sto a20 mhorizontal and6 mvertical pass, well inside the50 mhorizontal and15 mvertical limits). Solving the quadratic distance inequality flags separation loss inside the30 stier -> severityWARNING. - Stateful alert lifecycle: The Alert Manager opens one canonical
("uav_304", "uav_719")alert (version = 1), pushes it to both operators, waits for automatic softwareDeliveredreceipts within 1 s and humanAckclicks within 10 s, refreshes countdown numbers silently on later 1-second cycles, and closes the alert only after 3 consecutive confirmed-clear cycles once the drones pass or turn away.
Key trade-offs
- Expanding uncertainty margins vs. false-alarm rate: Treating an aged report or a 60-second prediction as an expanding radius (
h_acc + 2 m/s * (age + window)) catches drones that drift or suffer delayed cellular packets, at the cost of wider protected zones. Evaluating three separate windows (10 s,30 s,60 s) with each window's own end-of-window margin keeps imminentCRITICALalerts tight while letting distantADVISORYalerts stay conservative. - Constant-velocity trajectory + growing margin vs. worst-case reachable disc: Predicting straight-line motion along current velocity matches normal flight paths; alerting whenever two worst-case
30 m/sdiscs merely touch would flag nearly every pair within 4 km over 60 seconds and make the console unusable. We reserve the worst-case30 m/sreach bound strictly for candidate selection on the grid (where being generous only costs microseconds of CPU), and rely on the next 1 Hz report to catch sudden turns. - Uniform 1 km grid vs. spatial trees (k-d tree / R-tree): A flat 1 km grid sized from physics rebuilds from scratch in
O(N)array operations every second and is trivial to prove complete (ceil(bound / 1000)cells). Spatial trees adapt better to skewed clustering, but are slower to rebuild at 1 Hz and much harder to certify free of corner-case misses. - Dual partitioning keys (
drone_idthenarea_shardwith halos): Partitioning ingestion bydrone_idguarantees in-order state per drone, while re-partitioning into geographic tiles with halos (read-only boundary strips copying border drones to adjacent shards) enables local pair checks across machines. The price is one extra Kafka hop and duplicate cross-border detections that the Alert Manager merges by pair. - Fixed 1 s snapshot ticks (+ 0.5 s urgent ring) vs. event-driven per-packet checks: Periodic snapshots compare all drones extrapolated to the exact same timestamp, keep detectors stateless, and make CPU load predictable, at the cost of up to
0.5–1.0 sof scheduling wait. Event-driven checks shave latency slightly but create bursty load and require complex incremental spatial state. - Active-active detector replicas vs. leader-standby failover: Running two live detector replicas per shard doubles a cheap CPU workload (a few cores) to eliminate multi-second failover blind spots on a safety-critical path.
Common mistakes
- Testing current distance instead of predicted relative velocity, which alerts far too late on fast head-on approaches and spams constant false alerts on parallel flight corridors.
- Running O(N²) all-pairs comparisons without bounding the search radius from maximum airspeed, look-ahead horizon, and position uncertainty.
- Treating last-known position as exact—or dropping silent drones, which erases the exact lost drone whose radio just failed instead of expanding its uncertainty bubble and warning nearby operators.
- Ordering reports by server arrival time or re-stamping delayed packets with
now(), which allows a 6-second-old buffered cellular packet to overwrite a newer position or masquerade as current. - Sharding by geography without border halos (missing collisions right across tile lines), or suppressing halo duplicates with
"only the lower shard ID emits"(which silently drops conflicts when aLOSTdrone's wide radius reaches into a neighbor shard whose normal drone wasn't copied back). - Skipping hysteresis and per-pair deduplication (hysteresis means requiring multiple clear cycles before stepping down an alert), causing operators to receive 60 duplicate pings per minute or rapid
WARNING <-> ADVISORYflickering near boundary distances. - Treating missing shard output as "airspace clear", turning a crashed detector or network partition into a silent loss of collision protection instead of triggering
NOT_PROTECTEDbanners. - Mixing barometric altitude with GNSS ellipsoid height, introducing 20–50 m vertical datum mismatches that exceed the 15 m vertical separation threshold.
Follow-up questions
- What architectural changes are required if the platform must transmit automated evasive maneuvers directly to the aircraft instead of only advising human pilots? Moving from advisory alerts to closed-loop flight control means an erroneous command can cause a mid-air collision rather than merely fail to warn about one. Avoidance trajectories must be synthesized deterministically and symmetrically for both aircraft (similar to aviation's TCAS/ACAS Xu—for example, instructing one vehicle to climb/turn right and the other to descend/turn right), checked for secondary conflicts against all surrounding tracks before dispatch, and delivered over a mutually authenticated low-latency command channel with strict execution acknowledgments. If either drone fails to confirm receipt or its next position report deviates from the commanded maneuver, the planner must reclassify that vehicle as an uncooperative hazard and recompute a solo escape trajectory for the compliant drone, backed by onboard sense-and-avoid autonomy whenever wireless links fail entirely.
- How would you integrate non-cooperative air traffic detected solely through noisy ground-radar feeds? Introduce a multi-target radar tracking stage ahead of the Track Service: correlate raw radar blips across successive sweeps (via spatial gating and nearest-neighbor or joint probabilistic data association), promote tentative detections only after repeated hits (such as
3 out of 5scans) to reject birds and ground clutter, and run a Kalman filter (a recursive state estimator that fuses noisy observations over time to infer smoothed position, velocity, and an error covariance matrix). Correlate and merge radar tracks against authenticated cooperative telemetry so a reporting drone never triggers a phantom conflict with its own radar reflection, then insert remaining non-cooperative tracks into the spatial grid with covariance-inflated uncertainty radii and larger crewed-aircraft separation buffers, sending alerts exclusively to the cooperative drones' operators. - Suppose drone density inside a single metropolitan sector spikes 10x. Which subsystem hits its capacity ceiling first, and how should the platform respond? Ingestion and per-vehicle state updates scale linearly (
10x), whereas candidate pair evaluations inside a fixed geographic footprint grow quadratically (10xvehicles multiplied by10xlocal neighbors =100x, jumping from~3Mto~300Mpair checks/s), causing that sector's Conflict Detector shards to exhaust their 1-second CPU budget first. First, shed outer-horizon work transparently inside each tick by evaluating the10 sCRITICAL3x3cell ring first (~6% of pair checks), then the30 sring, and publishingProtection: DEGRADEDif the60 sring runs out of budget—never dropping checks silently. Next, subdivide hot25 x 25 kmtiles across pre-warmed spare detector nodes (retaining 4 km border halos) alongside swept-box pre-filtering; finally, apply upstream launch throttling in the flight-authorization layer because40 drones/km²generates constant physical conflicts that overwhelm human pilots regardless of compute capacity. - What verification and operational evidence would you present to aviation authorities to certify that genuine separation violations are not missed? Build a structured safety assurance case connecting explicit kinematic assumptions to formal tests and live telemetry monitoring. First, prove grid candidate completeness algebraically from
v_max, separation minimums, and uncertainty growth (ceil(b_H / cell_size)grid cells plus 4 km shard halos), and validate the spatial detector against an exhaustiveO(N²)all-pairs oracle across millions of recorded and adversarial flight paths (head-on approaches, shallow-angle merges, vertical climbs, tile-boundary crossings, and delayed packets). Second, cross-check the closed-form quadratic solver against millisecond-step numerical integration, run chaos fault injection (terminating detector replicas, stalling Kafka partitions, skewing clocks, injecting spoofed frames) to demonstrate every failure surfaces either an alert or aNOT_PROTECTEDstatus within 3 seconds, and log continuous live proof via 1-minute synthetic canary collision pairs paired with documented operational envelopes.
Follow-up questions
- What architectural changes are required if the platform must transmit automated evasive maneuvers directly to the aircraft instead of only advising human pilots?
- How would you integrate non-cooperative air traffic detected solely through noisy ground-radar feeds?
- Suppose drone density inside a single metropolitan sector spikes 10x. Which subsystem hits its capacity ceiling first, and how should the platform respond?
- What verification and operational evidence would you present to aviation authorities to certify that genuine separation violations are not missed?
Similar questions
- Isolated Multi-Tenant Analytics Engine with ABAC and Audit Compliance
- Scalable Interview Question Repository and Live Selection System
- Design a Pull-Based Fleet Metrics Collector
- Design a Governed Tool Catalog and Execution Gateway for AI Agents
- Cart Checkout Pricing with Half-to-Even Unit Vouchers
- Aligning on Compensation, Logistics, and Hiring Timelines
More Palantir interview questions
- Maximizing Cart Discounts Within a Point Budget Medium
- Cart Checkout Pricing with Half-to-Even Unit Vouchers Medium
- Design a Pull-Based Fleet Metrics Collector Easy Pro
- Design a Governed Tool Catalog and Execution Gateway for AI Agents Medium Pro
- Shortest Hops and Distance on Two-Way Roads Easy Pro
- Inverted Interest Index and Shared Employee Pairs Medium Pro
- Grid Snake Simulation with Per-Move Scores Medium Pro
- Checkout Total Under Capped Multiplicative Coupons Medium Pro
- Isolated Multi-Tenant Analytics Engine with ABAC and Audit Compliance Medium Pro
- Scalable Interview Question Repository and Live Selection System Hard Pro