Designing a Real-Time and Batch Device Telemetry Pipeline
System DesignModel answerLast updated
Architect an ingest-to-query system that handles millions of device messages per second while serving both sub-second dashboards and long-range batch analytics.
You are asked to design a system that collects telemetry from a very large fleet of connected devices — think millions of units — and makes that data useful in two distinct ways:
- Near-real-time consumption: live dashboards that refresh within seconds, plus threshold and anomaly alerts that fire within roughly half a minute.
- Batch consumption: historical queries spanning months, scheduled aggregates, offline model-training jobs, and ad-hoc SQL against the raw data.
Your design should address:
- How devices connect and deliver data (transport protocols, authentication, buffering on the device and server side).
- Where data lives at each stage — a fast "hot" tier for recent data and a cheap "cold" tier for the long tail.
- How the real-time path and the batch path relate to each other (two separate pipelines? one unified stream? how do you reconcile them?).
- How you model the schema and how you partition/shard data through the pipeline.
- How the system scales, stays reliable, and stays affordable.
- A small, concrete set of APIs and query shapes you intend to support.
Assume devices are multi-tenant (grouped into customer fleets), sometimes go offline for hours and reconnect in bursts, occasionally retransmit duplicate readings, and may report clock times that are wrong or out of order. State your assumptions about scale explicitly before drawing the architecture.
Hints
Hint 1
Write down the arithmetic first: devices × messages per second per device gives you sustained throughput; multiply by payload size to get bytes per second and per day. Peak load often hits 3–5× the average because of reconnect storms after an outage.
Hint 2
The single most important architectural decision is inserting a durable, replayable log between producers and consumers. Once the gateway acknowledges a write only after the log commits, you get your no-loss guarantee and you can attach as many independent readers as you want.
Hint 3
Separate the hot tier from the cold tier by *latency requirement*, not just by age. The latest-value cache, the time-series store for dashboard queries, and the object-store lake answer very different questions. Missing-heartbeat detection is really an event-time timer problem.
Hint 4
Late and duplicate data are the crux: pick event time with bounded watermarks for the streaming path, let anything later than the bound land in the lake, and recompute the affected aggregate partitions in batch. That reconciliation is exactly why keeping both paths pays for itself.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing the problem
Treat this as a pipeline of four decoupled stages: ingest → durable buffer → dual processing (stream + batch) → serving. The interviewer wants to see you size the problem, decouple producers from consumers, pick storage per access pattern, and handle the nasty parts of telemetry — duplicates, late/out-of-order data, skewed keys, schema drift, and cost.
1. Requirements and sizing
Functional. Devices emit readings (device id, event timestamp, a payload of metric name/value pairs, a schema version, a monotonically increasing sequence number) plus occasional events and error codes. Consumers need: per-device time-series lookup, fleet-level aggregates (e.g. p95 by region over a rolling window), alert rules like "temperature above 80 for 2 minutes", a latest-known-state lookup, and historical SQL over the lake.
Non-functional. No acknowledged message is lost; at-least-once delivery with dedupe downstream so aggregates are effectively-once. 99.9 %+ ingest availability; devices buffer locally during outages. Tenant isolation and per-tenant quotas.
Back-of-envelope. 10 M devices at one message per 10 s ≈ 1 M msg/s sustained, plan for ~3 M/s peak. At ~500 B per message that is ~500 MB/s, roughly 40–45 TB/day raw. Compressed columnar Parquet at ~8× gives ~5 TB/day, ~1.8 PB/year cold. Seven days of full-resolution hot data is ~35 TB compressed; 1-minute and 1-hour rollups are trivially small next to that. The buffer log at 3-day retention with 3 replicas is ~0.4 PB on disk — compress at the gateway to shrink it.
2. Architecture
Devices ──MQTT / HTTPS──▶ Gateways (L4 LB, mTLS auth, per-device rate limit, payload compression)
│ ack only after log commit
▼
Durable partitioned log (Kafka/Event Hubs), key = hash(deviceId), 1–2k partitions
┌───────────────────┬───────────────────┴───────────────┐
▼ ▼ ▼
Stream processor Raw archiver Last-value updater
(Flink): validate, (log → Parquet/Delta, (KV store: device →
dedupe, windowed 1–5 min files) latest reading)
rollups, alert eval │
│ ▼
▼ Lake (bronze → silver → gold), object storage
Hot time-series / │
OLAP store (Druid, ├──▶ Batch engine (Spark): re-aggregation,
ClickHouse, ADX) │ compaction, backfills, ML features
│ └──▶ SQL engine (Trino/warehouse) for ad-hoc queries
▼
Query API + dashboards + alert/notification service
Ingest. MQTT over TLS is the right default for battery-constrained, intermittently connected devices — tiny headers, persistent sessions so a reconnect resumes rather than re-registers, and a QoS level that gives per-message acknowledgement. Gateways are stateless and horizontally scaled (~50–100 k connections per node, so a few hundred nodes), with a batch HTTPS endpoint as a fallback for restricted networks. Authenticate with per-device X.509 certificates validated against a device registry, caching the result; enforce per-device and per-tenant rate limits at the edge. The gateway acknowledges only after the log write is committed — that single choice is what makes the no-loss guarantee real.
Buffer. The log absorbs bursts, decouples producers from consumers, and lets any consumer replay. Keying by hash(deviceId) preserves per-device ordering, which you need for sequence-based dedupe and stateful alert timers. Size partitions at ~1 MB/s each with headroom. On the device, keep a ring buffer and retry with exponential backoff plus jitter so a mass reconnect does not become a thundering herd.
3. Storage tiers
| Tier | Store | Contents | Latency | Retention |
|---|---|---|---|---|
| Latest state | KV (Redis/DynamoDB) | one row per device | ms | current only |
| Hot | time-series/OLAP | raw + 1-min rollups | sub-second | 7–30 days |
| Cold | lake, Parquet/Delta on object storage | raw + gold aggregates | seconds–minutes | years, tiered to archive |
Partition the lake by date/hour, never by device id (10 M directories is a small-file catastrophe). Cluster files within a partition by tenant. In the hot store, partition by day then shard by tenant/device, sorted by (deviceId, ts) so a single-device range scan is sequential.
4. Schema
Use Avro or Protobuf with a schema registry; carry schemaVersion in every message and allow only backward-compatible evolution (add optional fields). Store a narrow core — tenantId, deviceId, ts, ingestTs, metricName, value — plus a variant/map column for sparse attributes, so you are not maintaining a table with thousands of columns across heterogeneous device models. Route malformed messages to a dead-letter topic.
5. Correctness: duplicates, lateness, clocks
- Duplicates from retransmission/QoS: dedupe on
(deviceId, seq)with keyed state and a TTL (e.g. 1 h); make sinks idempotent upserts. - Late data: devices flush hours of backlog on reconnect. Use event time with short watermarks (~2 min) for real-time windows. Anything later than the watermark still lands in the lake, and the batch job recomputes the affected hourly/daily partitions — this is precisely why you keep both paths, and it is the strongest point to raise.
- Clock skew: persist both device
tsand serveringestTs, clamp implausible timestamps, and answer dashboard queries fromingestTswhen freshness matters. - Alerting: compile rules into keyed stateful operators with event-time timers; fleet-level conditions run on windowed aggregates; missing-heartbeat detection is a per-device event-time timer. Suppress duplicate notifications to avoid alert storms.
6. APIs
PUBLISH telemetry/{deviceId}(MQTT) andPOST /v1/telemetry(batched HTTPS).GET /v1/devices/{id}/metrics?name=&from=&to=&granularity=1mGET /v1/fleets/{id}/aggregate?metric=&agg=p95&groupBy=region&window=5mPOST /v1/alerts/ruleswith{fleetId, expr, channel}GET /v1/devices/{id}/latest- Ad-hoc SQL over lake tables for historical analysis.
7. Trade-offs and pitfalls
Two paths (Lambda) buys simplicity of reasoning and cheap replayable recomputation at the cost of maintaining two codebases; a single-stream (Kappa) design is leaner but forces all corrections through streaming and demands very long log retention. Multi-tenant hot fleets can still skew a partition — salt very large device keys if needed. Finally, watch the cost levers: compress at the edge, roll up aggressively beyond a week, tier cold data to archive storage, and cap per-tenant raw retention. Common mistakes: acking before durable write, partitioning the lake by device, using processing time for windows, skipping dedupe because "the protocol says QoS 1", and ignoring the reconnect-storm peak.