Skip to main content

Publish to MQTT

info

MQTT publishing sends TDengine TMQ subscription data to an MQTT Broker for downstream subscribers. Verification must confirm that subscribers receive messages and parse business fields. Broker connectivity or healthy task status does not mean verification is complete. Start the subscription client before writing source data.

Where to operate: run taosx run on a command-line host that can reach source TDengine and the target MQTT Broker. Prepare the source in the taosExplorer Data Browser or taos CLI and verify downstream in an MQTT subscription client.

Data flows TDengine TMQ → taosX → MQTT Broker. To ingest data from MQTT, follow MQTT.

1. Prepare Source Data and Downstream Subscription​

In an isolated test environment, have an authorized TDengine TSDB administrator run the following SQL in the taosExplorer Data Browser or taos CLI. If the database name exists, use a new name and update subsequent topics and queries consistently. Do not overwrite business databases.

CREATE DATABASE taosx_out_demo PRECISION 'ms' WAL_RETENTION_PERIOD 86400;
CREATE STABLE taosx_out_demo.meters (ts TIMESTAMP, value DOUBLE)
TAGS (site VARCHAR(16));
CREATE TABLE taosx_out_demo.meter_1 USING taosx_out_demo.meters TAGS ('lab');

Create source objects and topics first, then prepare consumers for the selected method. Write test data after consumers are ready. Verify historical reads of existing data separately from continuous reads after subscription. Topic creation alone does not establish successful data transfer.

Create a dedicated source topic for the publishing task in the taosExplorer Data Browser or taos CLI:

CREATE TOPIC taosx_out_mqtt AS
SELECT ts, tbname, value, site FROM taosx_out_demo.meters;

The source account needs subscription permissions. The target MQTT account needs publish permissions on a dedicated test Topic, and the verification account needs subscribe permissions. Obtain the address, protocol version, TLS, and authentication requirements from the Broker administrator.

warning

Use an administrator-approved isolated TCP Broker for the first exercise. If the production Broker requires TLS, confirm the delivered package's actual publishing capabilities and deployment method with technical support first. Do not treat MQTT read-side ca, cert, and cert_key as effective publish-side settings, or disable production security requirements to complete the exercise.

Start the subscription client first. For example, with Mosquitto clients installed, run on a verification host that can reach the Broker:

mosquitto_sub -h <MQTT主机> -p 1883 -t taosx/test/meters -V mqttv5 -q 1 -v

This command demonstrates only an isolated test Broker without TLS. In production, add authentication and TLS as required by the Broker, without disabling certificate verification. Do not leave passwords in shared command records. The subscription client can run on Windows or Linux, but the corresponding tool must actually be installed.

2. Start Minimal Publishing​

Run on the taosX command-line host, substituting actual identities and addresses:

The copyable exercise commands below are only for isolated testing: source taosAdapter and MQTT Broker both run on the command execution host, the source default test account root / taosdata is unchanged, and the Broker explicitly permits unauthenticated connections. In production, use approved identities, actual addresses, and security materials. Default accounts are not a deployment requirement.

Run in Bash:

taosx run -f 'tmq+ws://root:taosdata@127.0.0.1:6041/taosx_out_mqtt?group.id=taosx_out_mqtt_demo&auto.offset.reset=earliest&timeout=never' -t 'mqtt://127.0.0.1:1883?topic=taosx/test/meters&qos=1&version=5.0&client_id=taosx-publish-demo&read_concurrency=1'

Retain outer DSN quotes, URL-encode special password characters, and follow TLS, DSNs, and Sensitive Files. 127.0.0.1 refers only to the command process's environment. In containers or WSL, it does not automatically mean the Windows host.

ParameterMeaning
Source path taosx_out_mqttTDengine topic, not an MQTT Topic.
group.idA fixed dedicated consumer group. Unintentional sharing divides source partitions among consumers.
auto.offset.reset=earliestStarting position when no committed position exists; it does not force replacement of existing group progress.
Target topicMQTT publish topic, fixed here as taosx/test/meters.
version=5.0MQTT protocol version, which must match the Broker; 3.1.1 is also supported.
client_idMQTT client identifier; avoid collisions with other online clients.
qos=1MQTT at-least-once delivery, not end-to-end exactly-once behavior.
Target read_concurrency=1Create only one publishing connection so its Client ID matches the configured value; this is not the source TMQ partition count.

If target read_concurrency is omitted, the execution environment's available parallelism determines the connection count. With concurrency above 1, each connection appends a random suffix to the configured Client ID. If the Broker authorizes full Client IDs, confirm permitted actual identifiers first. This is not ingestion-task read concurrency, and 0 must not be used. Before increasing it, check connection counts, downstream order, and business results under fixed load, not only send counts. See MQTT Publishing Parameters for defaults, units, sessions, and certificate conditions.

2.1 Check Source Subscription Scope​

To read persisted records, check source DSN experimental.snapshot.enable and source retention. earliest alone does not select all history. client.id is an optional TMQ client identifier, distinct from target MQTT client_id. See TMQ Continuous Synchronization for main snapshot, topic, start, and committed-position rules.

Explicitly set MQTT target version and client_id; topic is required. Omitted qos defaults to 0; this example explicitly uses 1. Protocol versions are 3.1.1 or 5.0. Do not use the Broker product version as the protocol version or treat MQTT 3.1 as a separate supported mode on this page.

3. Send a Source Record and Verify the Message​

Run in the source cluster's taosExplorer Data Browser or taos CLI:

INSERT INTO taosx_out_demo.meter_1 VALUES (NOW, 23.5);
SELECT ts, value, site FROM taosx_out_demo.meter_1 ORDER BY ts;

Record the actual primary timestamp and find its message in the subscription client. Data messages contain data and offset. data should contain projected fields ts, tbname, value, and site, with values 23.5, meter_1, and lab. offset contains the source database, TMQ topic, vgroup, and position. Match source-record time, not just receipt time.

Alternatively, use the MQTTX GUI client. Create a connection with the same Broker's actual host, port, protocol, and authentication, using another unique Client ID. After connecting, subscribe to taosx/test/meters, then write the source record. Check the above fields and values in received message details. Do not reuse taosX's publishing Client ID for MQTTX subscription, or the clients may disconnect one another.

The following only illustrates this record's JSON envelope. Check actual ts, vgroupId, and offset; do not expect the illustrative numbers:

{"data":{"ts":1795132800000,"tbname":"meter_1","value":23.5,"site":"lab"},"offset":{"database":"taosx_out_demo","topic":"taosx_out_mqtt","vgroupId":2,"offset":8}}
note

Write another timestamp and value to confirm continuous publishing. Broker connectivity or healthy taosX status does not replace verification that downstream receives and parses business fields. If a subscriber starts after publishing, do not assume the Broker retains all historical messages for it.

Publishing does not set Retain. Late subscribers cannot rely on retained messages for earlier records. Subscribe first, then write new-timestamp data for verification. Broker persistent sessions and Retain are different mechanisms and do not replace one another.

4. Metadata and Dynamic Topics​

To publish metadata such as schema, the source topic must contain the required metadata and the source DSN must select corresponding publishing options. This example's query topic verifies data only. Target meta_topic can be separate; if omitted, it falls back to the data Topic. Metadata and data use different message formats, which downstream must distinguish.

Dynamic Topics support variables such as source database, source topic, vgroup, and table name, but available variables differ by event. Referencing an absent variable can discard the current message. Preview actual data and metadata first. Not every projected query field is a routing variable.

Template variableAvailabilityExample
{database}, {tmq_topic}, {vgroup_id}Source context for data and metadatataosx/{database}/{tmq_topic}.
{stable}Metadata events with supertable informationDo not assume it exists in all data messages.
{table}Data with table information, or table-create/alter/drop eventsVerify regular and child tables against actual events separately.

Omitted meta_topic falls back to topic, but sharing a Topic does not unify message structures. Tasks needing source metadata require topics containing it and source options such as with.meta. with.meta.delete and with.meta.drop affect data-delete and table-drop events respectively. Define downstream handling first. Enabling switches alone does not provide complete recovery capability.

5. Troubleshooting​

SymptomNext action
Publish connection failsFrom the taosX host, check Broker network, protocol, TLS, authentication, and Topic publish ACL.
Subscriber receives no messagesFirst confirm it is running on the correct Topic, then check new source writes, source topic scope, consumer group, and taosX logs.
Client repeatedly disconnectsCheck duplicate MQTT Client IDs and expired authentication or certificates.
Connections rejected after adding concurrencyCheck read_concurrency, Broker connection limits, and authorization for actual suffixed Client IDs. Verify the single-connection example first.
Fixed Topic works but template Topic loses messagesCheck missing template variables and generated names. Return to a controlled fixed Topic first.
Downstream parsing failsCompare the data/offset envelope and actual types. Do not parse as raw SQL row text.

For other task, write, and runtime issues, see Troubleshooting by Symptom.

6. Stop and Resume​

Stop in the foreground with Ctrl+C. Retain the same source topic and consumer group when continuing and verify the original readable range and new messages. Changing starting-position parameters alone does not guarantee rereading all history.

The TMQ source for MQTT publishing uses automatic commits. Source-position advancement does not mean the Broker or business subscriber has acknowledged processing. MQTT QoS does not make these stages one transaction. After failure, check both duplicates and gaps. Downstream needs suitable business idempotency, and missing data requires a replay plan based on retained source ranges. Advanced positions alone cannot establish publishing completeness.

clean_session=false does not guarantee complete recovery either. Under MQTT 5.0 it requests a session expiry of 60 seconds, with actual behavior dependent on the Broker. With concurrency above 1, Client IDs have random suffixes; identical configured values after restart do not prove reuse of the original session. Verify recovery against source scope and downstream data. Do not bypass verification by changing consumer groups or only switching session settings.

7. Limitations​

MQTT publishing does not replace complete database backups, and downstream is not guaranteed to reconstruct every schema change automatically. Consumer groups, source WAL, Broker sessions, and downstream persistence each have boundaries that require separate planning and drills.