Fleet Command Dispatch and Telemetry Reconciliation at Scale
System DesignModel answerLast updated
Design a durable, idempotent command pipeline and telemetry reconciliation engine for five million intermittently connected edge devices.
Background
You work on the infrastructure team for a platform that manages a large fleet of edge devices — industrial controllers, remote inference nodes, and sensor hubs deployed in the field. Operators and automated systems need to send imperative commands to devices: run a self-test, swap a model artifact, restart a service, issue an emergency halt. The catch: devices go offline for hours or days at a time, reconnect over high-latency links, and report back with duplicated or out-of-order telemetry.
What You Need to Design
Design the full end-to-end pipeline that handles:
- Accepting and dispatching commands to devices or groups of devices
- Tracking exactly where each command is in its lifecycle, per device
- Reconciling incoming telemetry against server-side state
- Keeping the system safe when commands are cancelled, devices reconnect in a storm, or the network partitions mid-execution
Constraints and Scale
- Fleet size: 5 million registered devices; up to 1 million concurrently online
- Telemetry volume: ~33,000 events/sec at steady state, bursting to 200,000 events/sec during mass reconnects (~1 KB per event)
- Command throughput: up to 10,000 dispatch requests/sec; a single tag-targeted command can fan out to millions of individual device queues
- Targeting: commands can address explicit device IDs or dynamic tag expressions (e.g.,
region=us-east,model=v2-arm) - Scheduling: commands carry a
not_beforetimestamp, anexpires_atTTL, and a priority - Lifecycle states:
QUEUED → DISPATCHED → ACKNOWLEDGED → EXECUTING → COMPLETED | FAILED | EXPIRED - Durability: zero command loss for any command accepted within its TTL
- Idempotency: a device must never execute the same non-idempotent action twice, even if the command is redelivered
Deliverables
Address all four areas in your answer:
- API and data model — command submission, cancellation, status query, device-side protocol, and the schema for commands, per-device queues, and execution logs
- System architecture — the major components and how they connect: submission path, fan-out, gateway layer, telemetry ingestion, and reconciliation
- Reconciliation strategy — how late, duplicate, and out-of-order telemetry is handled; how clock drift and server-inferred state interact with observed device reports
- Failure modes and safety — network partitions mid-execution, reconnect storms, zombie/stale command execution, and cancellation fencing
Hints
Hint 1
Start by separating imperative commands (run diagnostic, reboot) from declarative desired-state updates (active model = v2.3). They have very different idempotency and retry semantics, and conflating them leads to subtle bugs.
Hint 2
Exactly-once delivery is impossible over a lossy network. The realistic goal is at-least-once delivery paired with device-side deduplication, giving exactly-once effect. Make sure your design draws that boundary clearly.
Hint 3
Order telemetry events by a device-managed monotonic sequence number rather than wall-clock time. This makes clock drift irrelevant to correctness and gives you a clean forward-only state lattice for lifecycle transitions.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Sizing and Framing
Turn the numbers into architecture pressure before drawing anything.
- Gateways: 1 million concurrent connections at ~50k long-lived sockets per node means roughly 20–30 gateway nodes with healthy headroom.
- Telemetry: 200k events/sec × 1 KB = ~200 MB/s at burst. A partitioned log (Kafka or Kinesis) absorbs this easily. A relational database taking raw writes directly does not.
- Fan-out: a single command targeting
region=us-eastcan generate millions of per-device queue rows. This fan-out must be asynchronous, rate-limited, and decoupled from the submission API's response time. - Idempotency clarification: exactly-once delivery is not achievable on a lossy link. The actual goal is at-least-once delivery plus device-side deduplication — exactly-once effect. For non-idempotent actions, the device executes at most once; if it crashes mid-action, it reports
FAILED(interrupted)rather than re-running silently.
2. Separate Imperative from Declarative Commands
This is the most important structural decision and strong candidates raise it unprompted.
- Declarative (desired-state / device twin): "active model = v2.3", "subsystem X = enabled". The server stores a versioned desired state; the device converges toward it. Redelivery and reordering are harmless because the latest version wins. Emergency stop fits here as a latched high-priority twin update (
estop=true, epoch=N) — it can be sent aggressively until acknowledged because it is inherently idempotent. - Imperative (discrete action): "run diagnostic #8812", "reboot", "swap weights". These require per-device sequencing, TTL enforcement, deduplication, and cancellation fencing. The rest of this answer focuses here.
3. API
POST /commands
body: { idempotency_key, action, params,
target: { device_ids[] | tag_query },
not_before, expires_at, priority, criticality }
response: { command_id }
POST /commands/{id}/cancel
response: { cancel_epoch }
GET /commands/{id}/devices?state=FAILED&cursor=...
GET /devices/{id}/commands
PUT /devices/{id}/desired-state # twin update, versioned
Device-to-gateway protocol (MQTT or WebSocket):
SYNC { last_applied_seq, last_event_seq }— sent on reconnect so the gateway knows where to resumeCMD { seq, command_id, action, params, expires_at, cancel_epoch, signature }— server to deviceEVENT { command_id, device_event_seq, state, ts, ... }— device to server
4. Data Model
| Table | Partition key | Key fields |
|---|---|---|
commands | command_id | action, params, target snapshot, not_before, expires_at, criticality, cancel_epoch, status |
device_queue | (device_id, seq) | command_id, state, state_source (OBSERVED/INFERRED), last_event_seq, updated_at |
device_meta | device_id | next_seq, last_acked_seq, revocation_watermark, gateway_id, twin versions |
execution_log | (device_id, device_event_seq) | append-only raw event, used for audit and replay |
Use a wide-column store (Cassandra or DynamoDB) partitioned by device_id so all of a device's state sits in one partition. Tag targets are snapshotted at submit time — the target set is resolved once and stored with the command, making rollouts auditable and keeping the target from drifting mid-execution.
seq is a per-device monotonic counter assigned by the control plane, not a wall clock.
5. Architecture
Operators / Automation
|
Command API ──► commands table
| |
| Fan-out workers
| (tag resolution → device index,
| rate-limited writes to device_queue,
| assigns seq, publishes to dispatch topic)
| |
| Kafka: dispatch topic (keyed by device_id)
| |
Connection registry (Redis: device_id → gateway_id)
| |
└─────► Gateway fleet (MQTT/WSS, ~1M conns)
│ ▲
telemetry topic │ SYNC / CMD
(Kafka, keyed by │
device_id) │
│
Reconciler workers
(one consumer group,
partitioned by device_id)
│
device_queue / device_meta / execution_log
│
Timeout/expiry scheduler, metrics, alerting
Gateways are stateless relays: they authenticate connections, route CMD messages from the dispatch topic to the right socket, and append EVENT messages from devices to the telemetry Kafka topic. They never write command state. Reconcilers are the single writer per device, consuming the Kafka partition that owns that device_id — no distributed locks needed.
6. Exactly-Once Effect and Fencing
- Every
CMDcarriesseq,command_id,expires_at,cancel_epoch, and a server signature. - The device maintains a durable high-water mark of the last executed
seqand a small ring buffer of recently seencommand_ids. - Before executing, the device writes an
INTENT(seq)record to local persistent storage. - After a reboot, an
INTENTwithout a matchingDONEis not re-executed for non-idempotent actions. The device reportsFAILED(reason=interrupted)and an operator decides whether to issue a fresh command. - Retries are always new commands with new seq values issued by the control plane — never a redelivery of the original message. This keeps the concepts of "redeliver for delivery guarantee" and "re-execute the action" cleanly separate.
- Cancellation raises
revocation_watermarkindevice_meta. Any cachedCMDwith aseqat or below the watermark, or whosecancel_epochis stale, is rejected without execution. The device reportsFAILED(reason=revoked).
7. Reconciliation Strategy
Use device sequence, not wall-clock time. Events are ordered by (device_id, device_event_seq), a counter the device increments and persists durably. Wall-clock timestamps are stored for display only. The server records its own receipt timestamp separately. Clock drift between device and server is irrelevant to ordering correctness.
The lifecycle is a forward-only lattice. The rank order is:
QUEUED < DISPATCHED < ACKNOWLEDGED < EXECUTING < {COMPLETED | FAILED | EXPIRED}
A late ACKNOWLEDGED arriving after an EXECUTING event is stored in the execution log for audit purposes but does not move the state backward. Duplicate events (same device_event_seq) are no-ops.
Observed facts outrank inferences. The timeout scheduler writes EXPIRED or FAILED(timeout) with state_source=INFERRED. If a device later reports COMPLETED, the reconciler overrides the inferred terminal state, sets reconciled_late=true, and emits an event so that any downstream automation (such as a compensating retry) can react.
Twin drift. Reported state is compared to the desired version on every reconnect. A mismatch re-queues a convergence command, which is safe because twin updates are idempotent.
8. Failure Modes
Reconnect storms. Kafka absorbs the burst. Reconcilers drain at their own pace. The gateway layer rate-limits SYNC processing per device to avoid thundering-herd pressure on the database.
Network partition mid-execution. The device continues executing and records events locally. On reconnect it replays buffered EVENT messages in device_event_seq order. The reconciler applies them in order; if the server had already inferred FAILED, it corrects the state.
Zombie commands. A device reconnecting after a long offline period may have cached CMD messages. Before executing any cached command, the device checks expires_at against its local clock (with a conservative drift buffer) and validates cancel_epoch against the current revocation_watermark received in the SYNC response. Anything that fails either check is dropped and reported as EXPIRED or FAILED(revoked).
Fan-out backpressure. A tag-targeted command that resolves to 2 million devices is written to device_queue by a pool of fan-out workers reading the device index in cursor-paginated batches. The command is marked DISPATCHING until fan-out completes, then DISPATCHED. If a worker crashes mid-fan-out, it resumes from a checkpoint — the (device_id, seq) write is idempotent on retry.
Common Mistakes
- Conflating imperative and declarative commands and trying to apply the same retry/dedup logic to both
- Using wall-clock time as the ordering key for telemetry events — this breaks under any clock skew
- Letting gateways own command state, which makes them stateful and hard to scale or replace
- Treating
EXPIREDas purely server-driven and forgetting that a device may already be executing when the TTL fires — thestate_sourcefield exists precisely to handle that conflict