Connected Fleet Telemetry: Availability, Scale, and Operational Simplicity

Medium · System Design · Software Engineer · HR Screen

Prompt

A fleet of 5,000,000 active connected vehicles streams continuous sensor readings and diagnostic signals—such as pack temperature, motor speed, tire pressure, and fault codes—over persistent connections (for example, MQTT, gRPC, or WebSockets) to cloud backend services. Each vehicle transmits roughly 1 KB every 10 seconds, producing 500,000 requests per second (~500 MB/s) on average and peaking at 1,000,000 RPS (~1 GB/s).

Design the cloud ingestion, alerting, and analytics backend for this fleet, explicitly justifying how your architecture balances availability, horizontal scalability, and operational maintainability during traffic spikes and partial infrastructure outages:

  • Routine telemetry: Acknowledge vehicle uploads in under 100 ms with 99.9% availability, and expose fleet data for both real-time operational dashboards and historical batch analytics.
  • Urgent safety alerts: Isolate severe vehicle hazards (such as battery thermal spikes or brake pressure loss) and dispatch notifications in under 1 second with 99.99% availability.

Scope & Expectations

  • Edge ingestion, isolation, and sizing: Specify the vehicle-to-cloud wire protocol, authentication, capacity math, and how safety-critical alerts are separated from high-volume periodic heartbeats so routine congestion never delays emergency dispatches.
  • Availability vs. consistency under partitions: Contrast the consistency, durability, and failover guarantees given to life-safety alerts versus routine metrics when cellular links, availability zones, or cloud regions experience partitions.
  • Scalability without operational sprawl: Show how to sustain 1,000,000 RPS and serve live state, fleet time-series charts, fault searches, and historical queries using proven, maintainable distributed components rather than bespoke storage engines or fragmented microservices.
  • Backpressure and degraded sinks: Explain how client-side buffering, broker retention, and tiered load shedding protect ingestion stability when downstream indexing or analytics stores slow down or reconnect storms hit.

Step-by-step walkthrough

  1. Clarify requirements and what "balance" means here

    At 5,000,000 connected vehicles and 1,000,000 messages per second (~1 GB/s peak ingress), the core design challenge is deciding where to spend engineering complexity. Two very different workloads share the vehicle-to-cloud connection:

    • Critical safety alerts (rapid battery thermal runaway, hydraulic brake pressure loss): tiny volume (< 0.01% of bytes), strict 99.99% availability, and under 1 second end-to-end dispatch.
    • Routine telemetry (10-second heartbeats of RPM, tire pressure, pack voltage): 99.99% of the bytes (~1 GB/s), 99.9% availability, and tolerant of delay, buffering, or temporary sampling.

    Running both through one uniform pipeline creates a bad trade-off: either you pay to make the entire 1 GB/s firehose "four nines" across regions, or a slow analytics index stalls brake-failure alerts. Separating the two paths right at the edge gateway lets us build both out of boring, battle-tested building blocks.

    Functional requirements

    • Continuous telemetry ingestion: accept ~1 KB updates every 10 s per vehicle over persistent connections and acknowledge receipt within 100 ms.
    • Critical alert isolation & dispatch: isolate safety alerts at receipt and dispatch them to the owner's mobile app, fleet operations console, and roadside systems within 1 s.
    • Dashboards & batch analytics: power live single-vehicle lookups, fleet-wide time-series charts, diagnostic fault searches, and historical SQL/ML analytics.

    Non-functional requirements & assumptions

    • Scale: 5,000,000 active vehicles; 500,000 RPS average (~500 MB/s), 1,000,000 RPS peak (~1 GB/s).
    • SLOs: 99.99% availability (~4.38 min/month downtime budget) and < 1 s latency for alerts; 99.9% availability (~43.8 min/month) and < 100 ms ack for routine telemetry.
    • On-board vehicle buffer: each vehicle has non-volatile flash storage holding at least 24 hours of unacknowledged telemetry (8,640 msgs x 1 KB = ~8.6 MB raw — trivial on automotive hardware).
    • Edge vs. cloud alert detection: vehicle firmware evaluates immediate safety thresholds on board (zero network lag) and tags critical alerts directly; a secondary cloud stream job checks multi-minute trends and older firmware rules on a best-effort (~seconds) basis.
    • Multi-region topology: each geography (e.g., North America, Europe) runs at least two paired cloud regions (3 availability zones per region). Every vehicle has a primary home region plus a pre-configured partner fallback endpoint for critical alerts.
  2. Back-of-the-envelope numbers

    Size every tier from first principles so cluster counts, partition counts, and storage choices are grounded in concrete math.

    Fleet ingress
      Active vehicles                 5,000,000 (~1 KB payload every 10 s)
      Average rate                    5,000,000 / 10 s = 500,000 msg/s = ~500 MB/s raw
      Peak rate (2x)                  1,000,000 msg/s = ~1 GB/s raw
      Daily volume                    500,000 x 86,400 s = 43.2B msgs/day = ~43.2 TB/day raw
      Compressed (zstd on batched     ~4x compression -> ~10.8 TB/day (~11 TB/day)
        Protobuf payloads)
    
    Traffic split by criticality
      Critical safety alerts          ~50 alerts/s normal; up to 10,000 alerts/s (~10 MB/s) in a storm
      Diagnostic fault-code events    ~1% of messages = 5,000/s avg, 10,000/s peak (~432 GB/day raw)
      Routine periodic metrics        99% of messages
    
    Go edge gateways (fleet-wide across regions, 3 AZs per region)
      Per gateway planning target     50,000 TLS sockets and 10,000 msg/s
      Minimum at peak                 5M / 50k = 100 gateways; 1M / 10k = 100 gateways
      Provisioned                     180 gateways (60 per AZ slice): losing 1 AZ leaves 120 gateways
                                      (~41.7k sockets and ~8.3k msg/s each -> 20% headroom above peak)
    
    Kafka clusters
      Telemetry cluster (2 full-volume topics: telemetry.raw + telemetry.canonical)
        Peak compressed ingress       ~250 MB/s per topic -> ~500 MB/s total across both topics
        With replication factor 3     ~1.5 GB/s total broker disk writes across the fleet
        Broker count (@ ~50 MB/s/node)30 minimum -> run 36 brokers (12 per AZ)
        3-day retention footprint     2 topics x 11 TB/day x 3 days x 3 replicas = ~198 TB (~5.5 TB/broker)
        Partitions per topic          256 keyed by VIN -> ~250 MB/s / 256 = ~1 MB/s compressed
                                      (~3,900 msg/s) per partition at peak
      Dedicated Alerts cluster        3 brokers per region (1 per AZ), 32 partitions; < 10 MB/s even in storms
    
    Downstream processing & query stores
      Flink normalizer                1,000,000 msg/s / ~10,000 msg/s per task slot -> run 128 slots
      Redis (latest state per VIN)    5M keys x ~1 KB = ~5 GB (~10 GB with overhead); coalesced to
                                      1 write per 30 s per VIN = ~170,000 writes/s
      TimescaleDB (1-min rollups)     Grouped by (model, region, firmware, metric) = ~5,000 rows/s
      Elasticsearch (1% fault events) ~432 GB/day raw -> ~1 TB/day on disk (with index + 1 replica), 7d hot
      S3 Parquet data lake            ~11 TB/day compressed (~4 PB/year before cold-tier lifecycle rules)
    

    Three design lessons stand out immediately:

    1. Alerts are 0.01% of bytes: isolating them onto a tiny 3-broker regional cluster and over-provisioning it 10x costs almost nothing while guaranteeing 1-second latency.
    2. Never index raw heartbeats in Elasticsearch: indexing 1,000,000 docs/s of routine tire-pressure pings would require hundreds of search nodes for queries nobody runs. Filtering to the 1% diagnostic fault events cuts search cluster size by 100x.
    3. 5M vehicles x 8.6 MB = 43 TB of free edge buffer: because vehicles retain unacknowledged payloads in flash, the cloud can safely apply backpressure during outages without losing historical data.
  3. Vehicle protocol and APIs

    Vehicles connect using MQTT 5 (a lightweight publish/subscribe protocol over TCP built for intermittent IoT links) secured with mTLS (mutual TLS, where each vehicle presents a hardware-backed X.509 client certificate embedding its unique VIN so no vehicle can spoof another).

    Vehicle -> Cloud (MQTT QoS 1: vehicle retains message until Gateway returns PUBACK)
      v/{vin}/alert       Critical safety alerts; always jump to the front of the send queue
      v/{vin}/telemetry   Live 10-second periodic telemetry (~1 KB Protobuf envelope)
      v/{vin}/backfill    Buffered historical telemetry replayed after offline stretches
    
    Cloud -> Vehicle (server-pushed dynamic control)
      v/{vin}/config      {"telemetry_interval_s": 10, "signals": "full" | "essential",
                           "backfill_kb_per_s": 0.2,
                           "alert_endpoints": ["alerts.us-west...", "alerts.us-east..."]}
    
    MQTT 5 PUBACK reason codes returned by Go Gateway
      0x00 Success                  Safely replicated to Kafka; vehicle deletes from flash buffer
      0x97 Quota exceeded           Server shedding load; vehicle keeps in flash and backs off
      0x99 Payload format invalid   Corrupt message; vehicle logs locally and drops (prevents retry loop)
    

    Why MQTT 5 over a single persistent socket wins here:

    • 1 socket per vehicle, 3 topic prefixes: opening separate TCP connections for alerts vs. telemetry would double fleet sockets from 5M to 10M. Topic prefixes let the edge gateway route alerts and telemetry to separate internal queues immediately without parsing the inner payload.
    • Built-in flow control (Receive Maximum): MQTT 5 caps how many unacknowledged QoS 1 (at-least-once delivery) messages a vehicle can keep in flight, preventing runaway memory usage on gateways without inventing a custom framing protocol.
    • Live config topic: lets operators dial down fleet reporting frequency or backfill speed during emergencies without pushing a firmware update.

    Operational & analytics query APIs

    GET /v1/vehicles/{vin}/state                                   Latest snapshot from Redis (< 30 s)
    GET /v1/fleet/metrics?metric=batt_temp&group_by=model&step=1m  Pre-aggregated rollups (TimescaleDB)
    GET /v1/diagnostics?code=BMS_OVERTEMP&firmware=2026.44         Fault-code search (Elasticsearch)
    GET /v1/alerts?status=open&region=us-west                      Active safety incidents (Global KV)
    WS  /v1/alerts/stream                                          Live incident push to ops console
    SQL (Spark / Trino over S3 Parquet)                            Ad-hoc fleet history & ML training
    
  4. Data model and specialized stores

    Payloads use Protobuf (Protocol Buffers, a compact binary format where fields are identified by stable integer tags rather than verbose JSON keys). Crucially, the outer envelope is fixed while the inner payload bytes vary by vehicle model and firmware:

    TelemetryEnvelope (read by Edge Gateway)          AlertEnvelope (read by Alert Processor)
      vin            string   (verified vs mTLS cert)   alert_id       string   "{vin}:{seq}"
      seq            uint64   (monotonic per vehicle)   vin            string
      event_time_ms  int64    (GPS-disciplined clock)   severity       CRITICAL | HIGH
      schema_id      int32    (Schema Registry ID)      code           e.g. BRAKE_PRESSURE_LOSS
      firmware       string                             event_time_ms  int64
      payload        bytes    (opaque to Gateway!)      snapshot       key sensor readings + GPS
    

    Because the Go gateway inspects only TelemetryEnvelope and never decodes payload, rolling out new vehicle firmware with 50 new battery sensors never requires redeploying the ingestion gateways.

    Right-sized storage per query pattern

    Question asked Store Data written Retention
    "What is VIN X doing right now?" Redis cluster Coalesced hash of latest canonical signals per VIN Overwritten in place
    "How is pack temp trending across 2026 Crossover-E?" TimescaleDB (hypertable: SQL table auto-partitioned by time chunks) 1-min (bucket, model, region, firmware, metric) rollups (~5k rows/s) 90d minute, 2y hourly
    "Which cars threw BMS_f032 on firmware 2026.44?" Elasticsearch Only the 1% diagnostic fault events (diagnostics-YYYY.MM.DD) 7d hot, 30d warm
    "Track open critical alerts across regions" DynamoDB Global Table (multi-region KV) alert_id PK, status, timestamps, assigned responder 1 year
    "Replay every sensor reading of VIN X last month" S3 Parquet (Parquet: compressed columnar files for fast analytical scans) Every canonical record, compacted nightly sorted by (vin, event_time_ms) Multi-year tiered
  5. High-level architecture

    Kafka (a distributed, partitioned append-only log on disk) sits between stateless Go gateways and all stateful stream processors and databases, decoupling ingestion speed from indexing speed.

      5,000,000 Vehicles (MQTT 5 + mTLS, 24h flash buffer, alerts prioritized ahead of backfill)
           |  v/{vin}/telemetry & backfill                  |  v/{vin}/alert (1s retry -> partner region)
           v                                                v
      [ Regional L4 TCP Load Balancers ] ------------> [ Stateless Go Edge Gateways (180 pods, 3 AZs) ]
                                                        /                                    \
                             Bounded Telemetry Queue   / (sheddable)         Dedicated Alert  \ (never shed,
                             + Batched Kafka Producer v                      Queue + Producer  v linger.ms=0)
                        [ Telemetry Kafka (36 brokers) ]                [ Alerts Kafka (3 brokers/region) ]
                          telemetry.raw (256 parts, key=VIN)              alerts.raw (32 parts, key=VIN)
                                      |                                                |
                                      v                                                v
                   [ Flink Normalizer & Deduplicator ]                [ Stateless Alert Processor ]
                     Schema Registry decode, (vin,seq) dedup            Redis NX dedup (fail-open),
                     -> telemetry.canonical, diagnostics,               enrich, dispatch Push / Ops /
                        telemetry.dlq                                   Roadside + Multi-Region Alerts DB
                                      |                                                ^
             +------------------------+-----------------------+------------------------+
             |                        |                       |          (best-effort trend alerts)
             v                        v                       v
      [ Flink: Latest ]      [ Flink: 1m Rollups ]    [ ES Bulk Indexer ]     [ Kafka Connect S3 Sink ]
      (30s coalesce)           (event-time windows)   (reads diagnostics)      (reads canonical)
             |                        |                       |                        |
             v                        v                       v                        v
         [ Redis ]             [ TimescaleDB ]        [ Elasticsearch ]       [ S3 Parquet Lake ]
    
  6. Deep dive 1: isolating the critical alert path (1 s latency, 99.99% availability)

    We enforce physical and logical isolation from vehicle send queue to final dispatch.

    1. Priority & head-of-line prevention on the vehicle: if a vehicle just exited a tunnel and is uploading buffered backfill over TCP, queueing a 512 KB backfill batch ahead of a brake alert would cause TCP head-of-line blocking. Vehicles cap backfill chunks at <= 16 KB, insert v/{vin}/alert frames at the absolute head of their local queue, and if no PUBACK arrives within 400 ms, the vehicle immediately opens or uses a warm standby socket to its partner cloud region with the exact same deterministic alert_id = "{vin}:{seq}".

    2. Zero shared bottlenecks inside the Gateway and Kafka: inside each Go gateway, alert frames bypass the telemetry buffer and enter a dedicated memory channel wired to its own Kafka producer (acks=all, linger.ms=0 so records flush immediately without waiting to fill a batch) pointed at the isolated 3-broker Alerts Kafka cluster. Even if the 36-broker Telemetry cluster is completely saturated, alerts see zero queueing delay.

    3. Plain consumer service instead of heavy stream frameworks: the Alert Processor is a simple stateless Go consumer group (fetch.min.bytes=1), avoiding Flink checkpoint barriers or job-manager restarts on the 1-second critical path:

    Vehicle -> Gateway -> alerts.raw (acks=all, 2-of-3 AZs)         ~10 - 25 ms
    Alert Processor poll + Redis NX dedup (SET alert:{id} 1 EX 3600) ~2 - 10 ms
    In-memory cached VIN metadata + versioned rule lookup            ~1 ms
    Parallel dispatch (Owner Push, Ops WebSocket, Alerts Global DB)  ~50 - 200 ms
    -----------------------------------------------------------------------------
    Typical p99 end-to-end cloud latency: ~250 ms  (well inside 1,000 ms budget)
    
    • Fail-open deduplication: if Redis times out during an outage, the Alert Processor dispatches anyway. Sending a rare duplicate brake warning is infinitely safer than dropping a real emergency; the ops console merges duplicates by alert_id.
    • Alert-storm protection: if a heat wave triggers 10,000 battery alerts/s, vehicle owners still get individual alerts, while on-call operator pages group by (code, firmware, region) so engineers receive 1 actionable incident instead of 10,000 pages.
    • Continuous synthetic probing: simulated virtual vehicles in every region emit an end-to-end canary alert every 10 seconds, paging immediately if round-trip dispatch exceeds 1 second.
  7. Deep dive 2: availability vs. consistency under network partitions

    During network partitions (rural cellular dead zones, broken intra-region broker links, or full regional blackouts), the vehicle's non-volatile flash buffer acts as the durable source of truth until Kafka confirms receipt. That lets us make opposite, deliberate CAP choices for the two streams:

    Failure / Property Critical Safety Alerts (AP-leaning) Routine Telemetry (CP-in-cloud + Edge Buffer)
    Partition behavior Maximize availability: partner region accepts immediately if home region stalls > 400 ms. Preserve consistency in Kafka, delay at edge: home Kafka rejects under-replicated writes; vehicle buffers locally.
    Kafka durability RF=3, min.insync.replicas=2, acks=all, unclean.leader.election=false (an ISR, in-sync replica, is a broker fully caught up with the leader). Same strict Kafka durability: gateways return PUBACK Success only after 2 AZs persist to disk (< 30 ms of the 100 ms budget).
    Duplicates Deduplicated per region via Redis; rare cross-region duplicates merged in UI by alert_id. Deduplicated per VIN in Flink sliding-window state + exact (vin, seq) dedup in nightly S3 compaction.
    Ordering & clocks Independent self-contained snapshots; order not required. Ordered per VIN by seq and vehicle event_time_ms (never arrival time!).

    Handling out-of-order backfill and sliding-window deduplication

    When a car leaves an underground garage after 24 hours, live heartbeats (seq = 8640) arrive first on v/{vin}/telemetry, while buffered history (seq = 1..8639) trickles in over 30 minutes on v/{vin}/backfill.

    1. Event-time windows: Flink aggregates 1-minute fleet metrics by event_time_ms (not arrival time!), holding windows open for a 5-minute watermark lag (a watermark is a timestamp threshold telling Flink that almost all live data up to T has arrived). Backfill older than 5 minutes skips live TimescaleDB windows (marked "last 24h provisional" in UI) and is folded into exact historical rollups by nightly Spark compaction over S3.
    2. Bounded O(1) per-vehicle deduplication: keying telemetry.raw by VIN sends every message from one car to the same Flink task, which keeps a 16,384-slot circular window (~45.5 hours at 1 msg/10 s, > 24 h buffer, costing just ~2 KB per car = ~10 GB across 128 Flink slots):
    WINDOW = 16384  # Covers ~45.5 hours at 10 s intervals (~2 KB bitset per vehicle in production)
    
    
    class VehicleSeqDeduplicator:
        """Per-VIN sliding window that separates in-window duplicates from very old backfill."""
    
        def __init__(self):
            self.max_seq = -1
            self.seen = [False] * WINDOW
    
        def classify(self, seq: int) -> str:
            if seq <= self.max_seq - WINDOW:
                # Older than our 45.5 h RAM window: do NOT drop! Flag as late for S3 lake compaction.
                return "LATE_UNCHECKED"
    
            if seq > self.max_seq:
                # Slide window up to seq, clearing at most WINDOW slots even if seq jumped hugely
                clear_start = max(self.max_seq + 1, seq - WINDOW + 1)
                for s in range(clear_start, seq + 1):
                    self.seen[s % WINDOW] = False
                self.max_seq = seq
    
            slot = seq % WINDOW
            if self.seen[slot]:
                return "DUPLICATE"
    
            self.seen[slot] = True
            return "NEW"
    

    Notice why returning "LATE_UNCHECKED" instead of "DUPLICATE" for seq <= max_seq - WINDOW is critical: after a multi-day camping trip offline, the car's first live message jumps max_seq ahead by tens of thousands; classifying older buffered records as "LATE_UNCHECKED" ensures Flink still writes them to telemetry.canonical (with late = true) so the S3 lake loses zero history!

  8. Deep dive 3: backpressure, downstream slowdowns, and load shedding

    Two complementary mechanisms protect ingestion stability: Kafka absorbs downstream indexing hiccups, and coordinated edge load shedding handles cloud or regional blackouts.

    Case A: Downstream storage slows down (e.g., Elasticsearch degrades by 80%)

    • Why Kafka never runs out of RAM or disk: Kafka consumers pull from disk segments at their own pace — brokers hold zero per-consumer memory queues. Disk usage is strictly bounded by retention.ms = 72h and retention.bytes per partition regardless of consumer lag, and broker consumer byte-rate quotas prevent a catching-up reader's disk reads from starving live producer writes.
    • Tiered sink degradation:
      • Lag < 15 min: autoscale sink workers up to partition count (64 for diagnostics).
      • Lag 15 min – 6 h: Elasticsearch indexer drops INFO diagnostics and indexes only WARNING/CRITICAL, honoring HTTP 429 bulk backoffs; Redis state writer jumps straight to latest offsets (since only current state matters!).
      • Lag > 36 h (50% of 72 h retention): reset consumer offset to latest so live search recovers immediately, then run a throttled Spark job from the S3 Parquet lake to backfill the missed window.

    Case B: Cloud telemetry pipeline or regional connectivity overload

    Each Go gateway caps its telemetry memory queue at 64 MB and applies backpressure (telling senders to slow down) and load shedding (deferring lower-priority work) in four predictable stages — never touching the critical alert path:

    Level 0 (Normal)               Accept live telemetry + backfill (< 0.2 KB/s per vehicle)
    Level 1 (Queue > 50% / p99>50ms) Push config {backfill_kb_per_s: 0} -> pause all backfill uploads
    Level 2 (Queue > 75%)          Return PUBACK "Quota exceeded" to a % of telemetry; cars keep in flash
    Level 3 (Overload > 5 min)     Push config {telemetry_interval_s: 60, signals: "essential"} (6x cut!)
    Level 4 (Gateway CPU > 85%)    Throttle new TLS handshakes (~20k connects/s/region) with retry hints
    

    Surviving a regional reconnect & backfill storm: suppose a cellular carrier outage disconnects 1,000,000 vehicles for 1 hour (360 msgs = 360 KB buffered per car = 360 GB total). When service returns:

    1. Vehicles reconnect using exponential backoff with full jitter (1 s .. 5 min random spread) + TLS session resumption, capped at 20,000 handshakes/s (~50 s to reconnect 1M cars cleanly).
    2. If all 1M cars dumped 360 KB in 6 minutes, they would add 1 GB/s of extra traffic and double peak load. Capping backfill_kb_per_s = 0.2 (2x normal rate) adds only 1M x 0.2 KB/s = 200 MB/s region-wide, draining the entire 1-hour blackout cleanly in 30 minutes while live alerts and live telemetry flow unblocked.
  9. Deep dive 4: balancing scalability and maintainability

    At 1,000,000 RPS, the biggest operational risk is cognitive overload at 3:00 AM from custom storage engines or dozens of tiny microservices. We keep maintainability high by enforcing four architectural guardrails:

    Tempting complex pattern Simpler standard choice Why maintainability wins
    Custom stateful MQTT broker cluster replicating session state Stateless Go gateways + vehicle flash buffer Crashing a gateway loses zero data; scaling or deploying gateways is a plain rolling pod restart.
    Local disk spools on gateways when Kafka slows down Return MQTT Quota exceeded and keep bytes on the vehicle Avoids managing, monitoring, and draining 180 stateful gateway disks.
    25 microservices (one per vehicle subsystem: BMS, HVAC, tires, brakes) One Flink normalizer + declarative YAML/JSON alert rules Adding TIRE_RAPID_DEFLATION is a 5-line reviewed config push, not a new microservice deployment pipeline.
    Every consumer parsing 40 firmware payload versions Protobuf + Schema Registry + 1 canonical topic (telemetry.canonical) Firmware complexity stops at the normalizer; broken payloads route to telemetry.dlq (dead-letter queue, a side topic isolating unreadable records for inspection and replay).

    Scaling linearly to 10M+ vehicles: fix Kafka partition counts with 2–3x headroom up front (e.g., 256 -> 512 partitions) because changing partition count later remaps hash(VIN) across stateful Flink tasks; enforce per-VIN token-bucket rate limits at the gateway so a buggy firmware loop on 100 test cars cannot create a hot partition; and pair regions inside each geography (e.g., US-West <-> US-East) to respect regional data-residency laws while keeping ~30% spare gateway capacity for failovers.

  10. Failure handling, monitoring, and trade-off summary

    Failure modes and automated recovery

    Failure Immediate impact Recovery mechanism
    Single Go gateway crashes ~28,000 vehicles disconnect (5M / 180) Vehicles reconnect with jittered backoff to surviving gateways; unacknowledged frames stay in vehicle flash.
    Full availability zone lost 1/3 of gateways & brokers offline Remaining 120 gateways stay 20% above peak; Kafka retains 2-of-3 replicas (min.insync.replicas=2) with zero data loss.
    Home region unreachable Telemetry pauses; alerts time out at 400 ms Alerts immediately fail over to partner region; routine telemetry buffers in flash (failing over at reduced rate past 2 hours).
    Flink job crashes Downstream sinks lag briefly Restarts from latest checkpoint; idempotent upserts (by VIN, 1-min bucket, or doc ID) make replays harmless.
    Poison firmware payload Normalizer cannot decode inner bytes Routed to telemetry.dlq tagged with schema_id and paged on inflow spike; stream never stalls.

    Key production SLIs to monitor

    • Critical alert SLO (99.99%, < 1 s): end-to-end synthetic canary latency per region, alerts.raw consumer lag (page > 2 s), Redis dedup fail-open count, and push/console delivery error rate.
    • Ingestion & Kafka health: gateway PUBACK p99 (page > 100 ms), Quota exceeded shed level, under-replicated partitions, broker disk usage (warn > 70%), and consumer lag measured in hours against the 72 h retention window.

    Summary of key trade-offs

    • Split alerts from routine telemetry at the edge: runs a small second Kafka cluster so 0.01% life-critical traffic gets 99.99% multi-region availability without paying 4-nines cost on 1 GB/s of routine metrics.
    • CP Kafka durability + vehicle flash buffer: refuses under-replicated telemetry writes rather than losing data, relying on 8.6 MB of free on-vehicle flash to turn cloud hiccups into harmless delays.
    • Standard managed building blocks + 1 canonical schema: trades minor compute overhead and multi-second S3 historical queries for linear horizontal scaling and low 3:00 AM operational complexity.

Intuition & how it works

Think of a 5-million-vehicle telemetry backend like a trauma hospital entrance with a dedicated ambulance bay separate from the routine check-up lobby, backed by dashcam-style ring buffers in every car:

  • Two lanes at the front door: when a car sends a routine 10-second tire-pressure update (~1 GB/s across the fleet) vs. a critical brake-pressure fault (< 0.01% of bytes), the edge gateway immediately routes them into physically separate queues and Kafka clusters (distributed, partitioned append-only logs on disk). Ambulance traffic (critical alerts) gets a wide-open express lane to two cloud regions and dispatches within 1 second at 99.99% availability, completely immune to routine lobby congestion.
  • Every car carries its own shock absorber: 24 hours of telemetry per vehicle is only ~8.6 MB of local flash memory. Because the cloud returns an acknowledgment (PUBACK Success) only after Kafka replicates a message across availability zones, any network dead zone or cloud slowdown simply leaves routine data safely buffered in the car to trickle in later, while Kafka decouples fast ingestion from slower downstream databases.

A naive design pushes all 1,000,000 messages per second through one shared queue straight into one giant search database (like Elasticsearch), or splits processing into 30 tiny per-sensor microservices. That fails on all three axes: one Elasticsearch garbage-collection pause backs up the shared queue and delays life-critical brake alerts; indexing 43 billion routine heartbeats a day costs a fortune; a regional cellular reconnect wave triggers a self-inflicted thundering herd (millions of simultaneous retries); and 30 microservices turn every firmware update into a multi-team deployment nightmare.

Trace three packets from a single vehicle (VIN-402) to see how the balanced architecture behaves:

  1. Normal heartbeat (seq = 201): VIN-402 sends 1 KB on MQTT topic v/VIN-402/telemetry. A stateless Go gateway verifies the vehicle's mTLS certificate (mutual TLS hardware identity), appends the raw envelope to telemetry.raw (acks=all, 2-of-3 replicas in ~20 ms), and returns PUBACK Success. Flink decodes the Protobuf binary payload via Schema Registry into telemetry.canonical, updating Redis (latest state), TimescaleDB (1-minute fleet rollups), and the S3 Parquet data lake.
  2. Critical battery spike (seq = 202): Firmware detects cell over-temperature and publishes immediately on v/VIN-402/alert ahead of any queued data. Even if the routine telemetry cluster is overloaded, the gateway's dedicated alert producer flushes immediately (linger.ms=0) to the isolated 3-broker Alerts Kafka cluster (or fails over to the partner region after 400 ms), and the stateless Alert Processor dispatches push + ops console alerts in ~250 ms.
  3. 1-hour tunnel + reconnect (seq = 203..562): Offline in a mountain pass, VIN-402 buffers 360 KB locally. On exit, live seq = 563 flows immediately while v/VIN-402/backfill trickles in at a server-throttled 0.2 KB/s; Flink routes the late readings by event_time_ms so live charts never show a fake traffic spike.

Key trade-offs

  • Availability vs. consistency across the two paths. Routine telemetry configures Kafka for consistency (acks=all, min.insync.replicas=2, unclean leader election disabled) so acknowledged data is never lost; if a partition loses quorum, gateways return Quota exceeded and the vehicle's local flash buffer preserves eventual availability without data loss. Critical alerts make the opposite choice — availability first: if the home region stalls past 400 ms, the vehicle publishes to its partner region, and if Redis deduplication is unreachable, the Alert Processor fails open and dispatches anyway because a duplicate notification is far cheaper than a missed safety alert.
  • Physical alert-path isolation vs. one prioritized pipeline. Running a dedicated gateway queue, Kafka cluster, and stateless consumer for 0.01% of bytes adds a second small pipeline to monitor, in exchange for guaranteeing that no 1 GB/s telemetry backlog, Flink restart, or schema bug can ever consume the 4.38 min/month downtime budget of critical alerts.
  • Scalability vs. maintainability via standard building blocks. Stateless Go proxies, Kafka, Flink, Redis, TimescaleDB, Elasticsearch, and S3 Parquet cost slightly more compute per message than custom C++ storage engines or gateway disk spools, and require reading historical single-vehicle traces from S3 in seconds rather than milliseconds. In return, every failure mode has standard runbooks, horizontal scaling is linear, and adding a new alert threshold is a config change rather than a multi-service release.
  • Right-sized sinks per query vs. indexing everything in one store. Sending 100% of records only to cheap S3 Parquet while coalescing Redis updates (1 write/30 s/car), pre-aggregating TimescaleDB (1-minute buckets), and filtering Elasticsearch to the 1% diagnostic fault events cuts hot database cluster sizes by 10x–100x, at the cost of running Flink normalization upstream.
  • Event-time processing with watermarks vs. arrival-time processing. Aggregating by vehicle event_time_ms with a 5-minute watermark (late-data cutoff) plus nightly S3 Spark compaction means real-time dashboards are labeled provisional right after big outages, whereas arrival-time windows would permanently corrupt time-series charts whenever buffered backfill drains.
  • Edge load shedding vs. cloud-only buffering. Pushing dynamic config updates (backfill_kb_per_s = 0, telemetry_interval_s = 60) sheds load before bytes ever cross cellular links or cloud load balancers, trading coarser real-time granularity during severe incidents for rock-solid survival.

Common mistakes

  • Sharing one ingestion queue or Kafka cluster between brake alerts and periodic heartbeats. Any burst or broker stall in the 1 GB/s stream immediately blows past the 1-second alert SLO.
  • Indexing all 1,000,000 heartbeats/s into Elasticsearch. Search inverted indexes are built for sparse fault queries, not raw high-frequency sensor streams; full-stream indexing turns search cluster GC pauses into fleet-wide ingestion outages.
  • Acknowledging telemetry to the vehicle before Kafka acks=all completes. If a gateway ACKs on socket receipt and crashes 5 ms later, the vehicle has already deleted those readings from flash and the data is permanently lost.
  • Forgetting the post-blackout reconnect & backfill storm. Letting 1,000,000 vehicles reconnect in the same second and upload an hour of buffered data unthrottled doubles peak ingress and melts TLS terminators without jittered backoff, handshake rate limits, and server-paced backfill_kb_per_s.
  • Decoding firmware-specific sensor payloads inside the edge gateway. Tying gateway code to vehicle payload schemas forces risky gateway redeploys (dropping millions of sockets) on every vehicle firmware update.
  • Misclassifying very old backfilled sequence numbers as duplicates. If a per-VIN sliding dedup window returns duplicate for seq older than the window after a live heartbeat jumps max_seq forward, multi-day offline buffers get silently deleted instead of routed to the S3 lake for nightly compaction.

Follow-up questions

  • As new vehicle hardware generations and over-the-air firmware releases add or modify sensor fields, how do you evolve payload schemas without breaking downstream jobs? Keep the outer TelemetryEnvelope (vin, seq, event_time_ms, schema_id) tiny and frozen so Go gateways never decode inner sensor bytes. Register every firmware's inner Protobuf schema in a central Schema Registry gated by CI compatibility rules (never reuse field tag numbers, mark deleted tags reserved, never change a field's type, and add new fields as optional — e.g., add pack_temp_deci_c alongside legacy pack_temp_c instead of mutating units in place). Isolate all multi-generation mapping inside the single Flink Normalizer, which translates each schema_id into one clean telemetry.canonical schema for every downstream dashboard and sink; any unrecognized schema_id routes safely to telemetry.dlq (a dead-letter queue for later replay once the schema is registered) without crashing the pipeline, while rare breaking canonical changes use dual-writing to telemetry.canonical.v2 during migration.
  • Suppose your diagnostic search cluster loses 80% of its indexing throughput—how do you keep the streaming brokers from running out of RAM or local disk? Kafka brokers never push into per-consumer RAM buffers — each consumer group pulls sequentially from disk log segments by tracking its own integer offset, so an 80% slower Elasticsearch indexer simply increases its own consumer lag (~5,000–10,000 fault docs/s in minus ~4,000 docs/s indexed = ~1,000–6,000 docs/s lag, or <= 22 GB/hour) with zero impact on broker RAM, producers, alerts, Redis, or S3. Broker disk is strictly capped by retention.ms = 72h and retention.bytes per partition (which delete old log segments whether consumed or not), while broker byte-rate read quotas prevent catching-up consumers from starving live producer disk I/O. Meanwhile, the indexer backs off on Elasticsearch HTTP 429 rejections, sheds low-severity INFO logs past 15 minutes of lag, and if lag ever nears 50% of retention (36 hours), jumps its Kafka offset to latest to restore live search and backfills the missed slice asynchronously from the S3 Parquet lake.
  • Which concrete delivery and on-call metrics—such as recovery speed, release cadence, and paging signal-to-noise—would you track to verify operational maintainability? Instrument the four DORA software delivery metrics directly from CI/CD and incident logs per component: deployment frequency, lead time for changes, change failure rate (percentage of deploys triggering rollbacks or SLO alerts), and MTTR (Mean Time To Restore, average minutes from alert trigger to service recovery, verified via automated canary alerts). Pair those with on-call health metrics: paging alerts per shift, actionable page ratio (pages requiring real human action vs. self-resolving noise < 5 minutes, targeting > 85% actionable), runbook link coverage (100% of paging alerts), weekly manual toil hours (manual partition reassignments or DLQ replays), and version drift on Kafka/Flink/Go runtimes. Tie these directly to error-budget governance: if the 4.38 min/month alert-path budget burns too fast or noisy pages exceed threshold, feature changes pause automatically until automation and root-cause fixes bring toil and MTTR back in bounds.

Follow-up questions

Similar questions

More Tesla interview questions

All 52 Tesla questions →