Skip to main content

MQTT

info

MQTT ingestion reads messages from a Broker and writes them to TDengine. This page uses JSON payloads to explain connection, parsing, mapping, and ingestion verification. For binary Sparkplug B payloads, use Sparkplug B; do not decode them as JSON.

Navigation: taosExplorer → Data In → MQTT. Run SQL in taosExplorer's Data Browser or the taos CLI.

1. Prerequisites​

ItemPrerequisiteWhere to verify
BrokerActual host, port, 3.1.1 or 5.0 protocol, permitted topics, and QoSThe reading host is taosX or the selected taosX-Agent. Do not test only from the browser.
Authentication and TLSSubscription identity and CA; mutual authentication also requires a client certificate and private keyHave the source administrator approve the subscription ACL. Check certificate hostnames and validity.
Test messagesA separate topic approved for publishing and two identifiable JSON messagesFor example, taosx/test/temperature. Do not publish to production device-control topics.
Client identityUnique Client IDs for collection and test publishingDo not reuse IDs from other clients. Record the identifier actually generated by the UI.
Target clusterA separate database, supertable, and table-creation/write permissionsAn authorized TDengine TSDB administrator prepares these; actual writes use an approved identity.

This page reads an external Broker. MQTT subscriptions in which clients connect to a TDengine Bnode are a separate feature. Do not directly apply this page's QoS, authentication, or retention guarantees to it. If the Broker is a Bnode, check its documentation separately for supported behavior.

Have an authorized TDengine TSDB administrator create test objects in taosExplorer's Data Browser or the taos CLI. If an object with the same name exists, choose another name rather than overwriting a business database:

CREATE DATABASE mqtt_demo PRECISION 'ms';
CREATE STABLE mqtt_demo.temperatures (ts TIMESTAMP, temperature DOUBLE)
TAGS (device VARCHAR(32));

2. Minimal configuration​

  1. On the Data In page, click Add Data Source. Enter mqtt_temperature_demo as the name, select MQTT as the type and mqtt_demo as the target database, choose an Agent according to the deployment, and enter the Broker host and port. If a task with that name exists, choose another recognizable name and use it to find the task later.
  2. Select protocol 3.1.1 or 5.0 to match the server. Enter a separate client ID and configure the username, password, and TLS verification according to production requirements. Server-only authentication needs a CA; mutual authentication also needs a client certificate and private key.
  3. Enter taosx/test/temperature::0 as the subscription. Here ::0 specifies the topic's QoS. Start with one exact topic, not a wildcard spanning all business topics. Match message compression and encoding to the producer.
  4. Enter sample {"device":"d001","ts":1795132800000,"temperature":23.5} and select JSON parsing. Add no filters. Select supertable temperatures, child-table template t_{device}, milliseconds for time, a numeric temperature, and a device tag.
  5. After checking connectivity and previews, submit and start the task. Then have an authorized publishing client send the sample to the actual topic.

1795132800000 is 2026-11-20T00:00:00Z. If replacing it with a time within retention, update both the actual messages and the queries below.

2.1 Configure connection and subscription fields​

Enter the MQTT address and port separately under Broker Address. Click Add Broker if multiple entry points are needed. Use an address reachable by the actual reading host, not a browser-only address or full DSN.

Separate MQTT Broker address and port inputs

Expand Connection Configuration and check the protocol, client ID, Keep Alive, and Clean Session. The new form below shows protocol 3.1.1, Keep Alive 60 seconds, and Clean Session enabled. For existing tasks, use actual saved values. Keep Alive is neither a sampling interval nor a historical backfill duration. The client ID must be unique on the same Broker. Do not derive the actual ID from another version's prefix rules.

MQTT protocol, client ID, Keep Alive, and Clean Session

Expand Authentication Configuration, enter the Broker username and password, and select the source-required TLS mode. The image below has no TLS configured; this is not a production security recommendation. When TLS is required, configure the administrator-provided CA and client identity materials before checking connectivity.

MQTT username, password, and TLS mode settings

View material inputs for server-only and mutual TLS verification

Select Server Verification and provide a trusted CA to verify the server certificate. For Mutual Verification, also provide a client certificate and matching private key. Username/password credentials and certificates are different authentication materials; supply the combination required by source policy.

CA upload for MQTT server-only TLS verification

CA, client certificate, and private-key inputs for MQTT mutual TLS verification

note

When TLS Verification is Disabled, the client first tries TCP, then TLS without server-certificate verification if TCP fails. Do not interpret this as “always plaintext” or “strict certificate verification.” Explicitly provide a trusted CA for production TLS connections. For connection and certificate conditions in direct DSNs, see MQTT read parameters.

Expand Collection Configuration. Enter one exact topic and its QoS first, then select compression and encoding based on message production. Do not add shared subscriptions, topic extraction, and filters at once, as that makes the first failure harder to diagnose.

MQTT subscription topics, QoS, topic parsing, compression, and character encoding

2.2 Complete message parsing and target mapping​

Continue with mqtt_demo.temperatures and the temperature JSON above.

  1. Select json under Payload Transformation and preview it. Confirm that device is a string and ts and temperature are numeric. If rule blocks are present, keep one block for the single structure with match expression true. This example adds no extraction, splitting, or filtering.
  2. In the selected target database, select temperatures and enter t_{device} as the child-table template. Map source ts in milliseconds to the primary timestamp, temperature to a DOUBLE data column, and device to a tag.
  3. The mapping preview should generate t_d001, temperature 23.5, and tag d001, with the sample's timestamp. Fix rules first if values are null or types are wrong. Preview neither publishes messages nor writes to the target. Submit and start the task, then send real messages for verification.

For sample input, see Samples and previews. When extending rules, see Extraction, splitting, filtering, and transformation and Target mapping.

2.3 JSON depth and array boundaries​

When parsing all fields with depth configured, the JSON parser recursively flattens nested objects to that depth and joins field names with underscores. For example, with depth set to 10, the following input produces 1 row with a payload_device_sensor_value field whose value is 42:

{"payload":{"device":{"sensor":{"value":42}}}}

An array inside an object remains the value of that field. Objects inside the array are not flattened. For example:

{"payload":{"device":{"id":7},"items":[{"reading":{"value":42}}]}}

This produces 1 row with a payload_device_id field whose value is 7; the value of payload_items is [{"reading":{"value":42}}]. It does not produce a payload_items_reading_value field.

Every non-null element in a top-level JSONArray must be a JSONObject. null elements are skipped. For example, this input produces 2 rows with payload_device_id values 7 and 8:

[{"payload":{"device":{"id":7}}},null,{"payload":{"device":{"id":8}}}]

An array containing a scalar fails to parse. For example, the following input returns UnsupportedJsonValue(5):

[{"id":1},5]

3. Session and topic configuration​

SettingMeaning to confirm
Client IDThe UI may add a prefix or task identifier. Record the actual ID; conflicts may let another client displace the connection.
Clean SessionAffects session retention. Changing this switch alone cannot promise recovery of all downtime messages; Broker persistence, QoS, and other conditions also matter.
Subscription QoSDefines subscription delivery conditions, not an end-to-end duplicate-free database-write guarantee.
Topic parsingCan extract topic levels into fields. Check them separately from body fields; _ ignores that level.
Compression and character encodingIncorrect settings can cause parsing failures or garbled text. Verify with a real message first.

With MQTT 5.0 and Clean Session disabled, the client requests a session expiry of 60 seconds. Check the actual value accepted by the Broker and its persistence policy. This is not a backfill guarantee for arbitrary downtime. During recovery drills, record disconnect and reconnect times, Client ID, and server-side session state, then use identifiable messages to check gaps and duplicates.

3.1 MQTT 5 properties and shared subscriptions​

With protocol 5.0, Connection User Properties are sent with the connection, and Subscription User Properties with the subscription. Both are Broker-interpreted key-value properties, not ingested columns; generic Brokers are not guaranteed to support the same business meanings. DSNs use connect_user_properties and subscribe_user_properties, respectively, in a format such as key1=value1,key2=value2. Redact credential properties and do not expose them in screenshots.

MQTT 5 connection user property input

MQTT 5 subscription properties and Broker-specific initial position

The subscription format is 主题::QoS, with QoS 0, 1, or 2. Final behavior depends on Broker capabilities and authorization. A shared-subscription example is $share/taosx_demo/taosx/test/temperature::0: $share is the fixed prefix, taosx_demo is the group name, and the remainder is the actual topic. Shared subscriptions distribute messages among clients in the same group rather than giving every task all data. Confirm the Broker, protocol, and business intent first. Do not use them directly for tests that require complete copies.

The subscription initial position is a feature of specific Brokers, such as Bnode, not a Kafka-style consumer offset in ordinary MQTT Brokers. Setting it cannot promise replay on every server.

3.2 Parse topic levels​

For subscription plant/+/temperature::0 and topic parsing rule _/device/_, an actual topic plant/d001/temperature extracts device=d001. _ ignores a level; it is not a wildcard. The subscription's + matches a single topic level. If body fields and topic variables share a name, inspect a real preview before relying on either to overwrite the other.

Select compression none, gzip, snappy, lz4, or zstd to match the producer. Supported encodings are UTF_8, GBK, GB18030, and BIG5. Check decompression, decoding, and JSON structure with one real message first, then configure shared Parsing (JSON, Regex, UDT), Extraction, splitting, filtering, and transformation, and Target table modeling and field mapping.

To generate wide-table columns from metric names in messages, configure and verify using Dynamic column names and wide-table mapping. Keep the fixed temperature column for this page's minimal exercise rather than enabling a dynamic model at the same time.

3.3 Message-level collection time​

According to the v3.4.4.2 release notes, an MQTT 5.0 publish message can carry exactly one Timestamp user property to provide collection time in UTC+8. The property name is case-sensitive, and its value is parsed as yyyy-MM-dd HH:mm:ss:SSS, for example 2026-10-20 13:46:30:103. The parsed result becomes source ts and is used as the target primary timestamp only when the mapping selects this field for that role.

This property belongs to each publish message; Connection User Properties or Subscription User Properties cannot replace it. If it is missing, invalid, outside the nanosecond timestamp range, or appears more than once as Timestamp in the same message, the timestamp falls back to message reception time. MQTT 3.1.1 continues to use reception time. For older versions, confirm whether the delivered version includes this change.

4. Publish the test messages​

Confirm the task has established its subscription before sending. These commands require the Mosquitto command-line client installed and mosquitto_pub available on the publishing host. Use them only with an administrator-approved isolated Broker allowing unauthenticated plaintext access. Example host 127.0.0.1 refers to the host running the publishing process. Replace it with the real address if the Broker is elsewhere. Configure TLS and identity for production Brokers as the administrator requires. Do not disable authentication to run the example.

Run in Linux Bash on the publishing host:

set -e
broker_host=127.0.0.1
mosquitto_pub -h "$broker_host" -p 1883 -V mqttv311 \
-t 'taosx/test/temperature' -q 0 \
-m '{"device":"d001","ts":1795132800000,"temperature":23.5}'
mosquitto_pub -h "$broker_host" -p 1883 -V mqttv311 \
-t 'taosx/test/temperature' -q 0 \
-m '{"device":"d001","ts":1795132801000,"temperature":24.5}'

In both Windows and Linux commands, -p is the Broker port, -V mqttv311 is the test publishing client's protocol, -t is the topic, and -q 0 is the publishing QoS. A task using MQTT 5 does not require every publishing client to use that version too; the Broker decides what is allowed. If the port or topic differs, update both the task and publishing commands.

5. Advanced options and write-error policies​

Before submitting, expand Advanced Options and record batches, write concurrency, and health-monitoring settings separately. Batch size is not MQTT QoS or a Broker message-retention setting.

MQTT advanced options for waiting queues, batching, real-time caching, and raw retention

SettingNew-form initial value
Maximum processing batches100 batches, minimum 1.
Batch size1000 messages.
Batch delay500 milliseconds.
Write concurrency and health monitoringRecord this task's form values. For existing tasks, use actual saved values.

For batch sending, concurrency, and tuning verification, see Message batching. For health fields, see Health monitoring configuration.

5.1 Waiting queue and file purposes​

MQTT-specific settingConfiguration and conditionsOperations checks
Message waiting queue size50000 messages in a new form. When real-time caching is not enabled, a full queue drops newly arriving messages.Do not interpret 0 as unlimited capacity or shrink the queue to clear backlog. Compare changes in received, discarded, and written counts and check target samples.
Cache real-time dataDisabled by default. Only when enabled is Cached Data Storage Directory used to save pending data.First confirm the directory, service-account permissions, space, and interruption budget on the actual collection host. Recovery requires readable cache files and a writable target. Do not move live files manually.
Save raw dataDisabled by default. When enabled, configure Maximum Retention Days and Raw Data Storage Directory.Use an approved message to confirm files keep updating. Disable it and restart the task, then check that no new data is added. Retained files may contain business data; handle them according to authorization.

Source sessions, collection-side real-time cache, taosX-Agent store-and-forward, and target write caching below are different mechanisms. Raw message retention is for reviewing input, not an automatic backfill queue. Waiting queues and raw retention can each drop data. Even with caching selected, recovery is not guaranteed for QoS 0 messages, data never received, or files already removed. For directory queries, capacity estimates, and MQTT retention parameters, see Raw data retention.

The defaults above describe the new-task UI. Command-line parameters such as Keep Alive and read-batch wait have their own defaults and units; configure them using MQTT read parameters. Real-time disk caching for service tasks depends on task context. In standalone taosx run, the same DSN switch does not establish disk-recovery capability.

For target error actions, defaults, and cache/archive settings, see Write errors. For archive retrieval, see Logs and performance. For sessions and interruption recovery, see Restart, checkpoints, and store-and-forward.

6. Verification​

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

SELECT ts, temperature, device FROM mqtt_demo.t_d001
WHERE ts = 1795132800000;

The result should contain 23.5 and d001. Send data with a new timestamp to confirm continued writes. A Broker reporting the client online or a publishing client reporting success cannot replace a target-table query.

For the two messages above, continue with WHERE ts IN (1795132800000, 1795132801000) ORDER BY ts; expected values are 23.5 and 24.5, respectively. If timestamps were replaced to fit retention, update the sample, actual messages, and query conditions together.

7. Troubleshooting​

SymptomChecks and action
Repeated disconnectsCheck actual Client ID conflicts and Keep Alive settings.
Online, but no messagesCheck subscription topics, publishing topics, ACLs, and shared-subscription allocation. Check whether messages were sent only before the subscription was established.
Parsing failsCheck whether the payload is JSON or compressed, the character encoding, and field names.

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

8. Stop and recover​

Stop the original task and preserve its actual Client ID, session settings, and mapping. After restarting, check results with new messages. Historical backfill depends on Broker sessions and retention, not Kafka consumer-group behavior. For Agent-link caching, see Restart, checkpoints, and store-and-forward. It does not protect data not yet collected.

9. Limitations​

The legacy MQTT 3.1 protocol is not supported. Test retained messages, persistent sessions, shared subscriptions, and QoS separately rather than inferring them from one ordinary publication test. Do not disable production TLS verification to make a connection succeed.

The session and retention settings here are not a complete Broker or target-database backup. For their protection scope, see Waiting queue and file purposes.