Real-Time IoT Device Monitoring System
System DesignModel answerLast updated
Build a scalable backend to track health status for millions of IoT devices sending periodic check-ins and quickly identify unresponsive units.
Real-Time IoT Device Monitoring System
You need to architect a backend that tracks the operational status of a large fleet of IoT devices. Specifically, your system monitors 1,000,000 devices that each transmit a lightweight status ping containing their unique identifier and a timestamp every 10 seconds. Your platform must provide real-time visibility into which devices are currently unresponsive—defined as those that haven't transmitted any signal within the past 60 seconds.
What You Need to Support
Core Functionality:
- Accept and process status pings from the entire device fleet
- Provide an API endpoint
GET /devices/inactivereturning identifiers of all devices silent for 60+ seconds
Performance and Scale:
- Support approximately 100,000 incoming status messages per second under normal operation
- Inactive device status should reflect reality within a few seconds
- Handle sudden traffic surges gracefully (network reconnections, regional outages recovering)
What to Deliver
Describe your approach to:
- How you'll receive, process, and store the incoming status signals
- Your strategy for identifying inactive devices efficiently at query time without iterating through millions of records
- How you'll manage data lifecycle and address potential performance bottlenecks
Hints
Hint 1
Think about whether you need to store every individual status ping or just maintain current state
Hint 2
Consider how devices report to you versus how you detect silence—one is event-driven, the other requires periodic evaluation
Hint 3
Ask yourself if the inactive device list should be computed on-demand for each API request or maintained continuously
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Real-Time IoT Device Monitoring System
Understanding Scale and Constraints
Begin by quantifying what you're dealing with:
- Device population: 1M devices × 1 ping per 10 seconds = ~100K writes/second sustained. Allow 2-3x capacity for reconnection storms.
- Data volume: At roughly 100 bytes per message, that's around 10 MB/s of ingress. Network bandwidth is trivial; the challenge is handling the write request rate.
- State size: You only need to remember when each device last reported. 1M entries at ~100 bytes each totals approximately 100-150 MB—easily fits in memory.
- Latency target: Inactive status should be current within a few seconds.
Essential clarifying questions:
- Is the 60-second threshold strict or does it include a grace buffer?
- Can we rely on device-provided timestamps? (No—use server arrival time to avoid clock skew issues)
- What's the expected size of the inactive set? (During major outages, potentially all 1M devices, requiring pagination)
Key insight: Historical pings have minimal value once processed. The product needs current state, not an event archive. This drives storage decisions.
API Design
POST /status { device_id, timestamp } -> 204
GET /devices/inactive?cursor=&limit=1000®ion=
-> { snapshot_time, total_inactive, device_ids[], next_cursor }
The snapshot_time tells consumers how current the data is. total_inactive enables UI count displays without fetching all IDs.
Storage Strategy
- Redis Sorted Set
last_contact:{shard}: stores device_id as member with server receipt timestamp (epoch milliseconds) as score - Inactive set
inactive:{shard}: precomputed set of currently unresponsive devices, updated by a background worker - Device registry (PostgreSQL): device_id, organization, location, provisioning status—authoritative source for which devices should exist
Use ZADD last_contact:{s} GT <timestamp> <device_id> where the GT flag prevents out-of-order or delayed messages from incorrectly moving the timestamp backward.
Architecture Overview
IoT Devices -> Load Balancer -> Stateless Ingestion Layer -> Kafka (partitioned by device_id)
|
Stream Processors (batch + pipeline writes)
|
Redis Cluster (last_contact shards)
|
Background Worker (1-2s interval) -> inactive set + events
|
Query API / Real-time notifications
Ingestion layer: Validates requests, stamps server arrival time, publishes to Kafka. Horizontally scalable stateless services.
Kafka: Acts as a buffer against traffic spikes. If Redis experiences slowdown or reconnection bursts arrive, events queue instead of being dropped.
Stream processors: Consume in batches and deduplicate within each batch—if a device appears multiple times, keep only the latest timestamp. Write using pipelined Redis commands to achieve tens of thousands of updates per second per consumer.
Redis cluster: Shard by hash(device_id) mod N with N = 8-16 sorted sets.
- Even a single Redis instance can handle 100K pipelined writes/second
- Sharding provides headroom and reduces per-operation size
Efficient Inactive Device Detection
The core optimization: Since the sorted set score represents last-contact time, inactive devices form a contiguous range at the beginning:
ZRANGEBYSCORE last_contact:{s} -inf (current_time - 60000)
This runs in O(log N + K) where K is the number of inactive devices. Healthy devices are never touched.
Precompute instead of query-time computation: A background worker runs every 1-2 seconds per shard:
- Executes the range query to get currently inactive devices
- Compares against
inactive:{s}to identify state transitions (active→inactive and inactive→active) - Updates the inactive set and publishes transition events for alerting
The API then reads from the precomputed set using cursor-based pagination. Read cost becomes independent of dashboard access patterns.
Critical subtlety—processing lag: If consumers fall 30 seconds behind during a spike, naively using wall_clock - 60s will incorrectly flag thousands of healthy devices as inactive.
Solution: Track a processing watermark—the minimum processed message timestamp across all partitions. The background worker evaluates against the watermark, not current time. If lag exceeds thresholds, pause state transitions and mark API responses as stale.
Data Lifecycle and Bottleneck Mitigation
Data expiration: Sorted set entries don't need TTLs—a stale score is exactly what signals "inactive." When devices are decommissioned, the registry triggers ZREM. A daily reconciliation job catches any orphaned entries.
Durability tradeoffs: Raw status pings don't require persistent storage—accumulating billions of rows daily just to answer "seen recently?" is wasteful.
- Redis state is self-healing: after complete loss, every active device naturally repopulates within 10 seconds
- Run read replicas for availability
- During cold start, suppress inactive transitions for one full window (60s) to avoid false alarms about 1M "inactive" devices
- Kafka retention of several hours enables replay if necessary
Bottleneck mitigation strategies:
| Challenge | Solution |
|---|---|
| Redis single-thread write limit | Shard keys, pipeline operations, batch deduplication |
| Uneven partition load | Hash by device_id, not organizational hierarchy |
| Connection scaling | Long-lived connections (HTTP/2, MQTT); 1M connections across ~20 nodes |
| Large inactive responses | Pagination + aggregated counts by region |
| Worker failure | Leader election per shard; idempotent processing |
Key Tradeoffs
Redis vs. distributed database (Cassandra, DynamoDB): Redis provides fast score-based range queries and in-memory performance. The tradeoff is reduced durability, acceptable here since state reconstructs quickly.
Kafka vs. direct writes: Kafka adds latency (hundreds of milliseconds) and operational complexity. In return, it buffers spikes, decouples components, and enables replay. Given the "handle surge traffic" requirement at 100K/s, the benefits justify the cost.
Worker interval vs. freshness: 1-2 second sweeps satisfy the "few seconds freshness" requirement. More frequent sweeps add load for minimal benefit.
What Strong Candidates Demonstrate
- Calculated state size to confirm in-memory viability
- Recognized sorted set scores enable range queries rather than full scans
- Proposed precomputing inactive sets rather than computing per-request
- Identified the processing lag vs. wall clock time hazard
- Used server timestamps to avoid device clock skew problems
- Discussed durability tradeoffs and self-healing properties
- Addressed operational concerns like cold starts and partition strategy