High-Throughput Robot Fleet Telemetry Platform (2 GB/s)
Medium · System Design · Data Engineer · Technical Screen
Prompt
Architect a fleet-wide telemetry ingestion and analytics platform for autonomous robots generating 2 GB/s of continuous diagnostic and operational traffic, with peaks reaching 3 GB/s. Incoming streams combine rapid sensor time series, state-transition logs, and periodic camera snapshots.
Design the platform around these operational requirements and sizing baselines:
- Scale baseline: 1 KB mean event payload (~2M events/s sustained, ~3M events/s peak), producing roughly 170 TB per day.
- Persist-before-acknowledge durability: Zero ingestion loss — edge devices must retain local copies until the backend confirms durable persistence.
- Hands-off elasticity: Scale smoothly as additional robots join the fleet without manual repartitioning or operator intervention.
- Dual-speed workloads: Power both low-latency live fault alerting and high-throughput batch/interactive analytics.
- Seamless schema evolution: Accommodate frequent additions and revisions to sensor payload layouts while keeping live consumers and historical queries running uninterrupted.
- Tiered retention: Keep 30 days of data in hot queryable storage and retain historical archives indefinitely in cold storage.
Scope & Expectations
- Walk through the end-to-end data path from onboard robot buffers to analytical storage and justify your technology stack across transport, messaging, stream processing, and storage.
- Explain how backpressure, rate limiting, and buffering absorb sudden 3 GB/s bursts and multi-hour downstream outages without losing data or stalling live alerts.
- Define the data model, file formats, partitioning strategy, and schema compatibility rules that keep analytical queries fast across evolving sensor versions.
Step-by-step walkthrough
Clarify requirements and scope
At 2 GB/s sustained (
~170 TB/day), the hardest part of this design is satisfying three promises that pull directly against one another: zero data loss (never tell a robot its data is safe until bytes are replicated on disk across failure zones), low-latency alerting alongside petabyte analytics (urgent faults must fire in seconds even if batch storage is backed up for hours), and continuous schema evolution (weekly firmware updates must add sensor fields without breaking old readers or rewriting petabytes of historical data).Functional requirements
- Multimodal edge streams: Ingest dense joint/IMU time series, discrete runtime logs, and periodic diagnostic images emitted across the robot fleet.
- Durable-commit acknowledgments: Issue delivery confirmations strictly after multi-zone disk replication succeeds; unconfirmed batches remain on the robot's SSD for retry.
- Split-speed consumption: Evaluate critical fault rules within seconds on a fast streaming path while landing every valid event into analytical tables (30-day hot SQL tier plus indefinite cold archive).
- Non-breaking contract updates: Let firmware teams ship revised sensor layouts continuously without stalling live alerting, lake writers, or historical table scans.
Non-functional requirements
- Throughput: 2 GB/s sustained (
2,000,000events/s at 1 KB average), bursting to 3 GB/s peak (3,000,000events/s). - Fault tolerance: Survive broker crashes, worker restarts, downstream storage outages, or the loss of an entire cloud Availability Zone (AZ) (an isolated data center with independent power and networking inside a cloud region) with zero loss of acknowledged data.
- Hands-off scalability: Absorb fleet growth automatically without manual partition shuffling or downtime.
Sizing assumptions
- Fleet & mix: ~10,000 active robots averaging
200 KB/seach (85%continuous sensor readings,5%state logs,10%~200 KBdiagnostic camera snapshots). - Durability boundary: "Zero data loss" covers every byte from acknowledgment onward, plus up to 24 hours of offline robot buffering on local SSD; if a robot stays offline longer than its physical disk holds, dropped counts are reported explicitly via heartbeats.
- Latency & ordering: Urgent alerts fire at
p99 < 5 seconds; ordering is required per robot, never globally across the fleet.
Back-of-the-envelope numbers
Working through the arithmetic step by step reveals why batching, image offloading, and columnar compression are mandatory:
1. Event rates & storage footprint Sustained ingress 2 GB/s / 1 KB = 2,000,000 events/s (Peak: 3 GB/s = 3,000,000 events/s) Daily raw volume 2 GB/s x 86,400 s = 172.8 TB/day (matches ~170 TB/day assumption) Hot tier (30 days) 172.8 TB x 30 = ~5.2 PB logical raw Columnar Parquet + zstd (~4x compression) -> ~1.3 PB physical hot storage Cold tier (annual) 172.8 TB x 365 = ~63.1 PB/year logical raw Columnar Parquet + zstd (~4x compression) -> ~15.8 PB/year archive storage 2. Payload split & edge batching Images (10%) 0.2 GB/s = ~1,000 snapshots/s at ~200 KB -> uploaded straight to object storage Streamed events 90% = 1.8 GB/s sustained, 2.7 GB/s peak (size gateways & Kafka for full 3.0 GB/s; robot zstd batch compression provides extra headroom) Per-robot batching 1 sensor batch/s (~170 KB) + 1 log batch/5 s (~50 KB) + instant P0 faults -> ~12,000 batch RPCs/s across 10,000 robots (167x fewer than 2M single-event RPCs!) 3. Ingestion gateways, Kafka cluster (3 AZs), and edge spool Stateless gateways ~200 MB/s per instance -> 15 needed at 3 GB/s peak Deploy 30 instances (10 per AZ) so losing 1 AZ leaves 20 instances (4 GB/s capacity) Kafka disk writes 3 GB/s peak x Replication Factor 3 = 9 GB/s cluster disk writes (6 GB/s cross-AZ) Kafka network out 6 GB/s follower fetches + 3 consumer groups x 3 GB/s = 15 GB/s peak cluster egress Kafka broker count 45 brokers (15 per AZ): ~67 MB/s produce (~100 MB/s with 1 AZ down), ~200 MB/s disk writes, and ~333 MB/s (2.7 Gbit/s) NIC egress per broker Kafka 24 h retention 1.8 GB/s x 86,400 s x 3 replicas = ~467 TB -> ~10.4 TB local NVMe per broker Kafka partitions 1,024 partitions (~3 MB/s per partition at 3 GB/s peak; scales to ~5 GB/s) Robot local SSD 24 h x 200 KB/s = ~17.3 GB spool per robot Lake writer sizing Provisioned for 2x sustained rate (3.6 GB/s) so backlogs drain as fast as they formThree architectural rules fall straight out of these numbers: 1. Keep 200 KB images out of Kafka so broker records stay uniform (
<= 170 KB) and memory-predictable. 2. Batch on the robot (1 record = 1 robot-second batch) so gateways and Kafka track 12,000 writes/s instead of 2,000,000 writes/s. 3. Read Kafka replicas inside the same AZ (rack-aware fetching) so 3 consumer groups reading 3 GB/s each do not rack up 9 GB/s of cross-AZ cloud bandwidth charges.Ingestion API, priority lanes, and claim-check images
Robots connect to gateways over a persistent bidirectional gRPC stream with mutual TLS (mTLS), allowing the robot to pipeline batches continuously in one direction while receiving durable acknowledgments asynchronously in the other. Traffic is separated into three priority lanes (
P0urgent faults/safety sent immediately,P1state logs batched every 5 s,P2continuous sensors batched every 1 s):rpc StreamTelemetry(stream Batch) returns (stream BatchAck) Batch { envelope: { robot_id, boot_id, lane: P0_URGENT | P1_LOGS | P2_SENSORS, batch_seq, // Starts at 0 per (boot_id, lane); increments by 1 oldest_unacked_seq, // Lowest seq in this lane still held in the robot's SSD spool firmware_version, robot_model, min_event_time, max_event_time, event_count, crc32c } payload_zstd: bytes // Compressed array of (schema_id, event_time, avro_bytes), <= 512 KB } BatchAck { lane, batch_seq, status: PERSISTED // Replicated in Kafka; robot deletes batch from SSD spool | RETRY_AFTER(ms) // Broker/gateway overload or transient CRC error; retry from spool | REJECTED(reason) // Invalid auth or >512 KB batch (agent splits batch and resends) }Key protocol invariants: - Pipelined window of 8 batches per lane: Within each lane, a robot sends oldest batches first and allows up to 8 unacknowledged batches in flight simultaneously, saturating high-latency WAN links without waiting a full round-trip per batch. - Persist first, validate schemas later: If a batch contains an unrecognized
schema_id, the gateway still persists it to Kafka rather than rejecting it at the edge; downstream consumers route undecodable events to the Dead-Letter Queue (DLQ), ensuring a Schema Registry hiccup never causes edge data loss.Images via the claim-check pattern (storing a large binary payload directly in object storage and passing only a lightweight reference ticket through the message bus):
1. POST /v1/images:presign { robot_id, image_id, size_bytes, sha256 } -> { presigned_put_url, object_key } 2. PUT <presigned_put_url> (200 KB single PUT directly to object storage with SHA-256 integrity header) 3. Emit tiny image_ref event { image_id, camera_id, event_time, object_key, sha256 } in normal telemetry batchEvery 10 seconds, each robot also sends a tiny heartbeat reporting
spool_bytes,oldest_unsent_event_time, anddropped_counts, giving operators live visibility into offline fleet backlogs.Data model: Kafka topics and Bronze / Silver / Gold lakehouse
To balance fast streaming writes with petabyte-scale SQL scans, we pair row-oriented Apache Avro at ingestion with column-oriented Apache Parquet managed by Apache Iceberg in the data lake:
- Apache Avro is a compact row-based binary format that writes all fields of one event contiguously with no framing bloat — ideal for fast streaming serialization and sequential replay.
- Apache Parquet is a column-based file format that groups values of the same column together on disk — letting analytical queries read 2 columns out of 50 (column pruning) and compressing repetitive sensor floats ~4× smaller.
- Apache Iceberg is an open table metadata layer on object storage that tracks Parquet files via atomic snapshots, enabling concurrent streaming writes, background compaction, and zero-rewrite schema evolution.
Kafka Topics telemetry.raw 1,024 partitions, key = robot_id (P1 + P2 compressed batches; 24 h retention) telemetry.priority 64 partitions, key = robot_id (P0 urgent batches for < 5 s alerting) telemetry.dlq 64 partitions, key = robot_id (events failing schema decode or validation) alerts 16 partitions (triggered alert payloads for paging/webhooks) Medallion Data Lakehouse (Object Storage) 1. Bronze (Raw Landing — Avro container files, 7-day retention) - Exact compressed batches dumped straight from Kafka; safety net to replay parser bugs. 2. Silver (Validated Event Tables — Iceberg over Parquet, 30 days Hot -> Indefinite Cold Archive) - One table per event type (joint_state, imu_reading, state_log, image_ref) - System columns: robot_id, boot_id, lane, batch_seq, event_idx, event_time, ingest_time, schema_id, firmware_version - Partition spec: hours(event_time), bucket(64, robot_id) - File sort order: (robot_id, event_time) 3. Gold (Aggregated Rollups — Iceberg + ClickHouse / Apache Pinot OLAP store) - 1-second min/max/mean rollups kept 30 days (~7 TB/day); 1-minute & 1-hour rollups kept hot multi-year (~40 TB/year, 60x smaller) powering sub-second fleet dashboards.Why partition Silver by
(hours(event_time), bucket(64, robot_id))? At 172.8 TB/day (7.2 TB/hour), partitioning only by day forces single-robot queries to sift through 170 TB of mixed files. Combining hourly time partitions with 64 hash buckets onrobot_idnarrows "Robot R-07 between 14:00 and 15:00" to a single bucket of a single hour (1/64of7.2 TBraw ≈28 MBof compressed Parquet, narrowed further by Parquet min/max row-group statistics on sortedrobot_id).High-level architecture and component selection
ROBOT EDGE (x 10,000) Local Agent: append + fsync to 17 GB SSD spool -> zstd batch -> lanes P0 > P1 > P2 | \ | Bidirectional gRPC + mTLS (Batch / BatchAck) \ 200 KB snapshots: presigned PUT v v [ L4 Network Load Balancer ] [ Object Storage: Raw Images ] | v [ Stateless Gateways (30 across 3 AZs) ] <--- per-robot token buckets & dynamic catch-up grants | Kafka produce (acks=all, min.insync.replicas=2); send BatchAck ONLY after Kafka confirms v [ Apache Kafka Cluster (45 brokers across 3 AZs: raw | priority | dlq | alerts) ] | | | v v v [ Flink: Lake Writer ] [ Flink: Real-Time Alerts ] [ Bronze Archiver ] reads raw + priority reads priority (+ raw rules) dumps raw -> Avro (7 d) SeqTracker dedup keyed per-robot windows Avro -> reader schema < 5 s p99 rule evaluation | \ | | valid +--> [ dlq ] v v [ alerts ] --> [ Alert Router ] --> Pager / Live UI [ Iceberg Silver Tables (Parquet) ] ---> [ Compaction & Rollups ] ---> [ Gold + ClickHouse/Pinot ] ^ | | v [ Schema Registry ] <--- Firmware CI (Full Transitive check) [ SQL (Trino/Spark) & BI ]Component justification and trade-offs:
Layer Selected technology Why it fits 2 GB/s (and main alternative) Edge protocol gRPC streaming + mTLS Multiplexes pipelined batches + explicit application-level BatchAck tied strictly to Kafka replication. (MQTT QoS 1 works only if its PUBACK waits on Kafka acks=all.) Message buffer Apache Kafka Proven multi-GB/s throughput, rack-aware follower fetching, tight Flink/Iceberg integration. (Alternative: Apache Pulsar decouples brokers from BookKeeper storage so scaling brokers moves zero data, trading simpler scaling for operating two distributed systems.) Stream engine Apache Flink True event-time watermarks, RocksDB keyed state for dedup, and two-phase checkpoint commits into Iceberg. Schema management Confluent-style Schema 4-byte schema_id wire header + Avro reader/writer resolution Registry + Avro enforcing Full Transitive compatibility in CI. Analytical storage Apache Iceberg (Parquet) 4x columnar compression (~47 PB/yr saved vs raw), hidden + ClickHouse/Pinot partitioning, zero-rewrite schema evolution, and fast OLAP.Deep dive: zero-loss ingestion and stateful deduplication
Our durability invariant is simple: every sensor batch sits on the robot's local SSD until it is confirmed on at least two Kafka brokers in separate Availability Zones.
Robot SSD Spool Stateless Gateway Kafka Partition (RF=3 across AZ-1,2,3) 1. Write batch 812 + fsync 2. Send Batch(seq=812) -------> 3. Verify mTLS cert, quota, CRC32C 4. Produce(key=robot_id, acks=all) --> Leader writes + >=1 cross-AZ follower replicates <-- Broker confirms (>=2 ISRs) 5. Return BatchAck(812, PERSISTED) <-- 6. Mark 812 acked, reclaim SSDExact Kafka settings guaranteeing durability: -
replication.factor = 3withbroker.rackset to each AZ,min.insync.replicas = 2, produceracks = all, andunclean.leader.election.enable = false. If fewer than 2 AZ replicas are in sync, Kafka rejects the write, the gateway returnsRETRY_AFTER, and the robot safely holds batch812on SSD. (Note: Kafka flushes to OS page cache asynchronously by default; losing an acked batch requires simultaneous power/kernel loss across two distinct AZs within milliseconds, an industry-standard trade-off vs. per-message diskfsync.)Why downstream deduplication is required — and why naive max-seq fails: Suppose Kafka replicates batch
812, but the gateway crashes before step 5 reaches the robot. The robot reconnects to another gateway and resends812, landing a duplicate record in Kafka (Kafka's built-in idempotent producer only deduplicates retries from the same gateway session). Furthermore, because up to 8 batches fly in parallel, batch811can retry and land in Kafka after812, so a naive"drop seq <= highest_seen"check would silently destroy811! Conversely, if a robot stays offline for 3 days and its full SSD drops ancient batches100..500, tracking missing gaps forever would leak memory.Including
oldest_unacked_seqin every envelope solves both edge cases cleanly inside a Flink operator keyed by(robot_id, boot_id, lane):class BatchDeduplicator: """Tracks committed batch sequence numbers per (robot_id, boot_id, lane) in Flink state.""" def __init__(self): # Every seq <= contiguous_through is already committed or permanently dropped at the edge self.contiguous_through = -1 # Out-of-order seqs already committed above contiguous_through (bounded by window <= 8) self.seen_above = set() def should_process(self, batch_seq: int, oldest_unacked_seq: int) -> bool: """Return True on first arrival of batch_seq; False if duplicate.""" # Any seq below oldest_unacked_seq was either acked earlier in this partition or dropped known_done_cutoff = oldest_unacked_seq - 1 if known_done_cutoff > self.contiguous_through: self.contiguous_through = known_done_cutoff self.seen_above = {s for s in self.seen_above if s > self.contiguous_through} # Reject if already covered by contiguous prefix or out-of-order set if batch_seq <= self.contiguous_through or batch_seq in self.seen_above: return False # Record new batch and advance contiguous prefix across any closed gaps self.seen_above.add(batch_seq) while (self.contiguous_through + 1) in self.seen_above: self.contiguous_through += 1 self.seen_above.remove(self.contiguous_through) return TrueBecause each priority lane maintains its own
batch_seqand sends oldest-first within its 8-batch window,seen_aboveholds at most ~8 integers per robot lane (with a 7-day state TTL). Flink snapshotsBatchDeduplicatorstate inside the exact same distributed checkpoint that commits new Parquet manifests to Iceberg, achieving end-to-end exactly-once tables. Orphaned camera snapshots (uploaded to S3 whoseimage_refbatch never arrived) are swept after 7 days by a daily anti-join between bucket inventory and theimage_refSilver table.Deep dive: multi-tier backpressure and flow control
Transient spikes (3 GB/s) and multi-hour downstream outages are absorbed cleanly because every tier enforces explicit flow control rather than buffering unbounded data in RAM:
- Robot edge shedding & priority queues: On slow links or
RETRY_AFTER, the agent drainsP0faults first,P1logs second,P2sensors third, and images last, backing off exponentially with random jitter. Only if an outage exceeds the 24-hour (17.3 GB) SSD spool does the robot degrade gracefully: dropping snapshots first, downsampling oldestP2sensors from 100 Hz to 10 Hz second, and never droppingP0/P1fault logs while reporting exactdropped_countsin heartbeats. - Gateway admission control: Gateways are pre-warmed for the 3 GB/s burst (cloud autoscaling takes minutes, bursts take seconds). Each robot gets a token bucket (a rate-limiting allowance refilling at
2×normal rate,400 KB/s, with a 10-second burst). If Kafka produce latency rises, gateways immediately returnRETRY_AFTERonP2batches while still admittingP0urgent faults — keeping gateway memory flat. - Kafka 24-hour shock absorber: If object storage or the Iceberg catalog goes down for 6 hours, Flink checkpoints pause while gateways keep accepting live robot traffic at full speed. Kafka buffers
1.8 GB/s × 21,600 s = ~39 TBcleanly inside its 24-hour disk retention. - Strict consumer isolation:
Lake Writer,Real-Time Alerts, andBronze Archiverrun as independent Flink jobs and Kafka consumer groups. A stalled Lake Writer applies credit-based backpressure only to its own Kafka reader, leavingP0real-time alerting at< 2 slatency. Once storage recovers, the2×-provisioned Lake Writer drains the 6-hour (39 TB) backlog in~6 hours(3.6 GB/scapacity minus1.8 GB/slive arrivals =1.8 GB/snet catch-up). If the Real-Time job itself ever lags> 60 s, live paging jumps to latest offsets while a background instance evaluates skipped offsets silently without waking on-call for stale events. - Coordinated reconnect catch-up budgets: Suppose a factory Wi-Fi outage ends and 1,000 robots reconnect holding 24 hours of spool (
~17 TBtotal). Unthrottled, they would overwhelm the cluster; capped at the static2×token bucket (200 KB/snet catch-up), they would take 24 hours to drain. Instead, gateways allocate dynamic catch-up tokens out of current cluster headroom (3.0 GB/scapacity minus2.0 GB/slive =1.0 GB/sspare, or~1 MB/s=5×normal rate per reconnecting robot), draining all17 TBsmoothly in~4.8 hourswhile live fleet traffic sees zero added latency.
- Robot edge shedding & priority queues: On slow links or
Deep dive: columnar lake modeling and schema evolution
Preventing the Parquet small-file problem at 2 GB/s: If 512 parallel Flink tasks wrote directly into 64 buckets every 2-minute checkpoint, each commit would create
512 × 64 = 32,768tiny files (47 millionfiles/day), crippling query planning! Configuring Iceberg'swrite.distribution-mode = hashshuffles records in Flink by(hour, robot_bucket)before writing so exactly one writer task owns each active bucket, producing 64 healthy~340 MBParquet files per 2-minute commit (1.8 GB/s × 120 s / 4× compression / 64 ≈ 840 MBacross all event tables). An hourly background compaction job sorts files by(robot_id, event_time)and expires old metadata snapshots.Zero-downtime schema evolution: 1. CI Full Transitive Compatibility: Firmware CI registers changed Avro schemas in the Schema Registry under Full Transitive rules — both older and newer readers must read all versions. Engineers may add or retire fields only with default values; changing a field's type (even
inttolong, which breaks older readers) or physical unit is rejected by CI and requires adding a new field instead. 2. Per-eventschema_idresolution: Each event inside a batch carries its 4-byte writerschema_id. The Flink Lake Writer fetches (and caches) that writer schema and resolves fields by name into the table's latest reader schema, filling newly added columns with defaults on the fly. 3. Metadata-only Iceberg evolution: A schema-sync hook adds newly registered optional fields to the Iceberg table catalog. Because Iceberg tracks columns by unique integer IDs rather than file position, adding or renaming columns requires zero rewrites of existing petabytes of Parquet files. 4. Major semantic breaks: True structural overhauls (such as switching joint frames from Euler angles to quaternions) publish a new subjectjoint_state_v2landing in its own table, unified for analysts behind a SQL view that applies the mathematical conversion.Hot-to-Cold storage lifecycle: Silver Parquet files stay in standard object storage for 30 days (
~1.3 PB) for fast interactive Trino/Spark SQL, then transition via bucket lifecycle policies to cold archive storage (~15.8 PB/year) while remaining cataloged in Iceberg so historical slices can be restored and queried whenever needed. Bronze Avro files expire after 7 days, avoiding doubling multi-year cold storage costs.Automated scaling, failure modes, and observability
Hands-off fleet scaling - Gateways & sticky stream rebalancing: Stateless gateways autoscale on CPU and ingress bytes/s. Because gRPC streams are long-lived, newly launched gateways would sit idle unless connections rotate — so gateways close streams gracefully after
10 minutes ± random jitter, causing robots to reconnect evenly across expanded capacity. - Kafka scaling & rack-aware reads: Automated Cruise Control rebalances partitions onto newly added brokers proactively when sustained disk/CPU exceeds60%(well before bursts). Enabling rack-aware follower fetching (KIP-392) lets Flink tasks read from the replica in their own AZ, eliminating~9 GB/sof cross-AZ consumer egress fees. When fleet growth eventually exceeds 1,024 partitions (> 5 GB/s), gateways cut over cleanly at timestampTtotelemetry.raw.v2(4,096 partitions), and Flink drainsv1completely before consumingv2so per-robot ordering andBatchDeduplicatorguarantees remain unbroken. - Flink autoscaling: Kubernetes operator adjusts Flink task parallelism automatically from consumer lag and task busy ratios up to the 1,024 partition ceiling.Failure recovery & key observability signals - Node, AZ, or registry failures: Losing a full AZ leaves
2 of 3Kafka replicas (>= min.insync.replicas = 2),20gateways, and30brokers — enough to handle the full3 GB/speak without interruption. Schema Registry downtime is masked by in-memory Flink caches; Lake Writer bugs are fixed cleanly by rolling Iceberg back to the last good snapshot and rewinding Kafka offsets (within 24 h) or replaying Bronze Avro files (within 7 d). Gateways cap uncompressed batch expansion ratios to block zip-bomb memory crashes. - Core monitoring metrics: Track gatewayp99ack latency, Kafka under-replicated partitions, per-job consumer lag in seconds, Flink checkpoint duration, DLQ rate sliced by(schema_id, firmware_version), and fleet-wide event-time lag (ingest_time - event_time) alongside robot SSDdropped_countsfrom heartbeats.Summary of key trade-offs
- Persist to
>= 2AZs before acknowledging vs. memory-ack at gateway: Adds ~10–30 ms per batch and requires a 17 GB SSD spool per robot, guaranteeing zero data loss across gateway and single-AZ crashes. - Persist raw batches first, validate schemas in Flink vs. reject unknown schemas at gateway: Lets malformed events temporarily consume Kafka disk en route to the DLQ, ensuring a Schema Registry outage or parser bug never destroys edge telemetry.
- One Kafka record per 1-second robot batch vs. one per event: Cuts broker message overhead
167×(12k/svs2M/s), trading per-event routing inside Flink decompression. - Claim-check presigned
PUTs for 200 KB images vs. inline Kafka blobs: Adds a presign +PUTstep on the robot for snapshots, keeping broker memory and partition sizing uniform. - Avro Bronze (7 days) + Parquet Silver (30 days hot, indefinite cold) vs. single storage format: Pays one streaming Avro-to-Parquet conversion in Flink to get fast sequential replay and 4× columnar compression (
~47 PB/yearsaved) with fast column-pruned SQL. - Peak-provisioned ingestion front door (
3 GB/s) vs. reactive autoscaling: Leaves headroom idle during quiet hours because multi-GB/s bursts arrive in seconds while cloud VMs and Kafka rebalances take minutes.
- Persist to
Intuition & how it works
Think of ingesting 2 GB/s (2,000,000 events/s) from 10,000 robots like running a nationwide parcel hub with a strict "zero lost packages" rule. Instead of handing 2 million loose envelopes per second to front-desk clerks who toss them onto one fragile belt, each delivery truck (robot) packs 1 second of mail into a compressed crate on its own local hard drive, sends bulky oversized crates (200 KB camera snapshots) straight to a bulk warehouse (object storage) with just a barcode claim ticket, and waits for a stamped receipt proving its crate is copied inside two separate fireproof warehouses (replicated Apache Kafka brokers across Availability Zones) before erasing its truck copy. Behind those warehouses, independent sorting lines (Apache Flink jobs) unpack crates at their own speed — one fast lane scanning urgent red envelopes (P0 alerts) in under 5 seconds, and a heavy lane reorganizing events into neatly labeled filing cabinets (columnar Apache Parquet tables) that compress 170 TB/day by ~4× for years of fast search.
A naive architecture — firing 2 million individual HTTP JSON requests per second at web servers that acknowledge receipt in memory and insert directly into a database or uncompacted files — collapses immediately at this scale. Per-request overhead saturates server CPUs, any gateway crash loses thousands of "acknowledged" events held in RAM, uncoordinated parallel writes create millions of tiny files that grind analytical queries to a halt, and a single firmware team renaming or retyping a JSON sensor field breaks downstream pipelines across the company.
Trace how robot R-07 moves 1 second of data (170 sensor readings, 1 urgent motor fault, and 1 200 KB snapshot) through our pipeline even while object storage experiences a brief hiccup:
1. Edge spool & claim-check: R-07 writes its events to its 17 GB local SSD spool, uploads the 200 KB camera snapshot directly to object storage via a presigned URL (a short-lived signed upload link), and immediately sends the urgent fault on the P0 lane (telemetry.priority), firing an on-call alert via Flink in < 2 seconds.
2. Durable batch write: R-07 sends compressed sensor Batch(seq=812, oldest_unacked=810) over its mTLS gRPC stream; the gateway produces to telemetry.raw with acks=all across 2+ Availability Zones, and only after Kafka confirms replication does R-07 receive BatchAck(812, PERSISTED) and free its SSD space.
3. Deduplicating retries: Suppose a network blip caused R-07 to resend Batch(seq=812) through a second gateway, writing a duplicate into Kafka. When the Flink Lake Writer reads that partition, its stateful BatchDeduplicator sees 812 was already recorded for (R-07, boot_id, P2) and drops the duplicate cleanly.
4. Columnar landing: Flink resolves each event's 4-byte Schema Registry ID (mapping older or newer Avro sensor layouts to the current table schema without breaking), shuffles rows by (hour, bucket(64, robot_id)), and commits large, compressed Parquet files into Apache Iceberg once storage responds.
Key trade-offs
- Replicate across
>= 2Availability Zones before acknowledging vs. acknowledging on gateway receipt. Waiting foracks=all(min.insync.replicas=2) adds ~10–30 ms per batch and requires a local SSD spool on every robot, buying true zero data loss across gateway crashes and single-AZ outages. - Persist raw batches first, validate schemas downstream vs. strict schema rejection at the gateway. Gateways check auth, quotas, and CRC32C checksums without decoding inner events, so a Schema Registry outage or buggy rule routes affected events safely to the Dead-Letter Queue (DLQ) (a holding topic/table for failed events) instead of losing robot data at the front door — at the cost of carrying invalid bytes briefly in Kafka.
- One Kafka record per 1-second robot batch vs. one record per event. Batching shrinks message rates
167×(12,000records/s instead of2,000,000/s) and spares gateways from decompressing payloads, pushing decompression and per-event routing into Flink workers. - Claim-check object storage for 200 KB images vs. embedding blobs in Kafka. Offloading snapshots adds a presigned
PUTstep on the robot, keeping Kafka messages small, uniform, and predictable for broker page caches and consumer RAM. - Row-based Avro (7-day Bronze) + column-based Parquet (30-day Hot, Indefinite Cold Silver) vs. one format. Paying a one-time Flink conversion from Avro to Parquet gives fast sequential raw replay for parser bugs while cutting multi-petabyte analytical storage by ~4× (
~15.8 PB/yearphysical vs.~63.1 PB/yearraw) and speeding up column-selective SQL scans by orders of magnitude. - Full Transitive schema compatibility vs. unrestricted schema edits. Requiring every added or removed Avro field to carry a default value (and forbidding in-place type or unit changes) constrains firmware engineers slightly, ensuring months-old batch jobs and live readers coexist across multi-day fleet upgrades with zero downtime.
- Pre-provisioned peak front door (
3 GB/s) + Apache Kafka vs. reactive autoscaling or Apache Pulsar. Sizing gateways and Kafka for 3 GB/s leaves capacity idle off-peak because bursts arrive in seconds while cloud VMs and Kafka partition rebalances take minutes (whereas Pulsar's decoupled BookKeeper storage scales brokers without moving data, at the operational cost of running two distributed storage systems).
Common mistakes
- Acknowledging the robot as soon as a gateway reads bytes into RAM (or producing with
acks=1), which silently loses data whenever a gateway container restarts or a Kafka leader fails before followers copy the write. - Ignoring the robot's local disk in the durability and backpressure design, turning every transient
503or Wi-Fi drop into permanent data loss. - Assuming Kafka's idempotent producer eliminates robot-level duplicates, forgetting that when a robot times out and reconnects through a different gateway instance, Kafka sees a brand-new producer session and writes a second copy.
- Deduplicating with a naive
drop if seq <= max_seenrule, which falsely drops valid out-of-order batches whenever multiple pipelined batches are in flight, or sharing one sequence counter across throttled (P2) and unthrottled (P1) lanes so sequence gaps balloon memory. - Writing unshuffled Parquet files from every parallel streaming task, generating tens of millions of kilobyte-sized files per day instead of hash-partitioning by
(hour, robot_bucket)and running hourly sort compaction. - Partitioning the data lake only by day (
~170 TB/day) without bucketing onrobot_id, forcing single-robot diagnostic queries to scan terabytes of mixed fleet files. - Replaying hours of delayed offline backlog directly through live paging rules, waking on-call engineers at 3 AM for transient warnings that resolved six hours earlier.
Follow-up questions
- How should the pipeline process delayed batches uploaded hours later by robots operating on spotty Wi-Fi? Disconnected units spool up to 24 hours (
~17.3 GB) onto onboard SSD and flush oldest batches first within each priority lane under dynamic gateway catch-up tokens (~1 GB/sof spare cluster capacity), keeping reconnect bursts from slowing live fleet streams. Because payloads preserve capture-timeevent_timeand Silver Iceberg tables partition byhours(event_time), delayed batches write straight into their original hourly partitions, get sorted by background compaction, and trigger incremental recomputation of only those affected 1-minute and 1-hour Gold rollups. At the edge of streaming alerts, gateways readmax_event_timefrom the batch header and mark batches older than 5 minutes asbackfillso Flink evaluates historical records without firing stale 3 AM pages or holding back live watermarks, while 10-second device heartbeats advertiseoldest_unsent_event_timeto track partition completeness. - What safeguards stop a single malfunctioning robot spewing corrupt payloads from degrading ingestion for healthy units? Defense runs in concentric rings starting at the front door: gateways enforce per-device token buckets (
2×baseline rate) and immediately reject bad CRC32C checksums, oversized batches (>512 KB), or zip-bomb expansion ratios before touching Kafka. When structurally sound batches carry inner payloads that fail Avro decoding inside Flink, a stream monitor aggregates DLQ counts perrobot_id; crossing an anomaly threshold (such as>20%invalid events or>1,000failures/minute) writes thatrobot_idto a compactedquarantinecontrol topic read by every gateway. Gateways instantly clamp the offending unit to10%bandwidth and reroute itsP1/P2streams to a separatetelemetry.quarantinetopic (keeping its tinyP0safety stream alive and sampling 1% of errors into the DLQ alongside exact drop counters) until fixed firmware or an operator lifts the quarantine. - How would you structure a dead-letter pipeline for events that fail schema checks and replay them safely once fixed? Failed records in Flink are written as self-contained envelopes to
telemetry.dlqand compacted into an Icebergdlq_eventstable storing the untouchedavro_bytes, composite event key(robot_id, boot_id, lane, batch_seq, event_idx),schema_id,firmware_version,event_time, consumer build SHA, and categorizederror_class. Triage followserror_class:UNKNOWN_SCHEMA_ID(caused by delayed CI registration) runs an automated hourly retry for 7 days;VALIDATION_ERRORandPIPELINE_BUGtrigger targeted batch replays once the rule or parser fix ships; and trueDECODE_ERRORbit-rot from buggy firmware stays archived for debugging while paging the owning firmware team by(schema_id, firmware_version). Replays feed raw bytes through the identical Lake Writer transform and commit via an IcebergMERGE INTOmatched on(robot_id, boot_id, lane, batch_seq, event_idx)pruned to the affectedhours(event_time)partitions, making retries completely idempotent.
Follow-up questions
- How should the pipeline process delayed batches uploaded hours later by robots operating on spotty Wi-Fi?
- What safeguards stop a single malfunctioning robot spewing corrupt payloads from degrading ingestion for healthy units?
- How would you structure a dead-letter pipeline for events that fail schema checks and replay them safely once fixed?
Similar questions
- Telemetry Validation and Automated Firmware Rollout System
- Fleet KPI Hierarchy for Humanoid Firmware Rollouts
- Root-Cause Analysis for Robot Charging Failures and Slowdowns
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform