IoT Sensor Data Pipeline Architecture
System DesignModel answerLast updated
Design a distributed system to ingest and query temperature readings from millions of globally distributed IoT devices with high write throughput.
Problem
Design an architecture for collecting and analyzing temperature measurements from a global fleet of IoT devices. The system receives readings from 10 million sensors, with each device reporting its temperature every 10 seconds.
Your design must support:
Core Capabilities
- Data ingestion: Accept approximately 1 million temperature events per second on a sustained basis
- Current state lookup: Provide an endpoint that returns the most recent temperature for any given sensor
- Historical analysis: Provide an endpoint that computes aggregate statistics (average, minimum, maximum) for any sensor across a specified time window
Quality Attributes
- Scalability: Architecture should accommodate growth in sensor count without fundamental redesign
- Performance: Latest temperature queries must complete in under 100 milliseconds
- Resilience: Service should tolerate regional infrastructure failures
What to provide
- Textual description of your architectural components and their interactions
- API endpoint definitions for writing data and reading results
- Data schema design and technology selection for storage layers
- Approach to managing write throughput and data lifecycle
Event format
Each measurement contains: {sensor_id: string, timestamp: long, temperature: float}
Calculate expected storage volumes as part of your design.
Hints
Hint 1
Start by calculating throughput, bandwidth, and storage requirements to ground your design in concrete numbers
Hint 2
Consider how time-series data differs from general-purpose data—compression ratios, query patterns, and specialized storage engines matter
Hint 3
Think about the trade-off between storing raw measurements versus pre-aggregated summaries for different time ranges
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: IoT Temperature Monitoring Architecture
1. Capacity Planning and Requirements Clarification
Begin by establishing the scale parameters and working through the calculations.
Write throughput
- 10M sensors reporting every 10 seconds = 1M writes/second baseline
- Design for 2–3× overhead to handle reconnection storms and regional traffic shifts
Data sizing
- Each event: sensor identifier (16–36 bytes), timestamp (8 bytes), temperature value (4 bytes)
- Approximately 50 bytes payload, roughly 100 bytes including protocol overhead
- Network ingress: 1M events/s × 100 bytes = 100 MB/s
Storage capacity
- Daily volume: 1M/s × 86,400 seconds = 86.4 billion measurements
- Uncompressed: 86.4B × 50 bytes ≈ 4.3 TB daily, 130 TB for 30-day retention
- Time-series compression (delta encoding for timestamps, XOR compression for floats): reduces to ~2–4 bytes per point
- Compressed: ~260 GB daily, ~8 TB for 30 days (before replication)
- This compression advantage drives the choice of specialized time-series storage
In-memory state
- Current value cache: 10M entries × 100 bytes ≈ 1 GB (easily fits in memory)
Pre-computed aggregates
- Per-minute rollups: 10M sensors × 1,440 minutes = 14.4B entries daily (~290 GB)
- Hourly rollups: 60× smaller
Questions to explore:
- Are sensors capable of local buffering and batch transmission?
- What are the consistency requirements—can we tolerate duplicate processing with idempotency?
- Should sensors route to a home region or use proximity-based routing?
2. API Contract
POST /v1/ingest
Body: {
"readings": [
{"sensor_id": "sensor-42", "timestamp": 1700000000000, "temperature": 22.3},
...
]
}
Response: 202 Accepted # persisted to durable log
GET /v1/sensors/{sensor_id}/latest
Response: 200 {
"sensor_id": "sensor-42",
"timestamp": 1700000000000,
"temperature": 22.3
}
GET /v1/sensors/{sensor_id}/aggregate?from={ts}&to={ts}
Response: 200 {
"average": 21.7,
"minimum": 18.5,
"maximum": 24.1,
"sample_count": 8640
}
Design considerations:
- Ingestion may use MQTT for resource-constrained devices rather than HTTP
- Include
sample_countin aggregates to help clients detect missing data - 202 status signals durability in the message queue, not necessarily in the database
3. Architecture Overview
IoT Devices ──► Regional Load Balancers ──► Ingestion API Layer
(validate, authenticate, batch)
│
▼
Message Queue (Kafka/Kinesis)
Partitioned by hash(sensor_id)
┌────────────────────┬─────────┴──────────┬──────────────┐
▼ ▼ ▼ ▼
Cache Writer Time-Series Writer Aggregation Archive Writer
(most recent) (raw measurements) Pipeline (cold storage)
│ │ │ │
▼ ▼ ▼ ▼
Redis/DynamoDB Time-Series DB Rollup DB Object Storage
(current state) (7-day hot tier) (30-day+) (Parquet/S3)
└──────────────── Query API ───────────────┘
Component rationale:
- Message queue decouples ingestion from storage. Sensors receive acknowledgment once data reaches the durable log. Database slowdowns create consumer lag but no data loss.
- Kafka partition count: 100 MB/s fits in several hundred partitions. Kinesis would need ~1,000 shards (1,000 records/s limit per shard unless batched).
- Partitioning strategy: Hash by
sensor_idmaintains ordering per sensor and enables horizontal scaling of all consumers.
4. Storage Layer Design
Current value store: Redis Cluster or DynamoDB
- Schema:
sensor_id→{timestamp, temperature} - Conditional write: update only if incoming timestamp > stored timestamp (prevents late arrivals from overwriting newer data)
- Performance: Single-digit millisecond lookups, well within 100ms target
Raw time-series: Specialized TSDB (InfluxDB, TimescaleDB) or Cassandra
Schema for Cassandra approach:
CREATE TABLE raw_readings (
sensor_id text,
day_bucket text,
ts timestamp,
temperature float,
PRIMARY KEY ((sensor_id, day_bucket), ts)
)
- Composite partition key
(sensor_id, day_bucket)limits partition size to 8,640 rows - Distributes writes uniformly across cluster nodes
- Range queries become efficient scans of a single partition or small set of adjacent partitions
- Time-only partitioning would create a single hot partition receiving all current writes
Aggregate tables:
CREATE TABLE rollup_minute (
sensor_id text,
month text,
minute_ts timestamp,
sum_temp float,
count int,
min_temp float,
max_temp float,
PRIMARY KEY ((sensor_id, month), minute_ts)
)
CREATE TABLE rollup_hour (
sensor_id text,
year text,
hour_ts timestamp,
sum_temp float,
count int,
min_temp float,
max_temp float,
PRIMARY KEY ((sensor_id, year), hour_ts)
)
Critical detail: Store sum and count separately, not pre-computed averages. Averages cannot be meaningfully combined across buckets with different sample counts. Calculate average as total_sum / total_count across selected buckets.
Query execution strategy:
- Long-range queries use hourly aggregates for the bulk of the range
- Use minute aggregates or raw data for partial periods at range boundaries
- A 30-day query reads ~720 hourly records + ~120 minute records, avoiding 259,000+ raw data points
5. Write Optimization Techniques
Batching throughout the pipeline:
- Sensors or edge gateways aggregate multiple readings before transmission
- Ingestion API batches messages to Kafka with linger time and compression enabled
- Database writers group inserts by partition key
Storage engine selection:
- LSM-tree based systems (Cassandra, many TSDBs) convert random writes into sequential I/O
- Time-series databases use specialized chunk formats optimized for append patterns
Cache write reduction:
- Each consumer batch is deduplicated: retain only the latest reading per sensor
- This dramatically reduces cache write volume
Backpressure handling:
- Message queue absorbs traffic bursts while consumers auto-scale based on lag metrics
- Sensors implement local buffering with exponential backoff and jitter on retry
6. Data Lifecycle Management
| Tier | Contents | Technology | Retention |
|---|---|---|---|
| Hot | Latest value | Redis/DynamoDB | Current only |
| Warm | Raw measurements | Time-series DB (SSD) | 7 days (TTL) |
| Warm | Minute/hour rollups | TSDB/Cassandra | 30 days / 1+ year |
| Cold | Raw archive | S3 (Parquet format) | Multi-year, lifecycle to Glacier |
Implementation details:
- Archive consumer writes Parquet files directly from message queue, creating an independent cold path
- Time-to-live policies automatically expire old data from warm tier
- Compaction processes keep disk usage bounded
- Ad-hoc analysis queries use Athena or similar query engines against object storage
7. Multi-Region Resilience
Regional isolation:
- Deploy complete ingestion and processing pipeline in multiple regions
- Geographic DNS routing directs sensors to nearest healthy region
Failover mechanism:
- Health checks trigger DNS updates when regional failures occur
- Sensors buffer measurements locally during reconnection
- Exponential backoff prevents thundering herd
State replication for query path:
- Current-value store uses DynamoDB Global Tables or Redis active-active replication with last-write-wins conflict resolution based on event timestamp
- Aggregate data replicates asynchronously across regions for query redundancy
- Time-series databases can use cross-region replication or accept eventual consistency
Common Pitfalls
- Averaging pre-computed averages produces incorrect results when buckets contain different counts
- Partitioning purely by timestamp creates a hot partition receiving all current writes
- Skipping the message queue couples ingestion directly to database performance, losing durability guarantees
- Not compressing time-series data wastes 10–20× more storage than necessary
- Synchronous cross-region writes add latency and reduce availability without providing meaningful benefits for time-series data
This architecture handles the write-heavy nature of IoT workloads while providing low-latency reads through specialized storage layers and careful pre-aggregation.