Design a Real-Time Thermal Telemetry & Ingestion System
System DesignModel answerLast updated
Design an IoT telemetry platform ingesting half a million sensor readings per second, featuring low-latency current state queries, delayed data processing, and downsampled long-term storage.
Scenario
A global cold-chain logistics network requires continuous temperature monitoring across millions of refrigeration units, transit hubs, and fleet vehicles. Exposure to temperature anomalies can compromise sensitive cargo.
You need to design a reliable, scalable system that ingests high-throughput temperature sensor data, calculates current asset state, triggers real-time alerts, and maintains both raw and aggregated history.
System Characteristics & Constraints
- Sensor Population: 5,000,000 active temperature sensors.
- Reporting Frequency: Every 10 seconds per device.
- Ingestion Scale: ~500,000 events/sec baseline, with burst capacity up to 1,000,000 events/sec (e.g., when mobile assets reconnect after losing network signal).
- Latency Targets:
- P99 latency for fetching current asset status must be under 50 ms.
- Delay from device ingestion to safety breach alerting must be under 5 seconds.
- Data Lifecycle Requirements:
- Raw event retention: 30 days.
- Aggregated hourly/daily summary retention: 2 years.
Requirements
Functional
- Device Connection & Ingestion: Securely collect readings over standard lightweight protocols (MQTT, HTTP/2, gRPC over TLS).
- Event Handling: Support device generation timestamps as well as server receipt timestamps. Deduplicate redundant messages and process out-of-order data gracefully.
- Current State Projection: Provide real-time queries for the latest recorded temperature and operational status for any sensor, asset, or facility.
- Time-Series Storage & Rollups: Store detailed event data and continuously compute downsampled aggregates (min, max, mean per hour/day), supporting backfilled historical uploads.
- Rules Engine & Threshold Alerts: Detect out-of-bounds conditions (e.g., temperature exceeds 4°C for more than 15 consecutive minutes) and emit notifications.
Non-Functional
- Availability & Resilience: 99.99% availability for the write path. Vehicles operating offline must store readings locally and upload batch payloads without starving live streams.
- Scalability: Horizontal scaling for API gateways, message queues, stateful processors, and storage layers.
What to Cover
- Capacity Estimation: Traffic volume, storage size, and memory requirements.
- System Architecture: End-to-end design from edge gateways to ingestion, streaming components, and database tiers.
- Data Schemas & Storage Strategy: Payloads, ingestion protocols, current-state cache structure, raw time-series storage, and aggregate schemas.
- Handling Out-of-Order & Delayed Data: Deduplication strategies, watermarking rules, avoiding stale cache overwrites, and historical recomputation pipelines.
- Retention & Downsampling: Automated rollups and efficient lifecycle management for expiring raw metrics.
Hints
Hint 1
Establish clear estimates for write throughput vs query memory before selecting data stores.
Hint 2
Distinguish between live streaming ingest and backfilled bulk ingest from reconnected vehicles by splitting Kafka topics.
Hint 3
Use atomic versioning or timestamp comparisons (e.g., Lua scripts in Redis) to prevent old backfill data from corrupting the current-state projection.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Real-Time Thermal Telemetry Platform Architecture
1. Capacity & Scale Estimation
Data Volume & Ingestion Rate
- Devices: 5,000,000 active sensors emitting 1 payload every 10 seconds.
- Average Ingestion Rate: $5,000,000 / 10 = 500,000 \text{ events/sec}$.
- Peak Ingestion Rate: $1,000,000 \text{ events/sec}$ (2x multiplier for fleet reconnects).
- Payload Size: ~100 bytes binary (Protobuf over MQTT/gRPC).
- Ingress Bandwidth:
- Average: $500,000 \times 100 \text{ B} = 50 \text{ MB/sec}$.
- Peak: $1,000,000 \times 100 \text{ B} = 100 \text{ MB/sec}$.
Storage Estimates
- Raw Events / Day: $500,000 \times 86,400 = 43.2 \text{ billion records/day}$.
- 30-Day Raw Storage:
- Uncompressed: $43.2\text{B} \times 30 \text{ days} \times 100 \text{ bytes} \approx 129.6 \text{ TB}$.
- Specialized time-series compression (Delta-of-Delta for timestamps, XOR/Gorilla for floats) achieves ~10:1 compression: ~13 TB compressed.
- With Replication Factor (RF=3): ~39 TB total raw storage.
- 2-Year Downsampled Storage (Hourly Aggregates):
- Sensors: $5\text{M}$.
- Hours in 2 years: $24 \times 365 \times 2 = 17,520 \text{ hours}$.
- Aggregated rows: $5\text{M} \times 17,520 = 87.6 \text{ billion rows}$.
- Row size (SensorID, Hour, Min, Max, Avg, Count): ~40 bytes.
- Columnar storage (Parquet/Iceberg): ~3.5 TB total.
- Current State Cache:
- $5\text{M sensors} \times 200 \text{ bytes (state metadata)} = 1 \text{ GB}$.
- Easily fits in a single Redis primary-replica pair (sharded for high availability).
2. High-Level System Architecture
[ Edge Devices / Vehicles ]
│ (Local SQLite Buffer)
│
▼ mTLS / TLS
[ API Ingestion Gateways ] ──(Auth & Validation)
│
├─────────────────────────────────────────┐
▼ (Live Stream) ▼ (Backfill Stream)
[ Kafka Topic: tele.live ] [ Kafka Topic: tele.backfill ]
(512 Partitions, key=sensor_id) (128 Partitions, key=sensor_id)
│ │
└────────────────────┬────────────────────┘
│
▼
[ Apache Flink Cluster ]
/ │ \
/ │ \
▼ ▼ ▼
[ Redis Cluster ] [ TSDB / Scylla ] [ Alert Engine ]
(Current State) (Raw 30-Day) (Threshold Evaluation)
│ │
▼ ▼
[ Batch Processing ] [ PagerDuty / Ops Center ]
(ClickHouse / Iceberg)
Core Components
- Edge Gateways: Run on local store servers or vehicle telematics boxes. When WAN connectivity drops, readings are stored locally in an embedded database (e.g., SQLite/RocksDB) and flushed in batches upon reconnection.
- Ingestion Layer: Stateless MQTT Brokers (e.g., EMQX) and gRPC/HTTP Gateways behind a Layer 4 Load Balancer. They terminate mTLS connections, authenticate device certificates, sanitize payloads, and attach a server receipt timestamp (
arrival_ts). - Event Bus (Apache Kafka): Serves as an ingestion buffer.
tele.live: High-priority topic keyed bysensor_idfor real-time telemetry.tele.backfill: Dedicated lower-priority topic for reconnected devices flushing historical buffers. This prevents backfilled data from starving live monitoring pipelines.
- Stream Processing (Apache Flink): Stateful stream processing framework executing three parallel pipelines:
- Pipeline A: Maintains real-time state projections in Redis.
- Pipeline B: Evaluates temporal alerting rules (e.g., threshold violations exceeding 15 minutes).
- Pipeline C: Writes raw data into the time-series store and aggregates metrics into hourly windows.
- Storage Tiering:
- Hot Cache: Redis for immediate point lookups ($<5 \text{ ms}$).
- Operational Time-Series Store: ScyllaDB or TimescaleDB for raw logs (30-day TTL).
- Analytical Lakehouse: Apache Iceberg / ClickHouse on Object Storage (S3) for long-term aggregate trends (2-year retention).
3. Data Schemas & Protocols
Wire Payload (Protobuf)
syntax = "proto3";
message TelemetryReading {
string sensor_id = 1;
uint64 sequence_number = 2;
int64 event_timestamp_ms = 3; // Device clock
float temperature_celsius = 4;
float battery_level_pct = 5;
uint32 status_flags = 6;
}
message TelemetryBatch {
string gateway_id = 1;
string asset_id = 2;
repeated TelemetryReading readings = 3;
}
Redis Current State Store
Key: sensor:status:{sensor_id}
Data Structure: Hash
{
"temp": 2.4,
"event_ts": 1711958400000,
"arrival_ts": 1711958400120,
"seq": 104523,
"health": "OK"
}
Raw Time-Series Schema (ScyllaDB / Cassandra)
CREATE TABLE sensor_telemetry_raw (
sensor_id uuid,
bucket_date date, -- Partition key: (sensor_id, bucket_date)
event_ts timestamp,
sequence_num bigint,
arrival_ts timestamp,
temperature float,
battery float,
status_flags int,
PRIMARY KEY ((sensor_id, bucket_date), event_ts, sequence_num)
) WITH CLUSTERING ORDER BY (event_ts DESC, sequence_num DESC)
AND compaction = {
'class': 'TimeWindowCompactionStrategy',
'compaction_window_unit': 'DAYS',
'compaction_window_size': '1'
};
4. Handling Out-of-Order Data, Clock Skew, and Late Arrivals
A. Deduplication and Idempotency
- Unique Key: Each reading is uniquely identified by
(sensor_id, event_ts, sequence_number). - Primary Database: Writing to ScyllaDB using the primary key
((sensor_id, bucket_date), event_ts, sequence_num)makes writes naturally idempotent. duplicate inserts perform an upsert with identical values. - Stream Deduplication: Flink maintains a 10-minute sliding Bloom Filter or RocksDB state keyed by
sensor_idtracking recentsequence_numbervalues to suppress duplicate processing in alert/rollup pipelines.
B. Protecting Current-State Cache from Stale Overwrites
When a vehicle uploads 8 hours of buffered data after re-establishing connectivity, late-arriving events must not overwrite the latest real-time status in Redis.
We execute a Redis Lua script for atomic conditional updates:
local key = KEYS[1]
local new_event_ts = tonumber(ARGV[1])
local new_seq = tonumber(ARGV[2])
local current_event_ts = tonumber(redis.call('HGET', key, 'event_ts') or 0)
local current_seq = tonumber(redis.call('HGET', key, 'seq') or 0)
-- Update state only if incoming event is strictly newer chronologically
if (new_event_ts > current_event_ts) or
(new_event_ts == current_event_ts and new_seq > current_seq) then
redis.call('HMSET', key,
'temp', ARGV[3],
'event_ts', ARGV[1],
'seq', ARGV[2],
'arrival_ts', ARGV[4],
'health', ARGV[5])
return 1
end
return 0
C. Watermarking and Aggregation Reconciliation
- Watermark Generation: Flink uses Event-Time processing with a bounded out-of-orderness watermark (e.g., $W(t) = \max(\text{event_ts}) - 2 \text{ minutes}$).
- Handling Out-of-Range Timestamps:
- If a device clock is malfunctioning and sends timestamps far in the future ($\text{event_ts} > \text{arrival_ts} + 5 \text{ mins}$), the server clamps
event_tstoarrival_tsand flags the event asCLOCK_SKEW_EXCEEDED.
- If a device clock is malfunctioning and sends timestamps far in the future ($\text{event_ts} > \text{arrival_ts} + 5 \text{ mins}$), the server clamps
- Late Aggregate Reconstruction:
- Events arriving after an hourly aggregation window has closed bypass the real-time Flink window operator.
- Instead, late backfilled records trigger an event on a
reconcile.queuetopic. - A background worker re-runs the hourly aggregate query against the raw store for the affected
(sensor_id, hour)partition and updates the long-term aggregate in ClickHouse/Iceberg with an incrementedversion_id.
5. Data Lifecycle & Retention Strategy
-
Hot Tier (0 – 7 Days):
- High-performance NVMe storage backing the ScyllaDB cluster.
- Optimized for fast sequential writes and recent range queries.
-
Warm Tier (8 – 30 Days):
- ScyllaDB nodes with Time-Window Compaction Strategy (TWCS).
- Once a 1-day SSTable window exceeds the 30-day threshold, ScyllaDB drops the entire SSTable file instantaneously on disk, avoiding expensive tombstone cleanup operations.
-
Cold Analytical Tier (30 Days – 2 Years):
- Continuous Flink / Spark job rolls up raw data into Parquet files partitioned by
year/month/daystored in Amazon S3 / Object Storage. - Queried via ClickHouse or Trino for compliance reporting and trend analytics.
- Continuous Flink / Spark job rolls up raw data into Parquet files partitioned by
6. Key Design Trade-Offs
| Decision | Selected Approach | Alternative | Trade-Off Rationale |
|---|---|---|---|
| Ingestion Queue | Partitioned Dual Kafka Topics (live vs backfill) | Single Topic | Prevents reconnected fleet vehicles (bursting backfilled data) from stalling real-time temperature breach alerts. |
| Current State Update | Redis + Atomic Lua Script | Database Triggers / CDC | Redis delivers $< 5 \text{ ms}$ query latency to satisfy the 50 ms SLA. Lua scripts enforce chronological ordering without needing full transactions. |
| Storage Engine | ScyllaDB with TWCS | Standard Relational DB (PostgreSQL) | Column-family time-series engines handle high write concurrency (1M writes/sec) and allow zero-overhead partition drops for raw data expiry. |
7. Summary Evaluation Criteria
A candidate demonstrates mastery of this design by:
- Identifying that offline fleet reconnection creates massive ingest spikes that must be decoupled from real-time monitoring via topic isolation.
- Formulating a precise solution (Lua CAS scripts) to prevent out-of-order backfill events from corrupting current state caches.
- Defining clear strategies for raw data lifecycle management (TWCS SSTable dropping) to eliminate tombstone performance degradation.