Live Electric Fleet Telemetry and Control Platform
Medium · System Design · Software Engineer · Technical Screen
Prompt
You are in a full-stack system design interview with a connected electric-vehicle platform team.
Architect an internal web application for engineers and operations specialists to monitor live fleet measurements—including road speed, interior climate temperature, and battery state of charge—and control per-vehicle data sharing. Address each of the following areas:
- On-vehicle collection & uplink: How onboard hardware samples sensors, handles intermittent cellular coverage, and transmits readings to the cloud.
- Ingestion, validation & storage: How the backend receives, verifies, persists, and serves near-real-time snapshots alongside historical time-series data.
- Internal APIs & web UI: What REST/streaming endpoints and frontend views you would build, including a dedicated lookup returning the most recent speed of a given vehicle (for example,
veh_804). - Per-vehicle outbound shutoff: How an authorized operator can disable telemetry for a specific unit (for example,
veh_519) whenever the organization requires that vehicle's measurements to cease reaching external systems. - AI-assisted engineering workflow: How you would pair with an AI coding assistant to speed up implementation while preserving system invariants, security boundaries, and code quality.
Scope & Expectations
- End-to-end telemetry architecture: Cover vehicle-to-cloud transport, stream validation, storage separation for live versus historical queries, and out-of-order protection on latest-speed reads.
- Full-stack API & UI design: Define clean internal contracts and responsive dashboard components that surface data freshness honestly.
- Provable shutoff controls: Show how disabling telemetry for a vehicle stops outbound data flow immediately and converges reliably even if the vehicle is temporarily offline.
- Disciplined AI-assisted development: Detail which tasks you delegate to an AI assistant versus keep human-authored, and how automated tests and review gates catch subtle defects.
Step-by-step walkthrough
Clarify requirements and scope
Telemetry just means automatic measurements sent from a remote device—here, sensors inside an electric vehicle reporting speed, cabin temperature, and battery level over a cellular connection.
Four distinct engineering problems hide inside this single prompt: 1. A write-heavy ingestion pipeline: hundreds of thousands of moving cars sending small sensor batches over unreliable cellular networks. 2. A low-latency internal web app: engineers and support staff looking up one car's live speed or plotting its recent sensor history. 3. A provable control path back to the car ("stop sending data"): when the company disables telemetry for a vehicle, data flow to external systems must stop immediately and verifiably, even if that car is parked in an underground garage with no cell signal. 4. An AI-assisted engineering workflow: moving fast with an AI coding assistant without introducing subtle ordering bugs, auth holes, or leaked vehicle data.
Functional requirements
- Each vehicle samples ~20 sensor signals (speed, cabin temperature, battery state of charge, ignition state, etc.) and transmits them to the backend.
- The backend ingests, validates, and stores those measurements, serving both the latest snapshot and historical time-series charts.
- Internal users get a searchable fleet table, a single-vehicle live view, a low-latency API to fetch the latest speed of a specific vehicle, and a role-restricted control panel to manage per-vehicle telemetry policy.
- Operators can disable telemetry for a specific vehicle so its data stops flowing to external systems.
- Every lookup of an individual vehicle and every policy change is recorded in an immutable audit log.
Non-functional requirements
- Freshness: while a car is driving online, a measurement reaches the backend within 5 seconds at p95 (p95 means 95% of measurements arrive at least this fast), and within 2 seconds when an engineer switches a specific car into temporary "live mode".
- Read latency: the "latest speed" API responds in under 50 ms at p99 (99% of requests finish within 50 ms).
- Zero silent gaps from brief outages: when a car drives through a tunnel or dead zone, it buffers measurements locally and uploads them once connectivity returns.
- Security and privacy: cars authenticate with factory-provisioned cryptographic certificates; internal employees log in via corporate SSO (Single Sign-On) with role-based permissions; speed and location are treated as sensitive personal data.
Assumptions to state out loud
- Fleet size: 1,000,000 connected vehicles total, with 15% (150,000) driving at peak rush hour and 5% (50,000) driving on average across a 24-hour day (meaning an average of
0.05 × 24 = 1.2 hoursof driving per car per day). A smaller pre-production test fleet uses the exact same architecture with fewer server instances. - Sampling vs. sending: driving cars sample sensors at 1 Hz (once per second) and transmit one compressed batch every 5 seconds. Parked cars send a lightweight heartbeat every 5 minutes (300 seconds).
- Internal audience: ~2,000 engineers and support specialists, with at most ~200 live dashboards open simultaneously.
- What "stop sending data to external systems" means: the phrase has two practical interpretations, so one per-vehicle policy supports both modes:
INTERNAL_ONLY: the car still reports to our internal backend for diagnostics, but our backend blocks all forwarding to third parties (insurance partners, commercial fleet integrations, analytics vendors).OFF: the car stops transmitting telemetry altogether, and our backend also drops any packets from it at the edge. Legally mandated safety features such as automatic crash emergency calling live on a separate hardware path outside this switch.
Back-of-the-envelope numbers
Before picking databases or protocols, we estimate message rates, bandwidth, and storage from our assumptions so the numbers guide our architecture.
Fleet & message sizes Total connected vehicles 1,000,000 Driving at peak / daily average 150,000 (15%) / 50,000 (5%, or 1.2 h/day per car) Parked at peak / daily average 850,000 (85%) / 950,000 (95%, or 22.8 h/day per car) Driving batch (every 5 s) 5 samples × 20 signals ≈ 1 KB (1,000 B) binary payload + headers Parked heartbeat (every 5 min) 1 snapshot ≈ 200 B Peak ingestion rate Driving messages 150,000 cars / 5 s = 30,000 msg/s (~30.0 MB/s) Parked heartbeats 850,000 cars / 300 s ≈ 2,833 msg/s (~0.6 MB/s) Total peak ingest ~32,800 msg/s ≈ 31 MB/s Peak sample rows 150,000 cars × 1 row/s = 150,000 rows/s (1 wide row = all 20 signals) Daily volume & storage (at 50k average driving, 950k average parked) Average message rate 50,000 / 5 s + 950,000 / 300 s ≈ 13,167 msg/s (~1.14B msg/day) Raw network bytes per day (10,000 × 1 KB + 3,167 × 200 B) × 86,400 s ≈ 919 GB/day (~0.92 TB/day) Time-series rows per day 50,000 driving × 86,400 s + heartbeats ≈ 4.6B rows/day Compressed time-series storage 4.6B rows × ~100 B raw ≈ 460 GB/day raw -> ~90 GB/day at 5x compression 30-day full-resolution retention 30 × 90 GB ≈ 2.7 TB per replica Latest-state memory & internal read traffic Latest snapshot in RAM 1,000,000 vehicles × ~1 KB/car ≈ 1 GB total Internal live UI updates ~200 open dashboards × ~50 visible cars × 1 push/s ≈ 10,000 pushes/s Internal REST API calls a few hundred requests/s Monthly cellular usage per car Driving (1.2 h/day) (3,600 s / 5 s) × 1 KB = 720 KB/h -> 864 KB/day -> ~26 MB/month Parked (22.8 h/day) (22.8 × 12 heartbeats) × 200 B ≈ 55 KB/day -> ~1.6 MB/month Total per vehicle ~28 MB/monthThree design lessons jump straight out of this math: 1. Writes outnumber reads by roughly 100 to 1. ~33,000 batches/s flow in from cars while internal users make only a few hundred API requests/s. Meanwhile, the entire fleet's latest state fits in ~1 GB of RAM, so serving
/latestfrom memory will be effortlessly fast if we protect the write path. 2. Store one wide row per timestamp, not one narrow row per sensor. Putting all 20 signals of a 1-second tick into a single row writes 150,000 rows/s instead of150,000 × 20 = 3,000,000rows/s—a 20x reduction in row overhead. 3. Batching is our main cellular and server cost lever. Grouping five 1-second samples into one 5-second packet cuts message count 5x. Streaming every single second (150,000 msg/s) should only be turned on temporarily when an engineer actively clicks "Live mode" on one specific car.APIs and frontend components
Vehicle-to-cloud protocol: MQTT over mutual TLS (mTLS)
Instead of opening a fresh HTTP request every 5 seconds, each car maintains one lightweight persistent connection using MQTT (Message Queuing Telemetry Transport, a publish/subscribe protocol designed for lossy mobile networks) over mTLS (mutual Transport Layer Security, where both the server and the car prove their identity using cryptographic certificates). Payloads are encoded with Protocol Buffers (Protobuf), a compact typed binary format that uses far fewer bytes than JSON. Topic names use an internal random
vehicle_idrather than the VIN (Vehicle Identification Number, the regulated 17-character chassis serial number) so broker logs do not leak personal identifiers.MQTT topics (port 8883, mTLS) Car publishes: v1/vehicles/{vehicle_id}/telemetry Live 5 s sensor batches (Protobuf, QoS 1) v1/vehicles/{vehicle_id}/backfill Buffered batches uploaded after an offline gap (rate-capped) v1/vehicles/{vehicle_id}/config/reported Policy version the car confirms it has applied Car subscribes: v1/vehicles/{vehicle_id}/config/desired Retained message holding the target telemetry policy v1/vehicles/{vehicle_id}/commands On-demand commands (e.g., live_mode for 10 min, report_now)// Protobuf wire contract between vehicle and cloud message TelemetryBatch { string vehicle_id = 1; uint64 seq = 2; // Strictly increasing +1 per batch, saved in flash across reboots uint32 schema_version = 3; uint32 policy_version = 4; // Policy version active on the car when this batch was recorded bool ignition_on = 5; repeated Sample samples = 6; } message Sample { int64 ts_ms = 1; // UTC epoch milliseconds from GPS / cellular-synced vehicle clock optional float speed_kph = 2; // 'optional' distinguishes "sensor did not report" from 0.0 km/h optional float cabin_temp_c = 3; optional float soc_pct = 4; // Battery state of charge (0-100%) // ... ~20 signals total; new signals get new field numbers, retired numbers are never reused }Internal backend APIs: REST + WebSocket
Internal employees authenticate with corporate SSO. We use standard REST (HTTP JSON endpoints) for lookups, historical queries, and policy changes, and a WebSocket (a persistent two-way browser-to-server connection) solely to push live sensor ticks to open dashboards.
GET /v1/vehicles?fleet=eng-west&status=online&page_token=... -> Paginated fleet list with latest speed, cabin temp, battery %, connection state, and policy mode GET /v1/vehicles/{id}/latest?signals=speed_kph,cabin_temp_c -> 200 OK { "vehicle_id": "veh_804", "signals": { "speed_kph": {"value": 84.0, "sample_ts_ms": 1795948867123, "age_ms": 1620} }, "connection": "online", "freshness": "live" // one of: live | stale | offline | telemetry_off | never_reported } GET /v1/vehicles/{id}/telemetry?signals=speed_kph,cabin_temp_c&from=...&to=... -> Downsampled historical series (capped at ~2,000 min/max/avg buckets per chart) WS /v1/stream -> Client sends: {"subscribe": ["veh_804", "veh_809"], "signals": ["speed_kph", "cabin_temp_c"]} -> Server pushes 1 Hz UI diffs for up to 100 subscribed vehicles per browser tab PUT /v1/vehicles/{id}/telemetry-policy (Header: If-Match: 7) Body: {"mode": "OFF", "reason": "Executive fleet opt-out", "ticket": "OPS-2084"} -> 202 Accepted {"desired_version": 8, "reported_version": 7, "state": "PENDING_VEHICLE_ACK", "backend_enforced": true} POST /v1/vehicles/{id}/commands Body: {"type": "live_mode", "duration_s": 600}Why return
202 Acceptedinstead of200 OKwhen changing telemetry policy? Because the car might be parked in an underground garage for three days. Our backend enforces the block within seconds (backend_enforced: true), whilePENDING_VEHICLE_ACKhonestly tells the operator the car itself has not yet woken up and confirmed version 8. Notice also theIf-Matchheader (optimistic concurrency control): it prevents two operators who open the dialog at the same time from accidentally overwriting each other's changes.Frontend components (React + TypeScript)
- Virtualized fleet table: UI virtualization means rendering only the ~30 table rows currently visible in the browser viewport rather than creating 10,000 DOM nodes. The table subscribes over the shared WebSocket only to those ~30 visible
vehicle_ids and batches screen redraws to once per second so rapid updates never freeze the browser. - Single-vehicle live dashboard: displays big numeric tiles for speed, cabin temperature, and battery level—each paired with an unmistakable freshness badge (
Live,Stale (42s ago),Offline, orTelemetry OFF) so nobody ever mistakes a frozen reading from a tunnel for live highway speed. Includes a 15-minute scrolling chart, a historical date-range picker, and a "1 Hz Live Mode (10 min)" toggle button. - Telemetry policy & audit drawer: visible only to authorized privacy/operations roles. Shows current mode (
ON,INTERNAL_ONLY,OFF),desired_versionvs.reported_version, enforcement status across backend and vehicle, a confirmation modal requiring a ticket ID and written reason, and the full change history. - Sensor validation inspector: lists recent flagged or rejected packets for that car (for example,
cabin_temp_c = 140°Cflaggedout_of_range) so vehicle engineers can spot faulty sensors or bad firmware builds.
- Virtualized fleet table: UI virtualization means rendering only the ~30 table rows currently visible in the browser viewport rather than creating 10,000 DOM nodes. The table subscribes over the shared WebSocket only to those ~30 visible
Data model and storage tiers
No single database handles transactional policy audits, sub-millisecond single-key reads at 33k writes/s, and multi-billion-row historical charts equally well. Splitting storage by access pattern keeps each store simple:
1. Relational metadata & policy store (PostgreSQL) vehicle vehicle_id (PK), vin_encrypted, model, model_year, fleet_id, firmware_version, cert_fingerprint, created_at telemetry_policy vehicle_id (PK), mode (ON | INTERNAL_ONLY | OFF), desired_version, reported_version, reported_at, updated_by, updated_at policy_audit_log audit_id (PK), vehicle_id, old_mode, new_mode, version, actor_id, ticket_id, reason, created_at [append-only] access_audit_log audit_id (PK), actor_id, vehicle_id, action, created_at 2. Latest-state store (Redis Cluster + compacted Kafka backup topic `vehicle-latest`) Hash key `veh:{vehicle_id}`: speed_kph, speed_kph:ts, cabin_temp_c, cabin_temp_c:ts, soc_pct, soc_pct:ts, ... ignition_on, expected_interval_ms, state_ts, connection ("online" | "offline"), policy_mode ("ON" | "INTERNAL_ONLY" | "OFF"), policy_version 3. Historical time-series store (ClickHouse — a columnar database) telemetry_samples vehicle_id, sample_ts_ms, received_ts_ms, speed_kph, cabin_temp_c, soc_pct, ..., quality_flags[] Partitioned by day, sorted by (vehicle_id, sample_ts_ms), TTL 30 days telemetry_1m_rollup vehicle_id, minute_ts, min/max/avg per signal, TTL 2 years 4. Raw immutable archive (Object storage like S3, in Parquet columnar files) Every validated batch stored by date/hour for long-term analytics and pipeline replayTwo key concepts make this layout fast and recoverable: - Columnar database (ClickHouse): unlike row-oriented databases (PostgreSQL) that store all columns of a row together on disk, a columnar store writes each column (
speed_kph,cabin_temp_c) in its own contiguous compressed file. When an engineer plots 6 hours of speed forveh_804, ClickHouse reads only thespeed_kphandsample_ts_msbytes forveh_804(which sit next to each other because the table is sorted by(vehicle_id, sample_ts_ms)) and achieves ~5x compression on smooth sensor numbers. - Compacted Kafka topic (vehicle-latest): Apache Kafka is a distributed append-only event log, and log compaction tells Kafka to retain at least the newest message for everyvehicle_idkey forever while discarding older superseded updates. That lets us treat Redis as a fast in-memory cache: if a Redis shard ever loses memory, a replacement node replaysvehicle-latest(~1M keys) and rebuilds the fleet's latest state in a few minutes.High-level architecture
[ Vehicle: Sensors -> CAN Bus -> Gateway -> Telematics Control Unit (TCU) ] (Samples 1 Hz, batches every 5 s, 72 h flash ring buffer, local policy switch) | | MQTT over mTLS (port 8883, factory client certificate) v [ MQTT Broker Cluster ] <--------------------------+ (Per-car ACL: car X can only use v1/vehicles/X/...) | | | v | [ Kafka: telemetry.raw (key = vehicle_id) ] | | | v | [ Stateful Stream Validator ] -------------------> [ Kafka: telemetry.rejected ] (Cert match, schema, seq dedup, ranges, | clock check, policy gate) | | | v | [ Kafka: telemetry.valid (key = vehicle_id) ] | | | | | | v v v v | [ Latest-State ] [ TSDB Writer ] [ S3 Raw ] [ WebSocket ] [ External Export ] [ Updater ] [ (ClickHouse)] [Archiver] [ Fan-out ] [ Gateway ] | | (Fail-closed check) v v | [ Redis Cluster ] [ Internal ] v (+ vehicle-latest) [ Web UI ] [ Third-Party APIs ] ^ | | v [ Internal Telemetry REST API ] <--------- (SSO + RBAC) | v [ PostgreSQL: Vehicles, Policies, Audit + Outbox ] | v [ Policy Service & Outbox Relay ] +--> Publishes compacted `vehicle-policy` topic (consumed by Validator, | Latest-State Updater, and External Export Gateway within seconds) +--> Updates MQTT Broker ACL + publishes retained `config/desired` message to carWalking through the three paths in plain English: 1. Ingest path: cars push MQTT batches to the broker, which forwards them into
telemetry.rawpartitioned byvehicle_id. Partitioning byvehicle_idguarantees every packet from carveh_804lands on the same Kafka partition and is processed by the same validator worker. 2. Independent consumers: once validated,telemetry.validfans out to five separate consumer groups. If ClickHouse slows down during maintenance or an external partner API goes down, Kafka absorbs their backlog while Redis (latestspeed) and live WebSocket dashboards stay completely unaffected. 3. Policy control path: when an operator setsveh_519toOFF, PostgreSQL records the new version and audit log, andvehicle-policyimmediately updates the Validator, Latest-State Updater (Redis), Export Gateway, Broker ACL, and the car's desired config topic.Deep dive 1: collecting and transmitting telemetry from the car
Inside a modern electric vehicle, microcontrollers talk over a CAN bus (Controller Area Network, the internal wiring network connecting brakes, motor, climate control, and battery management). A dedicated TCU (Telematics Control Unit—the onboard Linux/RTOS computer containing the cellular modem and GPS receiver) reads selected signals through an isolated read-only gateway so cloud software can never inject steering or braking commands onto the drive bus.
Batching vs. freshness
Mode Batch interval Peak fleet msg/s Worst-case UI age When used Live mode 1 second ~150k if all cars ~1-2 seconds Watched cars only (auto-expires after 10 min) Normal driving 5 seconds ~30,000 msg/s ~5-6 seconds Default whenever ignition_on = true Parked 5 minutes ~2,833 msg/s up to 5 minutes Heartbeat when ignition_on = falseHandling unreliable cellular networks
- At-least-once delivery (MQTT QoS 1): QoS 1 (Quality of Service level 1) means the car keeps buffered batches in flash and retransmits until the MQTT broker replies with a
PUBACKacknowledgment. Network hiccups never silently drop data; the trade-off is that occasional duplicate packets reach the backend when an acknowledgment gets lost, which ourseqnumber cleans up. - Persistent sessions and Last Will: a persistent session tells the broker to queue incoming commands while a car is offline and deliver them upon reconnect. A Last Will message is a pre-registered notice the broker automatically publishes if a car's connection vanishes without a clean sign-off (detected after
1.5 × 60 s keepalive = 90 seconds). - Offline ring buffer ("live first, rate-capped backfill second"): the TCU reserves ~52 MB of flash memory as a circular buffer—enough for 72 hours of continuous driving (
72 h × 720 KB/h ≈ 52 MB). When a car exits a 1-hour mountain tunnel, if it uploaded oldest-first, the dashboard would show 1-hour-old speeds while draining the backlog! Instead, the car immediately publishes current driving batches ontelemetry, while trickling buffered history onbackfillcapped at 2 KB/s (10x the normal 0.2 KB/s driving rate, draining a 1-hour outage in ~6 minutes). If 30,000 cars exit a regional cellular outage together,30,000 × 2 KB/s = 60 MB/s—manageable for Kafka, whereas uncapped uploads would spike into hundreds of megabytes per second. - Jittered exponential backoff: after a broker restart or cell-tower outage, if 200,000 cars reconnected at the exact same millisecond, they would overwhelm TLS handshakes (thundering herd). Each car waits a random jitter of
0–60 secondsbefore its first retry and doubles the window after failures (up to 10 minutes), while broker nodes enforce a connection-rate cap.
- At-least-once delivery (MQTT QoS 1): QoS 1 (Quality of Service level 1) means the car keeps buffered batches in flash and retransmits until the MQTT broker replies with a
Deep dive 2: backend ingestion, validation, and storage
The Stateful Stream Validator (built with Apache Flink or Kafka Streams, keyed by
vehicle_id) keeps a tiny per-car state record in memory backed by periodic checkpoints. Every batch passes through seven checks in order:Step Check Rule Action if check fails 1 Identity payload.vehicle_id == MQTT topic ID == mTLS cert Drop + fire security alert 2 Policy gate car's current mode in `vehicle-policy` != OFF Drop batch + increment off-drop counter 3 Schema Protobuf parses & schema_version is supported Route raw bytes to `telemetry.rejected` 4 Deduplication `seq` not already seen for this vehicle Drop silently (normal QoS 1 retry) 5 Clock sanity now - 7 days <= sample.ts_ms <= now + 2 minutes Flag `clock_suspect`; archive raw only 6 Sensor bounds speed in [0, 300] km/h, cabin in [-50, 90] °C, Set that field to null + add battery in [0, 100]% `out_of_range` to `quality_flags` 7 Plausibility |delta speed| <= 40 km/h within 1 second Keep value + add `implausible_jump` flagWhy keep a sequence bitmap for deduplication instead of just storing
max_seq? Because live batches (seq = 501, 502) and tunnel backfill batches (seq = 440, 441) arrive interleaved! Storing the highest contiguousseqbefore the gap plus a compact bitset of received sequence numbers above it uses ~150 bytes for a caught-up car (1M × 150 B ≈ 150 MBacross the cluster) and at most51,840 bits ≈ 6.5 KBfor a car draining a full 72-hour buffer.Why flag bad sensor values (
quality_flags) instead of silently throwing away the whole batch? Because ifcabin_temp_creads-99°Con every 2026 crossover running firmwarev4.2.1, speed and battery in that batch are still valid, and vehicle engineers need to see the spike inout_of_rangeflags grouped by firmware version to diagnose the faulty thermistor driver.Writing and serving historical data
- Batched columnar writes: columnar databases like ClickHouse write immutable sorted data parts on disk and struggle if hit with 33,000 tiny single-row inserts per second. The TSDB Writer buffers ~1 second of validated samples (~150,000 rows) per bulk insert. As a safety net behind validator deduplication, ClickHouse's
ReplacingMergeTree(received_ts_ms)ordered by(vehicle_id, sample_ts_ms)merges any duplicate rows that slip through during consumer restarts. - Fast chart queries: querying up to 6 hours reads
telemetry_samplesand downsamples on the fly into at most 2,000 time buckets returning(min, max, avg)per bucket—preserving sharp speed spikes that pure averaging would flatten. Ranges longer than 6 hours querytelemetry_1m_rollupso scanning 30 days touches43,200rows instead of2.5 million.
- Batched columnar writes: columnar databases like ClickHouse write immutable sorted data parts on disk and struggle if hit with 33,000 tiny single-row inserts per second. The TSDB Writer buffers ~1 second of validated samples (~150,000 rows) per bulk insert. As a safety net behind validator deduplication, ClickHouse's
Deep dive 3: retrieving the latest speed of a specific vehicle
An interviewer asking "how do you get the latest speed for vehicle
veh_804?" is testing whether you fall into the out-of-order overwrite trap.Why naive "last write wins" breaks
Suppose car
veh_804drives out of a tunnel at 10:05:00 going96 km/h, and 3 seconds later backfills a buffered tunnel packet from 10:01:00 when it was slowed to18 km/h. If Redis blindly overwrotespeed_kphon every arriving packet,veh_804's "latest speed" would jump backwards to18 km/h! Even comparing a single per-car timestamp is not enough, because one packet might carrycabin_temp_cwhile omittingspeed_kph.Arrival order at backend for car veh_804: 10:05:01 Live batch arrives: sample_ts = 10:05:00, speed_kph = 96.0 -> Redis sets speed_kph = 96.0, speed_kph:ts = 10:05:00 (newer than nothing) 10:05:04 Backfill batch arrives: sample_ts = 10:01:00, speed_kph = 18.0 -> 10:01:00 < 10:05:00 -> IGNORED for Redis latest! (Still written to ClickHouse history)Atomic per-signal compare-and-set in Redis
A compare-and-set update checks the existing timestamp and writes the new value in one indivisible step so two packets never race. Redis executes Lua scripts atomically on the shard holding
veh:{vehicle_id}:-- KEYS[1] = "veh:{vehicle_id}" -- ARGV[1] = state_ts_ms, ARGV[2] = ignition_on ("1"|"0"), ARGV[3] = expected_interval_ms -- ARGV[4..end] = triples of (signal_name, sample_ts_ms, value) local old_state_ts = tonumber(redis.call("HGET", KEYS[1], "state_ts") or "-1") local new_state_ts = tonumber(ARGV[1]) if new_state_ts > old_state_ts then redis.call("HSET", KEYS[1], "state_ts", ARGV[1], "ignition_on", ARGV[2], "expected_interval_ms", ARGV[3]) end for i = 4, #ARGV, 3 do local sig = ARGV[i] local ts_field = sig .. ":ts" local sample_ts = tonumber(ARGV[i + 1]) local old_ts = tonumber(redis.call("HGET", KEYS[1], ts_field) or "-1") if sample_ts > old_ts then redis.call("HSET", KEYS[1], sig, ARGV[i + 2], ts_field, ARGV[i + 1]) end end return 1Notice two crucial safeguards: 1.
expected_interval_ms(5000ms whenignition_onis true,300000ms when parked) is guarded bystate_tsjust like the signals, so a backfilled batch from this morning's commute cannot trick Redis into thinking a currently parked car is still driving. 2. The Latest-State Updater also consumes thevehicle-policytopic (applying a version checknew_policy_version > old_policy_version) so switching a car toOFFupdatespolicy_modein Redis within seconds—even though the validator immediately stops forwarding telemetry batches for that car.Reading latest speed in the API
def get_latest_speed(redis_client, vehicle_id: str, now_ms: int) -> dict: # Fetch all needed fields from the vehicle's hash in a single ~1 ms round-trip raw_fields = redis_client.hmget( f"veh:{vehicle_id}", ["speed_kph", "speed_kph:ts", "connection", "expected_interval_ms", "policy_mode"], ) speed_str, sample_ts_str, connection, expected_interval_str, policy_mode = raw_fields # Check policy_mode first so an OFF car never leaks old cached speed or says 'never_reported' if policy_mode == "OFF": return { "vehicle_id": vehicle_id, "speed_kph": None, "sample_ts_ms": None, "age_ms": None, "freshness": "telemetry_off", } # Vehicle exists in fleet metadata, but has never sent a speed reading yet if speed_str is None or sample_ts_str is None: return { "vehicle_id": vehicle_id, "speed_kph": None, "sample_ts_ms": None, "age_ms": None, "freshness": "never_reported", } sample_ts_ms = int(sample_ts_str) age_ms = max(0, now_ms - sample_ts_ms) # Default to 5,000 ms if ignition state has not been recorded yet expected_interval_ms = int(expected_interval_str or 5000) # Distinguish deliberate offline state from silent network lag if connection == "offline": freshness = "offline" elif age_ms <= 2 * expected_interval_ms: freshness = "live" else: freshness = "stale" return { "vehicle_id": vehicle_id, "speed_kph": float(speed_str), "sample_ts_ms": sample_ts_ms, "age_ms": age_ms, "freshness": freshness, }Why compare
age_msagainst2 * expected_interval_ms? Because a parked car reports0.0 km/hevery 5 minutes (300,000 ms): a 3-minute-old reading from a parked car is healthy andlive, whereas a 3-minute-old reading from a driving car (expected_interval_ms = 5,000) is 36 intervals late and must be markedstaleimmediately—even before the MQTT broker's 90-second keepalive timeout marksconnection = "offline". Total latency is ~1 ms in Redis plus auth check, comfortably inside our 50 ms p99 target.Deep dive 4: disabling telemetry for one vehicle
If the organization requires unit
veh_519to stop transmitting readings to external systems, simply pushing a "stop" command to the car is not enough: the car might be offline in a garage, on buggy old firmware, or sitting with packets already queued inside our backend. We combine the device shadow pattern with four independent enforcement layers.A device shadow separates desired state (version 8:
OFF, chosen by the operator) from reported state (version 7:ON, last confirmed by the car) so offline devices converge reliably whenever they wake up. To ensure PostgreSQL and Kafka never drift apart if a server crashes mid-request, we use the transactional outbox pattern: the API writes both thetelemetry_policyupdate and anoutboxevent row inside one PostgreSQL transaction, and a background relay reliably publishes that outbox row to the compactedvehicle-policyKafka topic.Operator PUT /telemetry-policy (mode = OFF or INTERNAL_ONLY) | v [ PostgreSQL transaction: telemetry_policy (desired_version = 8) + policy_audit_log + outbox ] | +---> Layer 1: External Export Gateway (in-memory policy map from `vehicle-policy`) | Checks policy AT SEND TIME (not ingest time). Blocks non-ON cars within seconds. | Fails closed: if its `vehicle-policy` consumer lags or restarts, exports pause! | +---> Layer 2: Stream Validator & Latest-State Updater (`vehicle-policy`) | If mode == OFF: Validator drops arriving batches; Redis sets policy_mode = "OFF". | If mode == INTERNAL_ONLY: Validator stamps `internal_only = true` on records. | +---> Layer 3: MQTT Broker ACL (for mode == OFF) | Revokes publish permission ONLY on `telemetry` and `backfill` topics. | Keeps `config/desired` and `config/reported` OPEN so the car can receive OFF (and later ON)! | Broker replies with MQTT 5 PUBACK "Not Authorized" WITHOUT closing the TCP socket. | +---> Layer 4: Vehicle TCU (`config/desired` retained QoS 1 message) Writes version 8 = OFF to flash, stops sampling/transmitting, wipes unsent flash buffer, and publishes `config/reported` (version 8) -> UI flips from PENDING to APPLIED.Look closely at Layer 3's subtle trap: why must the broker reject unauthorized
telemetrypublishes with a packet-level error (PUBACKreason code0x87 Not Authorizedin MQTT 5) without severing the TCP connection, and why must we never revoke the car's mTLS certificate to disable telemetry? 1. If we revoked the certificate, the car could never connect again to receive a future command turning telemetry backON. 2. When an offline car wakes up, it often flushes a live batch milliseconds before processing its queuedconfig/desiredmessage. If a denied publish tore down the TCP connection, the car would reconnect, retry the publish, get disconnected again, and spin in an infinite reconnect loop without ever applyingOFF!Edge cases interviewers probe: - Offline for weeks: Layers 1–3 enforce the block within seconds; the UI clearly shows
Backend Enforced — Vehicle Pending (offline since Nov 12). - Replay or out-of-order config:desired_versionis strictly increasing; the TCU ignores any config whose version is<=the version stored in flash. - Re-enabling (OFF -> ON): if the switch toOFFcarried a privacy/customer-consent ticket, the Policy Service requires a recorded re-consent artifact before allowingON, restores the Broker ACL first, and then publishesdesired_version = 9 (ON).Scaling, failure handling, and monitoring
Horizontal scaling
- MQTT broker cluster: 1M idle/low-rate TLS connections spread across ~20–40 broker nodes (sized from load tests, protected by per-node connection-rate limits and client jitter).
- Kafka & stream processors: ~31 MB/s per topic across 64 partitions keyed by
vehicle_id(~0.5 MB/s per partition), allowing up to 64 parallel Validator and Updater instances. At 10x fleet growth (10M cars), we widen partitions and shorten full-resolution ClickHouse retention (e.g., 14 days full-res + 2 years of 1-minute rollups). - WebSocket hubs: ~200 open internal browsers need only 2–3 stateless gateway servers consuming
telemetry.validand filtering in memory for the ~100vehicle_ids subscribed on each socket.
Failure handling
Component failure User / system impact Automated recovery Tunnel / cell dead zone Car appears stalethenofflineCar buffers up to 72 h in flash; sends live first + 2 KB/s backfill on reconnect MQTT broker node crash ~25k–50k cars lose socket Cars reconnect to healthy nodes with 0–60 s random jitter; QoS 1 resends unacked batches Redis shard failure Latest-speed cache miss Replica promotion; cold rebuild from compacted vehicle-latesttopic (ClickHouse fallback meanwhile)ClickHouse overload / maintenance Historical charts lag by minutes Kafka buffers telemetry.validfor days; live speed and WebSockets stay unaffectedPolicy stream lag at Export Gateway Risk of stale policy view Fail closed: gateway pauses partner exports until caught up to latest vehicle-policyoffsetBuggy validation rule Valid samples rejected Raw payloads retained in telemetry.rejected+ S3 Parquet archive; fix rule and replayProduction monitoring
- End-to-end freshness SLO:
now_ms - sample_ts_mswhen written to Redis (p50, p95 < 5 s), broken down by cellular carrier and region. - Policy enforcement health:
vehicle-policylag at Export Gateway (page immediately if > 5 s), count of batches dropped fromOFFcars (surfaces old firmware ignoringOFF), and cars stuck withdesired_version != reported_versionfor > 24 hours while online. - Synthetic canary car: a lightweight daemon authenticating with a test vehicle certificate publishes a known speed curve every 30 seconds; an independent checker queries
GET /latestand pages on-call if freshness exceeds 10 seconds.
Accelerating development safely with an AI coding assistant
An AI coding assistant is a huge multiplier on boilerplate, provided humans own the contracts, invariants, security boundaries, and verification.
1. Humans author the specs and invariants first
Before asking the assistant to generate application code, engineers write and review the Protobuf schema, the OpenAPI specification, and an explicit
INVARIANTS.mdchecked into the repository context: - Ordering invariant: a signal's latest value in Redis never regresses to an oldersample_ts_ms. - Export invariant: no record for a vehicle whose current mode is notONever leaves the Export Gateway. - Topic isolation invariant: vehicle certificateXcan publish/subscribe only tov1/vehicles/X/*. - Control-channel invariant: settingmode = OFFnever blocksconfig/desiredorconfig/reported.2. Delegate well-bounded scaffolding to the assistant
Use the assistant to generate OpenAPI server stubs and typed TypeScript API clients, React table/chart components following an existing component template, Kafka consumer setup, Terraform/Docker Compose test harnesses, database migrations, and a fleet load-test simulator that emulates thousands of cars driving, entering tunnels, and backfilling out of order.
3. Humans write or scrutinize property-based tests for subtle invariants
Never trust an AI assistant to both write tricky state logic and write weak happy-path unit tests that merely mirror its own code. Instead, verify invariants across hundreds of randomized arrival orders using property-based testing (testing rules that must hold for all valid inputs, not just one hand-picked example):
import random def merge_latest_state(current_state: dict, incoming_samples: list) -> dict: """Reference specification for per-signal timestamp compare-and-set. current_state: {signal_name: (sample_ts_ms, value)} incoming_samples: list of (signal_name, sample_ts_ms, value) """ updated = dict(current_state) for signal_name, sample_ts_ms, value in incoming_samples: previous = updated.get(signal_name) # Only overwrite when this sample was recorded strictly later than what we hold if previous is None or sample_ts_ms > previous[0]: updated[signal_name] = (sample_ts_ms, value) return updated def test_arrival_order_never_changes_latest_speed(): """Live batches, tunnel backfills, and QoS 1 duplicates in any order yield the exact same result.""" random.seed(42) # Build 200 sequential samples plus 50 duplicate redeliveries ordered_samples = [("speed_kph", ts * 1000, float(ts % 130)) for ts in range(200)] samples_with_duplicates = ordered_samples + ordered_samples[:50] expected = merge_latest_state({}, samples_with_duplicates) for _ in range(100): shuffled = list(samples_with_duplicates) random.shuffle(shuffled) assert merge_latest_state({}, shuffled) == expectedWe run this exact same shuffled-stream test in CI against the real Redis Lua script inside a Docker container, plus automated negative tests proving car
A's cert is rejected on carB's topic andINTERNAL_ONLY/OFFrecords never reach a mock external sink.4. Guardrails for code review, security, and data privacy
- Review pitfalls to check on every AI-assisted PR: hallucinated or typosquatted package names (slopsquatting—verify every dependency exists and is approved), endpoints missing role-based auth middleware, overly permissive cloud IAM wildcards (
*), and non-atomic read-modify-write Redis calls. - Strict prompt-privacy rules: use only company-approved enterprise AI tools with zero data retention; never paste real VINs, factory certificates, private keys, or real driver GPS/speed traces into prompts—always feed synthetic fixtures from the simulator.
- Embedded boundary: any code running inside the vehicle's TCU follows automotive safety review and hardware-in-the-loop (HIL) bench testing regardless of how the initial draft was written.
- Review pitfalls to check on every AI-assisted PR: hallucinated or typosquatted package names (slopsquatting—verify every dependency exists and is approved), endpoints missing role-based auth middleware, overly permissive cloud IAM wildcards (
Summary of key trade-offs
- 5-second MQTT batches vs. 1-second HTTP requests: cuts message rate 5x (~30k vs. ~150k msg/s) and keeps cellular data around ~28 MB/car/month; temporary 1-second "live mode" restores instant feedback for the few cars engineers are actively watching.
- On-car ring buffer with live-first + 2 KB/s backfill: eliminates tunnel gaps while showing current speed immediately upon reconnect; introduces out-of-order arrivals, which we solve cleanly with per-signal timestamp compare-and-set.
- Redis latest-state hash + ClickHouse wide rows + S3 Parquet: ~1 ms
/latestlookups and 20x lower time-series row overhead, at the cost of maintaining separate read stores fed by independent Kafka consumers (backed by compactedvehicle-latestfor fast Redis recovery). - Four-layer policy enforcement + fail-closed Export Gateway: guarantees disabled vehicles stop leaking to external systems within seconds even when offline or running legacy firmware, trading a small amount of control-plane complexity and a
PENDING_VEHICLE_ACKUI state for provable compliance. - Human-owned contracts + AI-generated scaffolding: captures big speedups on repetitive full-stack boilerplate while keeping ordering, auth, and privacy invariants verified by deterministic CI gates.
Intuition & how it works
Picture a million delivery hikers spread across mountains and tunnels, each carrying a sensor wristwatch and a walkie-talkie. Every second they jot down their speed and temperature on a notepad, and every 5 seconds they radio a single bundle of 5 lines to headquarters. If a hiker enters a dark tunnel with no signal, they keep writing pages into their backpack; the moment they step back into daylight, they radio their right-now speed first so headquarters immediately sees where they are, and then slowly read off the older tunnel pages in the background. Back at headquarters, two separate records are kept: a wall whiteboard holding one slot per hiker for instant lookups (with a strict rule: only erase a number on the whiteboard if the incoming reading carries a newer wristwatch timestamp than what is already written there), and a logbook filing every single historical second in order for later charts.
Why does a naive web-app design fall apart here? First, having servers poll cars over HTTP ("what is your speed?") is impossible because cellular networks put cars behind carrier NAT (Network Address Translation, a carrier firewall that blocks incoming connections initiated from the internet) and cars go offline constantly—while having 1 million cars send individual HTTP requests every second would burn huge cellular data and overwhelm servers with connection handshakes. Second, if the backend stores "latest speed" using naive last-write-wins (blindly overwriting the database with whichever packet arrived most recently), buffered tunnel packets arriving 10 minutes late will overwrite a car's live 90 km/h highway speed with 0 km/h from earlier. Third, implementing "disable telemetry" only by sending a "stop" message to the car fails whenever the car is parked offline in an underground garage—its already-queued data or first reconnect burst could still leak to external partners unless the backend blocks it independently.
Walk through a concrete 4-event trace for vehicle veh_804 (and veh_519) to see how all pieces fit together:
1. 10:00:05 — Normal drive (online):
veh_804 sends batch seq=10 with 5 samples (latest: ts=10:00:05, speed=84 km/h).
-> Validator checks cert & seq=10 -> Redis whiteboard sets speed=84 km/h (ts=10:00:05)
-> ClickHouse appends 5 rows -> GET /latest returns 84 km/h, freshness="live".
2. 10:00:10 — Enters tunnel (offline):
veh_804 records seq=11 (ts=10:00:10, speed=18 km/h) into its 72-hour flash buffer.
At 10:00:20, an engineer calls GET /latest: age_ms is 15,000 ms (> 2 × 5,000 ms interval),
so API returns 84 km/h with freshness="stale" (no false "still 84 km/h live!" illusion).
3. 10:00:25 — Exits tunnel (live first, backfill second):
veh_804 immediately sends live seq=14 (ts=10:00:25, speed=96 km/h) -> Redis updates to 96 km/h.
Two seconds later, veh_804 backfills seq=11 (ts=10:00:10, speed=18 km/h):
-> ClickHouse inserts 10:00:10 into history so the speed chart has zero tunnel gaps!
-> Redis Lua script checks 10:00:10 < 10:00:25 and IGNORES 18 km/h, keeping 96 km/h!
4. 10:02:00 — Operator disables outbound telemetry on veh_519 (PUT /telemetry-policy mode="OFF"):
-> PostgreSQL saves desired_version=8 + audit row; Kafka `vehicle-policy` updates within 1-2 s:
* External Export Gateway blocks veh_519 at send time (even for already-queued records).
* Validator drops any new batches; Redis marks policy_mode="OFF" (GET /latest -> "telemetry_off").
* Broker ACL blocks `telemetry` publishes while keeping `config/*` open.
-> veh_519 receives retained config v8, stops sending, wipes its flash buffer, reports v8 -> "APPLIED".
Key trade-offs
- 5-second MQTT batches vs. 1-second HTTP requests. MQTT (a lightweight publish/subscribe protocol over a single long-lived connection) with 5-second batches holds peak fleet traffic to ~33,000 msg/s and ~28 MB/car/month, whereas 1-second unbatched sends would cost 5x the packets and radio wakeups for screens nobody is watching. The trade-off is up to ~5 seconds of normal display lag, which temporary on-demand live mode (1-second batches for 10 minutes) eliminates when an engineer actively inspects one car.
- Live-first + rate-capped backfill vs. strict FIFO upload. Uploading current samples immediately while trickling flash backlog at 2 KB/s restores live dashboards within a second of exiting a tunnel and prevents 30,000 reconnecting cars from flooding the backend. The price is out-of-order arrival, requiring per-signal timestamp compare-and-set (an atomic check-before-overwrite operation) in Redis and deduplication in the stream validator.
- Dedicated Redis latest-state store vs. querying the time-series database. Asking a columnar database (a store like ClickHouse that groups each column's values on disk for fast analytical scans) for "the newest row of
veh_804" works, but suffers from 1-second batching lag and higher tail latency under heavy writes. Keeping ~1 GB of per-vehicle hashes in Redis answers in ~1 ms, at the cost of maintaining a second read store backed by a compacted Kafka topic (a log that keeps the newest message per key so Redis can be rebuilt after a crash). - Wide time-series rows vs. narrow
(vehicle_id, signal_name, value)rows. Writing all 20 signals of one timestamp into one wide row reduces row count 20x (150k vs. 3M rows/s) and keeps multi-signal charts cheap. Adding a brand-new sensor requires anALTER TABLE ADD COLUMNmigration (trivial for nullable columns in ClickHouse) rather than inserting a new string key. - Flagging suspect sensor readings vs. dropping them. Recording
quality_flags(out_of_range,implausible_jump) preserves valid sibling signals in the same packet and lets hardware/firmware teams spot broken sensors by model, at the cost of teaching chart and export consumers to filter or gray out flagged values. - Four-layer policy enforcement + fail-closed exports vs. car-only toggle. Enforcing
OFF/INTERNAL_ONLYacross the Export Gateway, Validator, Broker ACL (Access Control List, the per-topic permission rules), and the car itself guarantees immediate compliance even when a car is offline or running old firmware. Failing closed (pausing external exports if the gateway's policy stream lags) occasionally delays partner feeds during internal hiccups, but guarantees a disabled car's data never leaks. - Human-written contracts + AI-generated boilerplate. Letting an AI coding assistant draft OpenAPI clients, UI tables, and load simulators speeds up implementation dramatically, while keeping schemas, security rules, and property-based tests (automated randomized tests of system invariants) human-owned ensures subtle race conditions do not slip into production.
Common mistakes
- Using naive last-write-wins for latest speed, allowing a 2-hour-old tunnel backfill packet to overwrite a car's current highway speed.
- Comparing one timestamp per car instead of one timestamp per signal, which either drops or corrupts readings when partial batches report some signals without others.
- Returning a speed number with no age or freshness verdict, making a car that lost signal inside a tunnel at 110 km/h look as if it is still cruising at 110 km/h hours later, or treating a parked car's normal 5-minute heartbeat as "stale" after 10 seconds.
- Polling vehicles from the cloud, which fails behind cellular carrier NAT and collapses at 1 million vehicles.
- Reconnecting without random jitter, turning a brief broker or cell-tower blip into a synchronized thundering herd (hundreds of thousands of simultaneous TLS handshakes) that knocks the broker cluster down repeatedly.
- Uncapped offline backfill, where thousands of cars exiting an outage dump gigabytes of flash history at full LTE speed and starve live telemetry.
- Enforcing "disable telemetry" only on the car—or revoking its client certificate. Car-only commands fail while the car is offline; revoking its mTLS certificate (or closing the MQTT socket whenever a
telemetrypublish is denied) severs theconfig/desiredchannel so the car can never applyOFFcleanly or be turned backONlater. - Checking export policy at ingestion time instead of egress send time, allowing packets that were already sitting in an outbound partner retry queue before the policy flip to leak out afterward.
- Trusting vehicle identity from the payload body alone without verifying it matches the mTLS client certificate, allowing one compromised TCU to spoof telemetry for the entire fleet.
- Assuming AI-generated code is safe because AI-generated unit tests pass, when both share the exact same blind spot (such as testing only sequential timestamps and never shuffled backfill).
Follow-up questions
- How would you layer real-time anomaly alerts—such as a parked vehicle's battery pack overheating—onto this pipeline? Add an independent alerting consumer group reading
telemetry.valid(also partitioned byvehicle_id), so each worker can track per-car sliding windows like "battery above 55°C for 60 consecutive seconds" purely in local memory. Store alert definitions as data (signal, threshold, duration, target fleet/firmware, cooldown window) and backtest any new rule against 24 hours of S3 Parquet history before enabling it so noisy rules do not page on-call thousands of times. Because parked cars normally send heartbeats only every 5 minutes, configure the car's onboard TCU threshold monitor to wake the modem immediately—or have the backend issue alive_modecommand as soon as a pre-alarm temperature (say 45°C) is observed. - How can you introduce new sensor fields cleanly when over-the-air firmware rollouts take months across the fleet? Add the new signal as an
optionalProtobuf field with a brand-new field number—never reusing retired field numbers—so older vehicles omit it harmlessly and older readers ignore unknown tags. Before the first updated car ships, add a nullable column in ClickHouse and a validation range rule in the Stream Validator; in the React UI, render the new tile only when that signal is present in the vehicle's snapshot or capabilities metadata. Trackschema_versiondistribution on an ingestion dashboard so you know exactly which cars have upgraded. - Walk through how your system behaves when a regional cellular outage clears and 200,000 vehicles reconnect within a single minute. Each car applies a random 0–60 second reconnect jitter (with exponential backoff if a broker node's connection-rate limiter pushes back), spreading TLS handshakes smoothly across the MQTT cluster. Once connected, every car publishes its current sample on
telemetryfirst, so internal dashboards recover within seconds, while draining its flash buffer onbackfillat the configured 2 KB/s cap (for example, 30,000 cars that were driving during a 1-hour outage add30,000 × 2 KB/s = 60 MB/sfor ~6 minutes, roughly 2x normal peak, which Kafka partitions absorb easily—and if consumer lag rises, the backend dynamically lowers the backfill rate cap via config). Redis's Lua compare-and-set script automatically ignores the older backfilled timestamps for/latest, while ClickHouse merges them in(vehicle_id, sample_ts_ms)order to leave a gap-free historical chart.
Follow-up questions
- How would you layer real-time anomaly alerts—such as a parked vehicle's battery pack overheating—onto this pipeline?
- How can you introduce new sensor fields cleanly when over-the-air firmware rollouts take months across the fleet?
- Walk through how your system behaves when a regional cellular outage clears and 200,000 vehicles reconnect within a single minute.
Similar questions
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency
- Multi-Source Enterprise Question Answering System