Kar
Kar

Reputation: 6365

Is message order preserved in MQTT messages?

I wonder if the message sent order is preserved. That is, when a publisher sends a sequence of messages, is each subscriber guaranteed to receive the same sequence as the publisher had sent it? For both clean and persistent sessions?

Upvotes: 39

Views: 22788

Answers (2)

abhiarora
abhiarora

Reputation: 10450

when a publisher sends a sequence of messages, is each subscriber guaranteed to receive the same sequence as the publisher had sent it?

This question has already been answered and well accepted but I see an issue with the following statement in the accepted answer.

QoS 2 messages will be delivered in order

As per the documentation, it is mentioned the sequence of packets PUBLISH,PUBREC, PUBREL, PUBCOMP will be maintained per topic across QOS 2 level messages. However, a subscriber can still receive in different order than published by publisher (possible but rare). The same logic is also applicable for QOS 1.

Let's see how:

  1. PUBLISH packet has been send by broker for message m1.

  2. PUBLISH packet has been send by broker for message m2.

  3. PUBREC packet has been send by subscriber for message m1.

  4. PUBREC packet has been send by subscriber for message m2.

  5. PUBREL packet has been send by broker for message m1. But it got dropped.

  6. PUBREL packet has been send by broker for message m2.

  7. PUBCOMP packet has been send by subscriber for message m2.

  8. Timeout for PUBREL packet at the broker has occurred for message m1. Broker will retry for message m1.

  9. Broker re-transmits PUBREL packet for message m1.

  10. PUBCOMP packet has been send by subscriber for message m1.

By above sequence, there is an possibility of the message m2 being processed first at the receiver. However, m1 was published before m2.

See this answer for further details.

enter image description here

Picture taken from u-blox.

Upvotes: 8

knolleary
knolleary

Reputation: 10117

A summary of the message ordering capabilities in MQTT 3.1.1 can be found in the specification itself here.

In summary:

  • no guarantees are made about the relative ordering of messages published with different QoS values. (for example, QoS 0 can over take QoS 2 for example as it involves a single packet rather than the 4 packets of the latter).
  • QoS 0 messages will be delivered in order (albeit messages may get lost)
  • QoS 2 messages will be delivered in order
  • QoS 1 allows for message duplicates - it is possible a duplicate will arrive after the first instance of the next message that was published.

QoS 1 ordering can be guaranteed if the client/broker only allow a single message inflight at any time.

Upvotes: 60

Related Questions