All Products
Search
Document Center

ApsaraMQ for MQTT:FAQ about client connections

Last Updated:Mar 11, 2026

Common questions about connecting MQTT clients to ApsaraMQ for MQTT, including authentication, SDK setup, error troubleshooting, and connection management.

Authentication

What is the difference between one-way and mutual authentication?

One-way authenticationMutual authentication
What it verifiesClient verifies the broker's identityBoth client and broker verify each other's identity
Certificates neededServer certificate only (pre-installed)Server certificate + device certificate
Use caseEncrypted transmission is sufficientDevice identity verification is also required

With one-way authentication, the device checks the server certificate to confirm the broker's identity, then encrypted transmission begins. Alibaba Cloud provides a server certificate signed by GlobalSign -- the same root certificate authority (CA) that signs for aliyun.com. This root certificate is pre-installed in most operating systems, browsers, and programming language runtimes, so devices can trust the MQTT broker certificate without extra configuration.

Mutual authentication adds one more step: the broker also verifies a certificate installed on the device. Choose mutual authentication when you need to confirm device identity in addition to encrypting the connection.

How do I configure mutual authentication?

Configure the CA certificate, server certificate, and device certificate in order. For the full procedure, see Certificate management.

Configuration details:

  • Server certificate: You do not need to specify the CN field. Make sure the alt_names in server.crt.cfg include *.mqtt.aliyuncs.com.

  • Device certificate: Do not modify the CN field in the certificate file.

When can I use a proxy domain name to access MQTT?

This depends on your authentication mode:

  • One-way authentication (no TLS): Connect directly through the proxy domain name.

  • Mutual authentication: TLS connections through the proxy domain name are supported, but the proxy domain name must have a valid ICP filing.

MQTT does not support direct IPv6 connections. To connect from an IPv6-only environment, route IPv6 traffic through a proxy server to an IPv4 domain name that resolves to the MQTT service endpoint.

Endpoints

What is the difference between device SDK and cloud SDK endpoints?

ApsaraMQ for MQTT uses different endpoint formats for device-side and cloud-side SDKs:

Device SDK endpoints

Access typeFormat
Public{MQTT instance ID}.mqtt.aliyuncs.com
VPC{MQTT instance ID}-internal-vpc.mqtt.aliyuncs.com

Cloud SDK endpoints

Access typeFormat
Public{MQTT instance ID}-server-internet.mqtt.aliyuncs.com
VPC{MQTT instance ID}-server-internal.mqtt.aliyuncs.com

How do I connect to a VPC endpoint?

Any ECS instance in the same region can connect to the VPC endpoint over the private network. The ECS instance does not need to be under the same Alibaba Cloud account as your ApsaraMQ for MQTT instance.

SDK setup

How do I install the MQTT .NET SDK?

The current version requires RabbitMQ Client 6.5.0. Earlier or later versions may cause compatibility issues. For details, see Version Guide.

Search for and install the package at: https://www.nuget.org/packages.

For connection and authentication examples, see Sample code.

How do I fix errors when sending point-to-point messages with C# .NET?

Download the M2Mqtt package from https://www.nuget.org/packages/M2Mqtt.

For implementation details, see Point-to-point message sending and receiving (MQTT).

How do I use an MQTT client library in PHP?

Use the php-mqtt/client library. Run composer install in the directory that contains src, then start the sample programs:

php src/MqttConsumer.php
php src/MqttProducer.php

How do I fix errors when using an MQTT client library on Android?

Version 1.1.1 of org.eclipse.paho:org.eclipse.paho.client.mqttv3 does not support Android SDK 33 or later. Switch to the hannesa2/paho.mqtt.android library, which supports Android SDK 33.

ApsaraMQ for MQTT is compatible with the open-source MQTT protocol. Third-party SDKs may have their own compatibility issues. Use the libraries listed above for development.

Connection errors

Android demo reports "connection failed"

The endpoint format is likely incorrect. Specify the endpoint in one of these formats:

  • tcp://<Endpoint>:1883

  • tls://<Endpoint>:8883

"Too many publishes in progress"

The publish TPS (transactions per second) for the device is too high. Raise the value of mqttConnectOptions.setMaxInflight() to allow more concurrent in-flight messages per client.

"invalid param" -- client keeps disconnecting and reconnecting

The broker rejected the connection because the message body exceeded the size limit. In ApsaraMQ for MQTT, each message body cannot exceed 64 KB.

"valid owner failed" on connect

Check the following:

  1. Verify the instance name is correct.

  2. Confirm that the group and topic exist in the console and that their names are spelled correctly.

  3. Make sure the group and topic belong to the selected instance.

"connection reset by peer"

Duplicate Client ID values cause clients to kick each other off. When the server closes one connection and the displaced client continues sending data over the TCP socket, the peer responds with an RST packet.

Make sure each Client ID is globally unique. For naming rules, see Client limits.

Client connects, but the consumer disconnects immediately after subscribing

The topic settings or naming format is incorrect. Check your parent topic and subtopic configuration:

  • Parent topic: A level-1 topic. Create it in the ApsaraMQ for MQTT console or the ApsaraMQ for RocketMQ console before use.

  • Subtopic: A level-2 or level-3 topic under a parent topic. You do not need to create subtopics in the console -- specify them directly in code.

Subtopic naming format: <Parent topic name>/<Level-2 topic name>/<Level-3 topic name>

Example: SendMessage/demo/producer

Important

The combined length of the parent topic and all subtopics cannot exceed 64 characters. Exceeding this limit causes a client exception.

Connection management

Why is the first message delayed after connecting?

After the connectComplete callback fires, the first message may take about two seconds to arrive. The client needs this time to complete initialization and set up subscriptions. This behavior is expected.

How does heartbeat detection work?

After the client sends a heartbeat packet, the broker starts a timer. If the broker does not receive another heartbeat within approximately 1.5 times the heartbeat interval, it closes the connection. Each heartbeat received during this window resets the timer.

How do I set the heartbeat timeout?

Use the MqttConnectOptions class. The default heartbeat interval is 90 seconds.

Before running the following sample code, configure environment variables for your access credentials. For details, see Configure access credentials. The environment variables for the AccessKey ID and AccessKey secret are MQTT_AK_ENV and MQTT_SK_ENV.

Examples

String clientId = mqttTools.getClientId();
mqttConnectOptions = new MqttConnectOptions();
// Obtain AccessKey credentials from environment variables to avoid
// hardcoding sensitive information in your source code.
// We recommend using a RAM user instead of an Alibaba Cloud account
// for API calls and routine O&M.
mqttConnectOptions.setUserName("Signature|" + System.getenv("MQTT_AK_ENV") + "|" + instanceId);
mqttConnectOptions.setPassword(mqttTools.macSignature(clientId).toCharArray());
mqttConnectOptions.setCleanSession(true);
// Heartbeat interval in seconds. Default: 90
mqttConnectOptions.setKeepAliveInterval(90);
mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setMqttVersion(MQTT_VERSION_3_1_1);
mqttConnectOptions.setConnectionTimeout(5000);
mqttClient = new MqttClient("tcp://" + endPoint + ":1883", clientId, memoryPersistence);
mqttClient.setTimeToWait(5000);
mqttClient.setCallback(this.getMqttCallbackExtended());
mqttClient.connect(mqttConnectOptions);

Why does the connection drop unexpectedly?

Two common causes:

  • Device shutdown or network loss: Any interruption to network connectivity drops the MQTT session.

  • Expired token: With token-based authentication, the client disconnects when the token expires. If the client cannot obtain a new token before retrying, the reconnection fails as well.

Why does the subscription count in the console seem too high?

If cleanSession is set to false, subscriptions persist even after the client disconnects. To automatically clear offline client subscriptions, use the subscription cleanup feature.

Automatic reconnection

Enable automatic reconnection (Java SDK)

Set autoReconnect to true:

mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(true);

When the connectComplete callback is invoked, the connection or reconnection has succeeded.

Important

A reconnected session is a new connection. Subscriptions and pending operations from the previous connection no longer apply. Resubscribe to your topics inside the connectComplete callback:

mqttClient.setCallback(new MqttCallbackExtended() {
    @Override
    public void connectComplete(boolean reconnect, String serverURI) {
        // Resubscribe after each connection or reconnection
        System.out.println("connect success");
        executorService.submit(() -> {
            try {
                final String[] topicFilter = {mq4IotTopic};
                final int[] qos = {qosLevel};
                mqttClient.subscribe(topicFilter, qos);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public void connectionLost(Throwable throwable) {
        throwable.printStackTrace();
    }

    @Override
    public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
        // Process incoming messages here.
        // Do not throw exceptions from this callback.
        // Complete processing within the broker's timeout period.
        // Handle duplicate messages if using reliable transmission mode.
        // For timeout details, see Limits.
        System.out.println(
            "receive msg from topic " + s + " , body is " + new String(mqttMessage.getPayload()));
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        System.out.println("send msg succeed topic is : " + iMqttDeliveryToken.getTopics()[0]);
    }
});

Manage reconnection manually

Set autoReconnect to false:

mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(false);

When the connection drops, shut down the existing connection and create a new one. The ApsaraMQ for MQTT client does not reconnect automatically in this mode.