Your MQTT Command Was Published Successfully. But Did the Device Actually Execute It?
Imagine managing an IoT fleet with hundreds or thousands of connected devices.
An operator opens a dashboard, selects a device, and clicks Restart Device.
The backend publishes an MQTT message. The broker accepts it. The publishing function returns successfully.
The dashboard immediately displays:
Command successful.
But is the device actually restarted?
Not necessarily.
The device might be offline. It might receive the message but fail during execution. It might execute the command but lose its acknowledgment before the backend receives it.
There is an important distinction here:
Successfully publishing an MQTT message does not mean successfully executing a device command.
This distinction becomes critical when building production IoT platforms where remote commands control hardware, update configurations, change operating modes, or trigger physical operations.
In this article, we'll explore how to design a reliable device command workflow using MQTT, Python, FastAPI, PostgreSQL, and application-level acknowledgments.
1. MQTT Publish Success Is Not Execution Success
MQTT is a lightweight messaging protocol designed for communication between devices and messaging infrastructure.
It provides different Quality of Service (QoS) levels:
- QoS 0: At most once delivery.
- QoS 1: At least once delivery.
- QoS 2: Exactly once delivery within the MQTT protocol exchange.
These delivery guarantees are useful, but they should not be confused with application-level execution guarantees.
Consider this workflow:
Backend
|
| Publish RESTART command
v
MQTT Broker
|
| Message delivered
v
IoT Device
|
| Execute restart
v
Device Reboots
Now introduce a failure.
The device executes the restart command, but its acknowledgment never reaches the backend.
What does the backend know?
It knows that the message was published. It may not even know whether the device received it. It certainly cannot conclude that the operation completed successfully.
There are three separate events:
| Event |
What it actually means |
| Message published |
The publisher successfully completed its MQTT publishing operation |
| Message received |
The device application received the command |
| Command executed |
The device completed the requested operation |
These events must be tracked separately.
For example, a successful MQTT publish acknowledgment at QoS 1 confirms the broker's receipt according to the protocol. It does not confirm that the device application received or executed the command.
This is why a production command system needs an application-level acknowledgment.
2. Designing a Device Command Lifecycle
Instead of maintaining a simple Boolean field such as success, I prefer representing commands through explicit lifecycle states.
A possible state model is:
PENDING
|
v
PUBLISHED
|
v
RECEIVED
|
v
EXECUTING
/ \
v v
SUCCEEDED FAILED
Other possible outcomes:
PUBLISHED ---> EXPIRED
EXECUTING ---> UNKNOWN
Each state communicates something different.
| State |
Meaning |
| PENDING |
Command is saved and waiting for publication |
| PUBLISHED |
Publishing operation completed successfully |
| RECEIVED |
Device application acknowledged receipt |
| EXECUTING |
Device started processing the command |
| SUCCEEDED |
Device reported successful execution |
| FAILED |
Device reported an execution failure |
| EXPIRED |
Command exceeded its allowed lifetime |
| UNKNOWN |
Execution outcome cannot currently be determined |
The UNKNOWN state deserves special attention.
Suppose a device performs a restart and loses power before sending its final acknowledgment.
The backend cannot safely assume that the command failed. The operation may have completed.
Similarly, it cannot safely assume that the operation succeeded.
An explicit unknown outcome is more honest than incorrectly displaying success or failure.
Example command record
A command should be stored independently of the MQTT publishing operation.
A simplified PostgreSQL schema could look like this:
CREATE TABLE device_commands (
command_id UUID PRIMARY KEY,
device_id VARCHAR(100) NOT NULL,
action VARCHAR(100) NOT NULL,
payload JSONB NOT NULL,
status VARCHAR(30) NOT NULL DEFAULT 'PENDING',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
published_at TIMESTAMPTZ,
received_at TIMESTAMPTZ,
completed_at TIMESTAMPTZ,
expires_at TIMESTAMPTZ NOT NULL,
result JSONB
);
Now every command has an identity, a destination, a lifecycle, and a record of its outcome.
This also gives us something extremely useful during production debugging: a history of what the backend requested and what the device reported.
3. Building the Command Backend With FastAPI and MQTT
Let's look at a simplified implementation.
The API should not directly treat publishing as the completion of the command.
Its first responsibility is to persist the command.
Creating a command
from uuid import uuid4
from datetime import datetime, timedelta, timezone
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class CommandRequest(BaseModel):
device_id: str
action: str
payload: dict = {}
@app.post("/devices/commands")
async def create_command(request: CommandRequest):
command_id = str(uuid4())
command = {
"command_id": command_id,
"device_id": request.device_id,
"action": request.action,
"payload": request.payload,
"status": "PENDING",
"created_at": datetime.now(timezone.utc),
"expires_at": datetime.now(timezone.utc)
+ timedelta(minutes=5)
}
# Persist command in PostgreSQL.
# Production implementation should also create
# an outbox event in the same transaction.
return {
"command_id": command_id,
"status": "PENDING",
"message": "Command accepted for processing"
}
The important part is that the API returns PENDING, not SUCCEEDED.
The API has accepted the request. The actual device operation is still pending.
In a complete implementation, the command record and its outbox event should be inserted inside one database transaction.
Publishing the command
A background worker can read pending outbox events and publish them to MQTT.
A command topic might follow this convention:
devices/{device_id}/commands
For example:
devices/device-104/commands
The message could contain:
{
"command_id": "cmd-7821",
"action": "RESTART",
"payload": {},
"expires_at": "2026-12-06T10:30:00Z"
}
The publisher should use an appropriate QoS level and wait for the MQTT library's publish completion acknowledgment.
Conceptually:
async def publish_command(mqtt_client, device_id, message):
topic = f"devices/{device_id}/commands"
info = mqtt_client.publish(
topic,
json.dumps(message),
qos=1
)
await wait_for_publish_completion(info)
# Update publication state only after the
# publishing operation completes successfully.
The exact waiting mechanism depends on the MQTT client library and whether it uses synchronous or asynchronous callbacks.
Also, a publisher should not assume that a successful local method call means the broker has acknowledged the message.
For QoS 1, wait for the corresponding publish acknowledgment.
After publication, update the command's publication metadata.
The command should remain incomplete until the device reports its application-level result.
4. Making Device Commands Safe to Retry
One of the most dangerous situations in distributed systems occurs when a command is executed but the acknowledgment is lost.
Consider this sequence:
Backend Device
| |
|------ RESTART ------>|
| |
| Executes
| restart
| |
|<--- ACK LOST --------X
| |
| |
|---- RETRY ---------->|
| |
| Receives same
| command again
If the device executes every received message without checking its identity, the same operation may happen multiple times.
This is why commands should have unique IDs.
The device should maintain a record of previously processed command IDs.
A simplified example:
def process_command(command):
command_id = command["command_id"]
if already_processed(command_id):
return get_previous_result(command_id)
save_command_status(
command_id,
"EXECUTING"
)
try:
result = execute_action(command)
save_command_result(
command_id,
status="SUCCEEDED",
result=result
)
return {
"command_id": command_id,
"status": "SUCCEEDED",
"result": result
}
except Exception as exc:
save_command_result(
command_id,
status="FAILED",
result={"error": str(exc)}
)
return {
"command_id": command_id,
"status": "FAILED"
}
This is illustrative pseudocode. The production implementation needs a durable device-side command store and carefully defined behavior for commands left in EXECUTING after a crash.
There is another important detail: checking the command ID and recording its result must be coordinated so concurrent duplicate deliveries cannot both execute the operation.
A database uniqueness constraint or atomic insert can help enforce this.
However, duplicate detection alone does not make every physical operation exactly once.
For example, if a device controls a motor and crashes between performing the physical action and persisting the result, the backend may still be unable to determine whether the action happened.
For non-idempotent operations, use device-specific reconciliation, operation-state checks, or compensating behavior where possible.
Idempotency makes retries safer, but it does not magically eliminate uncertainty around physical side effects.
5. Handling Lost Acknowledgments With a Transactional Outbox
There is another failure scenario on the backend.
Suppose FastAPI performs these two operations:
- Save a command in PostgreSQL.
- Publish the command to MQTT.
What happens if the database transaction succeeds but the application crashes before publishing?
The command exists in the database, but the device never receives it.
Reversing the order creates the opposite problem: the message might be published successfully, but the database transaction could fail.
This is a dual-write problem.
A useful architectural pattern is the Transactional Outbox.
Instead of separately saving the command and publishing it, save both the command and an outbox event in the same database transaction.
FastAPI
|
v
Database Transaction
/ \
v v
Device Command Outbox Event
| |
+-----+------+
|
Transaction
Commit
|
v
Background Worker
|
v
MQTT Broker
|
v
Device
A simplified outbox table:
CREATE TABLE command_outbox (
event_id UUID PRIMARY KEY,
command_id UUID NOT NULL,
topic TEXT NOT NULL,
payload JSONB NOT NULL,
published_at TIMESTAMPTZ,
attempts INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
The command and its outbox event are inserted together.
A background worker then:
- Fetches unpublished events.
- Publishes them to MQTT.
- Waits for the appropriate broker acknowledgment.
- Marks the event as published.
- Retries events that remain unpublished.
If the worker crashes after publishing but before marking the event as published, the event may be published again.
That is expected.
The transactional outbox generally provides reliable, at-least-once publication when implemented with durable retries and recovery. It does not provide exactly-once delivery to the device application.
That is why the device still needs command-ID-based duplicate handling.
For multiple workers, use a safe claiming strategy such as PostgreSQL FOR UPDATE SKIP LOCKED, or another durable work-claiming mechanism. Avoid having every worker process the same unpublished rows simultaneously.
6. Showing the Truth in the Dashboard
A dashboard should reflect what the backend actually knows.
Consider two possible implementations.
Incorrect approach:
await mqtt_publish(command)
return {
"status": "SUCCESS"
}
This tells the user the device operation succeeded even though the backend only knows that publishing completed.
Better approach:
await mqtt_publish(command)
return {
"command_id": command_id,
"status": "PUBLISHED",
"message": "Command published. Awaiting device confirmation."
}
The dashboard can then display the lifecycle:
| Status |
Dashboard message |
| PENDING |
Command queued |
| PUBLISHED |
Command sent; awaiting device |
| RECEIVED |
Device acknowledged receipt |
| EXECUTING |
Device is processing the command |
| SUCCEEDED |
Device reported successful execution |
| FAILED |
Device reported execution failure |
| EXPIRED |
Command expired before completion |
| UNKNOWN |
Execution outcome could not be confirmed |
A timeout should not automatically mean execution failed.
For example, if the device is expected to respond within 30 seconds and does not, the backend might transition the command to UNKNOWN or TIMED_OUT_AWAITING_RECONCILIATION, depending on the system's state model.
The backend can then check device state, request a status report, or wait for a late acknowledgment.
For a restart operation, the device might reconnect and report its current boot ID or uptime. This can provide additional evidence that the requested restart occurred.
For configuration changes, the backend might compare the device's reported configuration version with the requested version.
This is a much stronger way to verify outcomes than simply trusting a message acknowledgment.
Final Thoughts
MQTT is an excellent communication protocol for IoT systems, but reliable device command execution requires more than publishing messages.
A production-ready command workflow needs:
- Persistent command records.
- Explicit lifecycle states.
- Application-level acknowledgments.
- Unique command IDs.
- Device-side duplicate handling.
- Reliable publication through an outbox.
- Retry and expiration policies.
- Reconciliation for ambiguous outcomes.
Most importantly, the backend must distinguish between what it requested, what the broker accepted, what the device received, and what the device actually completed.
There is no universal exactly-once guarantee across a database, MQTT broker, network, and physical device.
The goal is to design a system that handles retries, failures, duplicate messages, and uncertain outcomes without misleading operators or repeating dangerous operations.
A green status indicator should represent a verified device outcome—not simply a successful MQTT publish.
That is the difference between an MQTT integration and a reliable IoT command-management system.
What approach do you use to track remote device commands: MQTT acknowledgments alone, application-level acknowledgments, or a complete command lifecycle with reconciliation?
#MQTT #IoT #Python #FastAPI #DistributedSystems #SoftwareArchitecture #PostgreSQL #BackendEngineering #MessageQueues #SystemDesign #CSharpCorner
Join the conversation! Your thoughts help the community grow.