Design a Fleet Health Monitoring System for Edge Devices
System DesignModel answerLast updated
Architect a scalable real-time monitoring system to track the online/offline status of 10 million connected edge devices with low latency and high availability.
Architect a monitoring infrastructure for a fleet of 10 million IoT security cameras. The system must continuously track device status and provide real-time dashboard metrics showing the exact total count of healthy and unhealthy cameras across the network.
Operating Environment & Requirements
- Fleet Size: 10,000,000 registered cameras.
- Heartbeat Rate: Each camera emits a small ping (payload containing
camera_id,timestamp,firmware_ver) once every 60 seconds. - Health Definition: A device is marked healthy if the system has ingested at least one heartbeat from it within the last 120 seconds (2 minutes). If 120 seconds elapse without a heartbeat, the device transitions to unhealthy.
- Dashboard Latency: Global health metrics should be updated within 5 to 10 seconds of real-world state changes.
- Data Retention: The dashboard only requires live global/aggregated status metrics. Storing full historical time-series raw logs is out of scope.
Core Challenges to Address
- Ingestion Layer: Efficiently receiving ~167,000 requests/sec under steady state, while handling "reconnect storms" (e.g., after regional internet outages) where traffic spikes to 500,000+ requests/sec.
- State Management: Storing and updating per-camera operational status efficiently without performing full 10M row table scans every few seconds.
- Expiration Detection: Detecting when a camera stops sending heartbeats and transitioning its status to unhealthy in real time.
- Data Integrity: Handling duplicate pings, out-of-order network packets, and late-arriving messages without skewing the aggregate counters.
- System Resiliency: Recovering state after node failures and ensuring counter accuracy.
Hints
Hint 1
Avoid periodic full database scans across all 10 million records; design state updates around event-driven transitions.
Hint 2
Partition incoming device updates by `camera_id` so all events for a specific device are processed sequentially on the same worker node.
Hint 3
Use time-bucketed data structures or a timer wheel mechanism to track offline timeouts efficiently without polling every device record.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. High-Level Requirements & Capacity Sizing
Throughput Sizing
- Registered Devices ($N$): 10,000,000 cameras.
- Steady-State Ingestion Rate: $$\text{RPS} = \frac{10,000,000 \text{ heartbeats}}{60 \text{ seconds}} \approx 166,667 \text{ requests/sec}$$
- Peak / Reconnect Storm Rate (3x multiplier): $\approx 500,000 \text{ requests/sec}$.
- Payload Size: ~100 bytes per heartbeat payload.
- Ingestion Bandwidth (Steady): $166,667 \times 100 \text{ B} \approx 16.6 \text{ MB/s}$ (133 Mbps).
- Ingestion Bandwidth (Peak): $\approx 50 \text{ MB/s}$ (400 Mbps).
Key Observation: Network bandwidth is modest, but connection and request concurrency are high. The primary scaling axis is handling connections and state updates concurrently without CPU bottlenecks.
2. System Architecture
The architecture consists of four distinct components: Ingestion, Message Streaming, Stateful Processing, and Dashboard Aggregation.
+------------------+
| 10M Edge |
| Camera Fleet |
+--------+---------+
| HTTP/gRPC (167k - 500k RPS)
v
+------------------+
| Layer 7 Load |
| Balancers (ALB) |
+--------+---------+
|
v
+------------------+
| Stateless Ingest |
| API Service |
+--------+---------+
| Produce (Keyed by camera_id)
v
+------------------+
| Distributed Log |
| (Apache Kafka) | (e.g., 64-128 Partitions)
+--------+---------+
|
v
+------------------+ +-----------------------+
| Stateful Stream | <--> | In-Memory Key-Value |
| Processors | | Store (Redis / RocksDB)|
+--------+---------+ +-----------------------+
|
| Incremental Delta Updates (+1/-1)
v
+------------------+
| Global Metrics |
| Cache (Redis) |
+--------+---------+
|
v
+------------------+
| Web UI / |
| Dashboard |
+------------------+
3. Detailed Component Design
A. Ingestion Layer
- Protocol: HTTP/2 over TLS or gRPC. Using persistent HTTP/2 connections reduces TLS handshake overhead.
- Stateless API Gateway: A pool of lightweight stateless servers (Golang or Rust) behind AWS ALB/NLB.
- Ingress Logic:
- Authenticate ping token.
- Stamped incoming message with
server_ingest_timestampto protect against client clock skew. - Publish event to Apache Kafka topic
camera-heartbeats, partitioned deterministically byhash(camera_id). - Return
200 OKimmediately.
B. Stream Partitioning & Ordering
- Partitioning by
hash(camera_id)guarantees that all heartbeats from the same camera land on the exact same Kafka partition and are processed sequentially by the same worker thread. - This eliminates cross-node lock contention and simplifies out-of-order execution.
4. State Management & Expiration Detection
To avoid scanning 10M records periodically, the system relies on state-transition-driven counter updates.
Per-Camera State Model
For every camera, we store a small record in an in-memory key-value database (e.g., Redis or embedded RocksDB):
{
"status": "HEALTHY", // or "UNHEALTHY"
"last_seen_timestamp": 1700000000,
"expiration_bucket": 1700000120
}
Expiration Management: Time-Bucket Slotted Sets
Instead of setting individual keys with individual TTL timers (which creates high memory overhead and timer management complexity), we use Time-Bucket Slots (60-second granularity):
- Bucket Granularity: Divide time into discrete 60-second windows (Buckets).
- Bucket Key:
bucket:{timestamp_in_seconds}(e.g.,bucket:1700000120). - Each bucket contains a set of
camera_ids whose next health deadline falls within that window. - Bucket Worker Loop: Every 10 seconds, a background worker checks expired buckets (buckets where
bucket_time <= current_time - 120s).
Time-Bucket Slots (Expiration Wheel):
Bucket T [00:00-01:00] --> { Cam_1, Cam_4, Cam_99 } <-- Swept at T+120s
Bucket T+60 [01:00-02:00] --> { Cam_2, Cam_5 }
Bucket T+120 [02:00-03:00]--> { Cam_3 }
Heartbeat Processing Flow
When a heartbeat for camera_id = X arrives at t_now:
- Read
X's current record from the state store. - If
status == UNHEALTHY:- Update status:
status = HEALTHY. - Increment global healthy counter:
INCRBY global_healthy_count +1. - Decrement global unhealthy counter:
DECRBY global_unhealthy_count -1.
- Update status:
- If
status == HEALTHY:- Remove
Xfrom its old expiration bucket (bucket:old_exp).
- Remove
- Calculate new expiration time:
new_exp = t_now + 120s. - Update
X's record: setlast_seen_timestamp = t_nowandexpiration_bucket = new_exp. - Insert
Xintobucket:new_exp.
Timeout Expiration Sweeper Flow
A worker periodically sweeps buckets older than 120 seconds:
- Fetch all
camera_identries inbucket:expired_time. - For each
camera_idin the bucket:- Read the device state.
- If
expiration_bucket <= current_time(meaning no newer heartbeat updated this camera to a later bucket):- Change
status = UNHEALTHY. - Decrement global healthy counter:
DECRBY global_healthy_count -1. - Increment global unhealthy counter:
INCRBY global_unhealthy_count +1.
- Change
- Delete
bucket:expired_time.
5. Handling Edge Cases & Data Anomalies
| Edge Case | Solution |
|---|---|
| Out-of-Order Heartbeats | Use server_ingest_timestamp. Ignore incoming pings where server_ingest_timestamp <= last_seen_timestamp. |
| Duplicate Messages | Handled idempotently. If last_seen_timestamp is already updated to a newer or equal timestamp, skip state transitions. |
| Client Clock Skew | Ignore client timestamps for state computation; use server arrival time at the API Gateway layer. |
| Reconnect Storms | The Kafka layer acts as a buffer. Ingestion nodes write directly to Kafka. Consumer workers process at maximum safe throughput without crashing. Latency degrades gracefully while preventing system failure. |
6. Fault Tolerance & Consistency
- Global Counter Drift: Incremental counting (
+1/-1) can drift over long periods due to unexpected process crashes. - Reconciliation Job: Run a scheduled background batch job (e.g., every 1 hour via Spark or Flink) to perform an absolute count of
HEALTHYvsUNHEALTHYdevices in the state store and overwrite the aggregate Redis counters. - Worker Crash Recovery: Processor nodes save state checkpoints in RocksDB backed by Kafka changelogs. If a processor node dies, another node takes over its Kafka partition and resumes state tracking without data loss.
7. Resource & Storage Estimates
- Per-Device State Store:
- 10,000,000 devices $\times$ ~100 bytes/record $\approx 1 \text{ GB}$ total RAM.
- Entire state easily fits into a single Redis primary/replica pair or a small cluster.
- Redis Counter Cache:
global_healthy_count: 8 bytes.global_unhealthy_count: 8 bytes.- Read latency for dashboard requests: < 1 ms.
8. Summary Comparison of Design Approaches
| Approach | Latency | Scalability | Complexity |
|---|---|---|---|
Full DB Scans (SELECT COUNT(*) WHERE last_seen > NOW()-120) | Poor (~10-30s per scan) | Poor (Fails at 10M rows) | Low |
| Individual Redis Key TTL Expiration Events | Good | Moderate (High CPU on mass expire) | Medium |
| Partitioned Event Stream + Time Bucket Wheel (Chosen Design) | < 1 sec | High (Scales horizontally) | Medium-High |