tencent cloud

TDMQ for MQTT

Related Agreement
Política de privacidade
Contrato de Privacidade e Seguranca de dados
DocumentaçãoTDMQ for MQTT

Reason Code

Modo Foco
Tamanho da Fonte
Última atualização: 2026-04-01 16:37:50

1. Product Overview

In the MQTT protocol, a Reason Code is a standardized numeric identifier primarily used to provide explicit and standardized status feedback for operations between MQTT clients and servers.
By including a specific Reason Code in the response packet (such as CONNACK), the receiver can precisely determine the outcome of the requested operation. For instance, it can identify whether a connection failure is due to "Invalid Username or Password" (0x86) or "Client Blocked" (0x8A). This mechanism significantly improves the transparency, diagnosability, and automated processing capabilities of the MQTT protocol.

2. Evolution from MQTT 3.1.1 to MQTT 5.0

2.1 Limitations of MQTT 3.1.1

Although the MQTT 3.1.1 protocol already includes the concept of Reason Code, its scope of application and granularity of feedback are very limited:
Limited Packet Type Support: Only CONNACK and SUBACK support Reason Codes.
Coarse-grained Feedback: CONNACK has only 5 error codes, while SUBACK has only one failure code, making it impossible to distinguish specific reasons for subscription failures (such as invalid topic format or unauthorized access).
No Feedback for Critical Operations: For operations such as PUBLISH and UNSUBSCRIBE, the protocol does not provide any feedback on success or failure. The client cannot confirm whether the operation was properly handled by the server.

2.2 MQTT 5.0 Comprehensive Enhancements

MQTT 5.0 fundamentally overhauls and expands the Reason Code mechanism, making it one of the core features of the protocol:
Clear Success/Failure Demarcation: It introduces a clear numerical convention: Reason Codes with values below 0x80 indicate success, while those equal to or above 0x80 denote failure. This differs from the intermingled success and failure codes in MQTT 3.1.1, significantly simplifying the client's decision-making logic.
Extensive Packet Support: Control packets supporting Reason Codes are significantly expanded, covering nearly all interactive processes that require responses.

3. Detailed Explanation of Key Features

3.1 Server Proactively Sending DISCONNECT Packets

In MQTT 3.1.1, the DISCONNECT packet can only be initiated by the client. When the server must disconnect due to detecting client violations (such as sending oversized packets), it can only unilaterally close the TCP connection, and the client cannot determine the specific reason for the disconnection.
MQTT 5.0 allows the server to proactively send a DISCONNECT packet to the client before closing the connection. By including a corresponding Reason Code (such as 0x95: Packet too large or 0x89: Server busy) in this packet, the server can clearly inform the client of the reason for connection termination. This provides a basis for clients to implement intelligent reconnection strategies, such as reconnecting after adjusting the packet size or delaying reconnection attempts.

3.2 Reason String: Enhancing Diagnosability

The Reason String serves as a supplement to the Reason Code, designed as a human-readable UTF-8 string for diagnostic purposes.
Although Reason Codes provide standardized error categorization, in certain scenarios, developers or Ops personnel still require more specific contextual information. For example, when the server returns 0x8F (Topic Filter invalid), the Reason String can provide detailed descriptions such as "Topic filter depth exceeds server limit of 10 levels," making problem identification extremely efficient.
Important Usage Guidelines:
Purpose: Reason String is intended solely for diagnostic purposes, such as being logged or thrown as exception information in development environments.
Parsing Prohibited: A well-designed client or server must never attempt to programmatically parse the content of the Reason String to drive its business logic. Its content depends entirely on the peer's implementation, and no stability in format or content is guaranteed.
Optionality: Reason String is an optional property. The sender may choose not to send it, and the receiver must be capable of handling its absence.

4. Usage Guidelines

def on_connect(client, userdata, flags, rc, properties=None):
"""
Connection callback function
Important parameters:
rc: ReasonCode object - automatically passed by the paho-mqtt library
Reason Code indicating the connection result
"""
# ============ Core Usage of Reason Code ============
# 1. Check the type of the ReasonCode object
print(f"\\n1️⃣ ReasonCode object type: {type(rc).__name__}")
# 2. Obtain the value of the Reason Code
rc_value = rc.value if hasattr(rc, 'value') else int(rc)
print(f"2️⃣ Reason Code value: {rc_value}")
# 3. Obtain the name of the Reason Code
rc_name = rc.getName() if hasattr(rc, 'getName') else str(rc)
print(f"3️⃣ Reason Code name: {rc_name}")
// Example output
⏳ Connecting to the MQTT server...
1️⃣ ReasonCode object type: ReasonCode
2️⃣ Reason Code value: 134
3️⃣ Reason Code name: Bad user name or password

5. MQTT 5.0 Reason Code Cheat Sheet

Here is a quick reference table of commonly used Reason Codes in MQTT 5.0 to help you quickly understand and use them.
A. Success and Normal Operations
Code (Hex/Dec)
Name
Applicable Packets
Description
0x00 (0)
Success / Normal disconnection
All response packets
Indicates that the operation is successful, or the client disconnects normally (does not trigger a Will Message).
0x01 (1)
Granted QoS 1
SUBACK
Subscription is successful, and the server grants a maximum QoS level of 1.
0x02 (2)
Granted QoS 2
SUBACK
Subscription is successful, and the server grants a maximum QoS level of 2.
0x04 (4)
Disconnect with Will Message
DISCONNECT
The client disconnects actively and requests the server to publish its Will Message.
0x18 (24)
Continue authentication
AUTH
A step in the enhanced authentication process, indicating that authentication data exchange needs to continue.
B. Client Authorization and Authentication Errors
Code (Hex/Dec)
Name
Applicable Packets
Description
0x19 (25)
Re-authenticate
AUTH
The client initiates re-authentication after connection. If re-authentication fails, the connection is closed.
0x85 (133)
Client Identifier not valid
CONNACK
Client ID is valid in format but rejected by the server (such as empty when Clean Start=0).
0x86 (134)
Bad User Name or Password
CONNACK
User name or password is incorrect, and the connection is rejected.
0x87 (135)
Not authorized
All response packets
Not authorized to perform this operation; more generic than 0x86, applicable to token authentication or publish/subscribe permission checks.
0x8A (138)
Banned
CONNACK
The client is banned (such as when IP address or Client ID is added to the blocklist).
0x8C (140)
Bad authentication method
CONNACK, DISCONNECT
The authentication method specified by the client is not supported by the server.
C. Server Status and Resource Limitations
Code (Hex/Dec)
Name
Applicable Packets
Description
0x88 (136)
Server unavailable
CONNACK
The server is temporarily unavailable (such as failure of the dependent authentication service).
0x89 (137)
Server busy
CONNACK, DISCONNECT
The server is busy. Please try again later.
0x8B (139)
Server shutting down
DISCONNECT
The server is shutting down and actively notifies the client.
0x95 (149)
Packet too large
CONNACK, DISCONNECT
The packet size exceeds the agreed-upon maximum value.
0x96 (150)
Message rate too high
DISCONNECT
The client's message sending rate is too high.
0x97 (151)
Quota exceeded
All response packets
The client's resource quota is exhausted (such as daily message limit).
0x9F (159)
Connection rate exceeded
CONNACK, DISCONNECT
The client's connection rate is too high.
D. Protocol and Packet Errors
Code (Hex/Dec)
Name
Applicable Packets
Description
0x80 (128)
Unspecified error
All response packets
Unspecified general error, used when no more specific Code is available.
0x81 (129)
Malformed Packet
CONNACK, DISCONNECT
The packet format does not comply with specifications and cannot be parsed correctly.
0x82 (130)
Protocol Error
CONNACK, DISCONNECT
The packet format is correct, but its content or behavior violates protocol specifications (such as sending two CONNECTs).
0x83 (131)
Implementation specific error
All response packets
The packet is valid but not supported by the receiver's specific implementation.
0x84 (132)
Unsupported Protocol Version
CONNACK
The server does not support the MQTT protocol version requested by the client.
0x91 (145)
Packet Identifier in use
PUBACK, PUBREC, SUBACK, UNSUBACK
The Packet Identifier (Packet ID) is being used in another in-flight QoS 1 or 2 message flow, which typically indicates a session state mismatch.
0x92 (146)
Packet Identifier not found
PUBREL, PUBCOMP
In the QoS 2 process, the receiver cannot find a Packet ID corresponding to the PUBREL or PUBCOMP packet, which typically indicates a session state mismatch.
0x99 (153)
Payload format invalid
CONNACK, PUBACK, PUBREC, DISCONNECT
The packet payload format does not match the specification declared in the Payload Format Indicator property.
0x9B (155)
QoS not supported
CONNACK, DISCONNECT
The requested QoS level is not supported by the receiver.
E. Topic and Subscription-related Errors
Code (Hex/Dec)
Name
Applicable Packets
Description
0x10 (16)
No matching subscribers
PUBACK, PUBREC
The message is received, but there are currently no subscribers matching the topic (optional server-side implementation).
0x11 (17)
No subscription existed
UNSUBACK
No matching subscription is found when unsubscribing.
0x8F (143)
Topic Filter invalid
SUBACK, DISCONNECT
The topic filter format for subscription is valid but not accepted by the server (such as excessive hierarchy depth).
0x90 (144)
Topic Name invalid
CONNACK, PUBACK...
The topic name format for publishing is valid but not accepted by the server.
0x94 (148)
Topic Alias invalid
DISCONNECT
The topic alias value in the PUBLISH packet is 0 or exceeds the maximum value agreed upon during the connection.
0x9A (154)
Retain not supported
CONNACK, DISCONNECT
The server does not support retained messages.
0x9E (158)
Shared Subscriptions not supported
SUBACK, DISCONNECT
The server does not support shared subscriptions.
0xA1 (161)
Subscription Identifiers not supported
SUBACK, DISCONNECT
The server does not support subscription identifiers, but the client used this property during subscription.
0xA2 (162)
Wildcard Subscriptions not supported
SUBACK, DISCONNECT
The server does not support wildcard subscriptions.
F. Session, Flow Control, and Cluster Management
Code (Hex/Dec)
Name
Applicable Packets
Description
0x8D (141)
Keep Alive timeout
DISCONNECT
The server actively disconnects when it does not receive any packets from the client within 1.5 times the Keep Alive interval.
0x8E (142)
Session taken over
DISCONNECT
A new connection using the same Client ID causes the current session to be taken over.
0x93 (147)
Receive Maximum exceeded
DISCONNECT
The number of unacknowledged packets with QoS > 0 from the sender exceeds the agreed-upon Receive Maximum value of the receiver.
0x98 (152)
Administrative action
DISCONNECT
The connection is closed due to administrative operations, for example, Ops personnel manually removing this connection in the background.
0x9C (156)
Use another server
CONNACK, DISCONNECT
Inform the client to temporarily switch to another server.
0x9D (157)
Server moved
CONNACK, DISCONNECT
Inform the client to permanently switch to another server.
0xA0 (160)
Maximum connect time
DISCONNECT
The connection duration exceeds the maximum value set by the server for this authorization (such as JWT expiration).

Ajuda e Suporte

Esta página foi útil?

comentários