AWS IoT Core Does Not Guarantee Message Order, but You Need It
We have a large fleet of devices in the field. All of them connect to the cloud over MQTT through AWS IoT Core and send events. The events go into processing, which updates the device state and notifies clients. The setup is so standard that it seems nothing in it could break.
It breaks in exactly one place: message order.
AWS IoT Core doesn’t guarantee that a device’s messages are processed in the order the device sent them, and an Amazon SQS FIFO queue fed by AWS Lambda doesn’t restore that order. At Gecko Dynamics, we restore it ourselves: a per-device sequence number, a short wait for the missing predecessor, delayed returns to the queue, and a forced state synchronization as a last resort.
Event order is the device state
Devices don’t send us their full state. They send events: an alarm went off, the alarm was cleared, the configuration changed, and so on. From this chain of events, the cloud builds the current picture, and in normal operation it can rebuild that picture from scratch without polling the device.
We didn’t choose this out of love for event sourcing. It came from constraints. The first one is the hardware: devices have little memory, and attaching a state snapshot to every event would be an unaffordable luxury.
The second constraint is traffic. And traffic here isn’t just bytes; it’s money. The devices go online over cellular networks, and fleet data plans usually give each device a very small data allowance. One extra megabyte from a single device is nothing, but across the fleet it’s multiplied by the number of devices, and the connectivity bill grows with the fleet. That’s why the protocol was lean from the start: a device sends short events instead of pushing state snapshots over the network. For the same reason, the cloud doesn’t poll the fleet for an up-to-date picture: that would be the same traffic, plus extra time and extra synchronization. So the devices send events and nothing else.
That’s what makes a mistake expensive. If an “alarm” event and an “alarm cleared” event are processed in reverse order, the device stays in an alarm state in the system, even though there is no alarm. The client sees a false state. In some scenarios that’s merely ugly, and in others it’s completely unacceptable.
What matters is the order within a single device. How events from different devices interleave doesn’t matter at all.
AWS IoT Core message order: the documentation not everyone reads
AWS IoT Core rules (the rules engine) fire asynchronously and with some delay. As long as a device’s messages are spaced out in time (say, ten seconds or so apart), in practice they are processed in the order they were sent. But if a device sends a burst of messages back to back, they may well be processed in a different order.
The AWS IoT Core documentation for the SQS rule action says it plainly: “Because the rules engine is a fully distributed service, there is no guarantee of message order when the SQS action is triggered.” The MQTT message broker makes no promise either: its documented differences from the MQTT specification include this one: “The message broker doesn’t guarantee the order in which messages and ACK are received.”
And yet it comes as a surprise to many: they assume that if there is a broker and a queue, ordering is taken care of. It isn’t.
Why SQS FIFO and Lambda don’t restore message order
The first idea for restoring order is to use an Amazon SQS FIFO queue. But the AWS IoT Core SQS rule action can only write to a standard Amazon SQS queue: it doesn’t support FIFO queues. To get messages into a FIFO queue, you need an intermediate layer, usually an AWS Lambda function that receives each message and forwards it.
And here is the trap. By this point the order has already been lost at the rules level. Lambda doesn’t restore it. It shuffles the messages even more: the rules invoke it asynchronously, a burst of messages spins up several parallel instances, and messages land in the FIFO queue in whatever order those instances finish. So we pay for FIFO and still fill it with a jumble. Limiting concurrency to a single instance doesn’t help either: the messages reach Lambda already shuffled, and a single instance just turns the intermediate layer into a bottleneck.
On top of that, FIFO has an unpleasant side effect: while we are processing at least one message from a message group, the queue won’t return any new messages from that group. If we group by device and a message lands in the FIFO queue ahead of its predecessor, the predecessor gets stuck behind it, and there is no way to wait for it without processing the current message out of order. In other words, we can’t hold a message on our side and wait for its predecessor. The tool that was supposed to give us ordering takes away our ability to restore it.
Device timestamps can’t be trusted: use a sequence number
The next idea is to sort by device time. Another miss. The devices have no clock that keeps running without power. Time is counted in ticks, and after a reboot a device simply doesn’t know what time it is until it connects and gets the time from outside. Such a timestamp is no source of truth for sorting.
That’s why the protocol has a sequence field: a per-device event counter. That one can be trusted.
Why not just recompute device state from the message history?
We store all events anyway. So why not write them as they arrive and compute the state with a query over the history?
Because it doesn’t scale. There is an enormous number of events. The history table is for looking back at what happened: occasional analytical queries and incident investigations. Running a recomputation over it for every incoming message would put a constant load on the heaviest table in the system. You can invest in the database and speed it up, but that has a limit: if the fleet doubles, the cluster has to grow along with it. And we want to keep the history longer, not trim it for the sake of performance.
So the order has to be restored on the fly, before anything is written.
How we restore per-device message order
The service reads a standard (non-FIFO) SQS queue with several threads. A single request returns up to ten messages, so several dozen messages are in flight at any moment. The whole chain (update the state, notify clients, run the related logic) has a budget of tens of milliseconds. We have to stay within it, so the ordering mechanism must be cheap.
The logic is simple:
receive a message
if this message is already in the database:
it is a duplicate: delete it from the queue without processing
else if its sequence number is zero:
the device has reset: handle it separately
else if the previous sequence for this device is already in the database:
process it
else:
hold it in the buffer and wait for the previous one
if it arrived:
process it
if it did not arrive within the wait window:
return it to the queue with a delay and an attempt counter A few important details.
Duplicates are dropped first. Devices publish events as QoS 1 messages, which means at-least-once delivery: the same message can arrive twice. A standard SQS queue gives the same guarantee. Processing an old event again would return the device to a state it has already left, and we would get the same false alarm. So we first check whether this message is already in the database. The check looks at more than the sequence number: every message carries attributes that identify it uniquely. And the check always runs on hot data. A duplicate never lags far behind the original: nothing in the chain redelivers a month-old message. So the lookup is limited to a reasonable time window, never scans partitions it doesn’t need, and finds recent rows that are already in the database buffer. Such a check is practically free. If the message is already there, we simply delete it. Even if a duplicate does slip past this check while several instances process messages in parallel (which is extremely unlikely), the database itself stops it with a unique key on those identifying attributes.
Sequence number zero means a reset. A message with sequence number zero tells us that the device has restarted, so it is handled separately: it isn’t mistaken for a duplicate of an earlier reset, and it doesn’t wait for a predecessor.
Coordination goes through the database, not process memory. The “is the previous sequence there?” check is a database query, not a lookup in local state. That’s why the mechanism works correctly with several service instances. And it isn’t a heavy query over the history: we look only at the device’s latest event, which holds its latest sequence number. That’s the freshest, just-inserted data, and it is practically always in the database buffer (the database is tuned to keep recent data hot), so access is almost instant, with no disk reads.
A message can’t be held forever. The queue has a visibility timeout, and if you hit it, you get duplicates and trouble out of nowhere. So the wait window in the buffer was tuned by experiment: short enough not to block the service for long, and long enough to give a real out-of-order situation a chance to resolve itself.
Messages go back to the queue with a delay. The queue doesn’t guarantee order, but a small delay on return increases the chance that the message comes back after its predecessors rather than before them.
Every return is counted. The message carries an attempt counter. As long as the counter stays within the normal range, this is routine reordering.
Doomsday: forced synchronization
Now the unpleasant part. You can write the code as carefully as you like, but a device’s message chain can genuinely break. A device resets and its counter goes back to zero. Or a device stays offline long enough to collect more events than fit into its EEPROM, and some of them have to be sacrificed. Either way, the previous sequence will never arrive, and you could wait for it forever.
That’s what the last line of defense is for. When a message’s attempt counter exceeds the threshold, we record the fact and wait briefly to collect other such messages from the same device, if there are any. Then we start a forced synchronization: we pull the device’s full current state. From then on we rely not on the broken message chain but on the device’s actual current state, and all subsequent events build on that.
This is the doomsday tool. It triggers very rarely, mostly because of device resets.
How the reordering behaves in production
In normal operation a message barely waits in the buffer. If a device sends a burst of messages at once and they get shuffled on the way through the MQTT broker, rule execution, and the SQS queue, each one waits only for its predecessor, and processing a single event takes 5 to 30 ms depending on its type. So once a burst of five messages reaches the service, it falls into order in roughly 25 to 150 ms, which is a good result for near-real-time IoT systems.
The second scenario is more interesting: scheduled maintenance. The processing service may be down for a short time. That’s rare, but it happens in every project. During that time tens of thousands of messages pile up in the queue, and on startup they all arrive at once and in random order. Some messages go through immediately, some sit in the buffer for a while, and a few make several rounds through the queue, especially if a device’s latest message arrived first.
In practice, the whole backlog is cleared in a few minutes, including all the retries and reordering. Seamlessly.
Short answers
Does AWS IoT Core guarantee message order?
No. Neither the MQTT message broker nor the rules engine guarantees it, and a burst of messages sent back to back is most likely to arrive out of order.
Can an AWS IoT rule write to an Amazon SQS FIFO queue?
No. The SQS rule action supports only standard queues. Putting AWS Lambda in between doesn’t help: the order is already lost at the rules level, and parallel invocations shuffle it further.
Can device timestamps be used to order events?
Sometimes, if the device has a real-time clock (RTC) that keeps running without power. Even then, the RTC itself can lose the correct time, and without regular synchronization every clock drifts. Without an RTC, a rebooted device doesn’t know the time until it syncs. And even with a correct clock, events sent back to back can end up with identical timestamps. A per-device sequence number has none of these problems.
How do you handle duplicates from MQTT QoS 1 and SQS?
QoS 1 and standard SQS queues both deliver at least once. Every message is checked against the database first. A duplicate never arrives long after the original, so the check only touches recent, hot data and is practically free. A unique key on the message’s identifying attributes backs up the check.
What happens when a device resets or loses messages?
A message with sequence number zero marks a reset and is handled separately. If messages are lost for good, a forced synchronization pulls the device’s full current state.
Conclusion
Read the documentation. Not by skimming, but with a specific question in mind: what does the service guarantee, and what doesn’t it? The absence of an ordering guarantee isn’t a bug or an exotic edge case; it’s documented behavior. Finding out about it in production hurts.
Don’t settle for the first solution you find. The “Lambda plus FIFO queue” combination looks like an answer, but in reality it adds another source of asynchrony and takes away your ability to order the messages yourself. Before adopting it, ask what guarantees each link in the chain gives and what happens where the links meet.
If order matters, implement it yourself. A counter in the protocol, a buffer that waits for the predecessor, delayed returns to the queue, an attempt counter, and forced synchronization as an emergency valve. These are simple mechanisms: they fit into a hundred or two lines of code and a tight time budget. No grand architecture is required.
And a final word on complexity. A lot of code is written with AI coding assistants these days, and they have a persistent habit of guarding against situations that can’t happen according to the protocol. Technically, that may be correct, but in practice such checks scatter the logic, hurt readability, complicate maintenance, and cost performance. If data arrives that shouldn’t exist, further processing makes no sense anyway. It’s better to log it loudly enough to trigger an alert, put the message into a dead-letter queue (DLQ), and investigate what happened than to heroically try to process garbage.
A simple, predictable architecture wins not because it’s prettier. It wins because a new person on the team can understand it at a glance from the code, not from a dozen pages of documentation.
At Gecko Dynamics, we build IoT systems like this for our clients. To see how we can help with your project, visit our IoT & Big Data page.