Skip to main content

Send data to Zerobus Ingest from an MQTT client library

Beta

This feature is in Beta. To use it, a workspace admin must turn on Zerobus Ingest MQTT Endpoint from the Previews page. See Manage Databricks previews.

info

For the MQTT endpoint, the CONNECT properties, and the quality of service (QoS) rules, see Use MQTT with Zerobus Ingest. This page covers only the client code.

Maintained by: the Eclipse Paho project, in the eclipse-paho/paho.mqtt.python and eclipse-paho/paho.mqtt.java repositories, and the MQTT.js project, in the mqttjs/MQTT.js repository.

A long-running service publishes JSON records to Zerobus Ingest over MQTT v5, and Zerobus Ingest writes each record directly to a Delta table. You don't need to run a message bus between the application and the table. This page has one example for each language: Python, Java, and Node.js. Choose your language in the tabs at each step. The rescue column and the acknowledgment rules are the same in every tab.

When to use this page​

  • Your application is written in Python, Java, or Node.js, and it publishes JSON records continuously, for example sensor readings or application events.
  • The service runs longer than one connection. The endpoint closes a connection after a bounded server-side lifetime, so the client must reconnect with a new token.
  • You need to know which records are stored, and what happens to the ones that aren't.

Otherwise, for a script that publishes a few records and exits, start with Example: Publish a record.

How it works​

  • Connections and tokens: The client connects over TLS to port 8883 on the Zerobus Ingest hostname. Each connection targets one table, and a connection can't switch tables. CONNECT carries two User Properties: Authorization, with a table-scoped OAuth token, and x-databricks-zerobus-table-name, with the table name. The server closes a connection after its bounded lifetime, so each reconnect sends a new token in new CONNECT properties. All three examples disable the client's automatic reconnect and reconnect in their own code.
  • Acknowledgments: A record counts as stored only after its PUBACK arrives with a successful reason code. If the connection closes before the PUBACK arrives, the record might already be stored, so a retry can create a duplicate row.
  • Rescue column: Each record is one UTF-8 JSON object. The examples need a rescue column. Without one, a record whose fields don't match the table closes the connection.

The examples track acknowledgments and reconnects differently. Compare Publish records and track each PUBACK with Reconnect with a new token and retry.

Requirements​

  • MQTT enabled for your workspace. See Prerequisites.
  • For the Python example, Python 3.10 or above, with pip. The example pins requests 2.34.2, which needs Python 3.10.
  • For the Java example, Java Development Kit (JDK) 17 and above, and Maven, which resolves the Paho client from Maven Central.
  • For the Node.js example, Node.js 20.6 or above, with npm. The example's npm start script reads config.env with --env-file, which needs 20.6.
  • An existing Unity Catalog table that meets the requirements in Table requirements, with a rescue column: a rescue VARIANT column with the zerobus-rescue tag. The examples depend on the rescue column. The Create the target table step creates the table.
  • A service principal with USE CATALOG, USE SCHEMA, SELECT, and MODIFY on the table. See Configure authentication.
  • Your workspace URL, workspace ID, and Zerobus Ingest hostname. See Get your workspace URL and Zerobus Ingest endpoint.
  • Outbound TLS access to the Zerobus Ingest hostname on port 8883.
  • SQL access (a SQL warehouse or compute) to run the statements in Create the target table.
  • The table's columns are nullable.

Create the target table​

Create a table with the columns that match your JSON records, plus a rescue column with the zerobus-rescue tag. Zerobus Ingest doesn't create tables, so run these statements first.

The Python example writes to a table named dice_rolls:

SQL
CREATE TABLE IF NOT EXISTS <catalog>.<schema>.dice_rolls
(roll_id STRING, player STRING, sides INT, dice INT, total INT, rescue VARIANT);

ALTER TABLE <catalog>.<schema>.dice_rolls
ALTER COLUMN rescue SET TAGS ('zerobus-rescue');

The rescue column stores a value whose type doesn't match its column only when that column is nullable. Tag changes can take up to 5 minutes to take effect, so wait up to 5 minutes after you apply the tag before you publish.

Add the client library to your project​

Install the Eclipse Paho Python client and the other dependencies from the example's requirements.txt file, which pins paho-mqtt 2.2.0 and requests 2.34.2:

Bash
pip install -r requirements.txt

Set the connection values​

The example reads its settings from environment variables. The file config.example.env shows each variable with a placeholder value:

Bash
# Copy to config.env and fill in. Never commit real values.
export DATABRICKS_WORKSPACE_URL="https://<workspace-url>"
export DATABRICKS_WORKSPACE_ID="<workspace-id>"
export DATABRICKS_CLIENT_ID="<service-principal-client-id>"
export DATABRICKS_CLIENT_SECRET="<service-principal-client-secret>"
export DATABRICKS_TABLE_NAME="<catalog>.<schema>.dice_rolls"
export ZEROBUS_MQTT_HOST="<workspace-id>.zerobus.<region>.<cloud-domain>"

Copy the file to config.env, replace the placeholders with your values, and load the variables into your shell:

Bash
cp config.example.env config.env
# edit config.env, then:
source config.env

Set ZEROBUS_MQTT_HOST to the Zerobus Ingest hostname from Requirements.

The hostname format is <workspace-id>.zerobus.<region>.gcp.databricks.com.

Connect with a new token​

Each connection requests a new table-scoped token and sends it in CONNECT. The token request uses the client credentials grant, with authorization_details for the catalog, schema, and table, and the zerobusDirectWriteApi resource for your workspace.

The fetch_token() function requests the token:

Python
def fetch_token(config: Config) -> str:
"""Client credentials grant, scoped to the target table (see zerobus-mqtt.md)."""
catalog, schema, _ = config.table_name.split(".")
authorization_details = [
{"type": "unity_catalog_privileges", "privileges": ["USE CATALOG"],
"object_type": "CATALOG", "object_full_path": catalog},
{"type": "unity_catalog_privileges", "privileges": ["USE SCHEMA"],
"object_type": "SCHEMA", "object_full_path": f"{catalog}.{schema}"},
{"type": "unity_catalog_privileges", "privileges": ["SELECT", "MODIFY"],
"object_type": "TABLE", "object_full_path": config.table_name},
]
response = requests.post(
f"{config.workspace_url}/oidc/v1/token",
auth=(config.client_id, config.client_secret),
data={
"grant_type": "client_credentials",
"scope": "all-apis",
"resource": f"api://databricks/workspaces/{config.workspace_id}/zerobusDirectWriteApi",
"authorization_details": json.dumps(authorization_details),
},
timeout=30,
)
response.raise_for_status()
return response.json()["access_token"]

Each connection has an _Attempt object, which Paho passes to the callbacks:

Python
class _Attempt:
"""One connection attempt. Paho passes it to the callbacks as userdata, so each event names its connection."""

def __init__(self):
self.connack = threading.Event()
self.reason = None # CONNACK reason code, once received
self.closing = False # set by _teardown before it closes this connection

The _new_client() method creates the Eclipse Paho Python client with automatic reconnect disabled:

Python
def _new_client(self, attempt: _Attempt) -> mqtt.Client:
client = mqtt.Client(
mqtt.CallbackAPIVersion.VERSION2,
client_id=f"zerobus-mqtt-{uuid.uuid4()}",
protocol=mqtt.MQTTv5,
# The app reconnects itself with a fresh token, so Paho's automatic reconnect is off.
reconnect_on_failure=False,
userdata=attempt,
)
client.on_connect = self._on_connect
client.on_publish = self._on_publish
client.on_disconnect = self._on_disconnect
client.connect_timeout = CONNECT_TIMEOUT_SECONDS
client.max_inflight_messages_set(MAX_INFLIGHT)
client.tls_set(cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLS_CLIENT)
return client

The connect() method fetches a token, builds the CONNECT properties, and opens the connection:

Python
def connect(self) -> None:
"""Fetch a new token and open a new connection. Called at start and on every reconnect."""
with self._connect_lock:
token = fetch_token(self.config)
log.info("token fetched %s", token_times(token))
properties = mqtt.Properties(mqtt.PacketTypes.CONNECT)
properties.UserProperty = [
("Authorization", f"Bearer {token}"),
("x-databricks-zerobus-table-name", self.config.table_name),
]
del token

attempt = _Attempt()
client = self._new_client(attempt)
result = client.connect(
self.config.mqtt_host,
port=PORT,
keepalive=KEEPALIVE_SECONDS,
clean_start=True,
properties=properties,
)
del properties
if result != mqtt.MQTT_ERR_SUCCESS:
raise ConnectionError(f"MQTT connect failed: {mqtt.error_string(result)}")
client.loop_start()

if not attempt.connack.wait(CONNACK_TIMEOUT_SECONDS) or attempt.reason is None:
client.disconnect()
client.loop_stop()
raise TimeoutError("Timed out waiting for CONNACK")
if attempt.reason.is_failure:
client.disconnect()
client.loop_stop()
raise ConnectionRefusedError(f"CONNECT rejected: {attempt.reason}")

with self._lock:
self._current = attempt
self._client = client
self._connected.set()
self.connect_count += 1
log.info("connected (connection %d)", self.connect_count)

Each connection gets a new client ID. The ID must be unique among active connections and at most 128 bytes.

Publish records and track each PUBACK​

The submit() method queues a record. The pump() method sends queued records while the connection is up and the in-flight window has room. The window holds up to MAX_INFLIGHT records, which is 100 in the example.

Python
def submit(self, record: dict) -> None:
"""Queue one record. It is sent now if connected, or on the next connection."""
self.submit_raw(json.dumps(record).encode("utf-8"), record)
Python
def pump(self) -> None:
"""Send queued records while the connection is up and the in-flight window has room."""
with self._lock:
self._drain()
if not self._connected.is_set() or self._client is None:
return
now = time.monotonic()
# A record that was in flight at a close with other records is a suspect. Suspects are
# sent one at a time, so the next close can be pinned on a single record. Other records
# wait until no suspect is left.
isolating = any(p.suspect for p in self._queue) or any(p.suspect for p in self._inflight.values())
window = 1 if isolating else MAX_INFLIGHT
remaining = []
for pending in self._queue:
if (len(self._inflight) >= window or pending.not_before > now
or (isolating and not pending.suspect)):
remaining.append(pending)
continue
if len(pending.payload) > MAX_PUBLISH_PAYLOAD_BYTES:
# An oversized PUBLISH closes the connection. Retrying it never succeeds.
self._reject(pending, "payload exceeds the packet size limit")
continue
info = self._client.publish(self.config.table_name, pending.payload, qos=1)
if info.rc != mqtt.MQTT_ERR_SUCCESS:
remaining.append(pending)
continue
pending.attempts += 1
self._inflight[info.mid] = pending
log.debug("PUBLISH mid=%s attempt=%d bytes=%d", info.mid, pending.attempts, len(pending.payload))
self._queue = remaining

Paho calls the PUBACK callback on its network thread, so the callbacks only queue an event. The application thread applies the queued events in _drain(), which pump() and flush() call. A PUBACK that arrives before publish() returns is still matched to its record, because _drain() runs after pump() has recorded the packet ID.

Python
def _on_disconnect(self, client, attempt, flags, reason_code, properties):
attempt.connack.set() # unblocks a connect() that is still waiting for CONNACK
# Paho also reports our own DISCONNECT here. Once _teardown has set closing, that close is ours.
kind = "closed" if attempt.closing else "disconnect"
self._events.put((kind, attempt, reason_code))
Python
def _on_publish(self, client, attempt, mid, reason_code, properties):
# A PUBACK can arrive before publish() returns. The event waits in the queue until
# _drain() runs, which is after pump() has recorded the mid, so it always finds its record.
self._events.put(("puback", attempt, mid, reason_code))
Python
def _drain(self) -> None:
"""Apply the callback events for the current connection, in the order they arrived."""
with self._lock:
while True:
try:
event = self._events.get_nowait()
except queue.Empty:
return
kind, attempt = event[0], event[1]
if attempt is not self._current:
continue # from a connection that was already closed or replaced
if kind == "puback":
self._apply_puback(event[2], event[3])
elif kind == "disconnect":
self._handle_disconnect(event[2])
# "closed" is our own close, echoed by Paho. _teardown requeues what is left.
Python
def _apply_puback(self, mid: int, reason_code) -> None:
pending = self._inflight.pop(mid, None)
if pending is None:
log.debug("PUBACK mid=%s matched nothing", mid)
return
pending.suspect = False # the server answered it, so it's no longer an unattributed casualty
log.debug("PUBACK mid=%s roll_id=%s reason=%s", mid, pending.record.get("roll_id"), reason_code)
if reason_code.is_failure:
self._retry_after_puback(pending, f"PUBACK {reason_code}",
bad_record=reason_code.value == PAYLOAD_FORMAT_INVALID)
else:
self.durable_count += 1
self.recent_durable.append(pending.record)

The publisher counts stored records in durable_count and keeps the 50 most recent in recent_durable. It counts and keeps failed and rejected records the same way, in recent_failed and recent_rejected. The example rejects a payload over the packet size limit locally, because the server closes the connection when it receives an oversized PUBLISH.

The following table shows what happens to a record that doesn't match the table:

Record

With the rescue column

Without the rescue column

A value of the wrong type, or a field that the table doesn't have

PUBACK succeeds. The nonmatching fields are stored in rescue, and the connection stays open.

The server closes the connection with reason code 0x83 (131, Implementation specific error). No PUBACK arrives, and the record isn't stored.

A payload that isn't valid JSON

PUBACK fails with reason code 0x99 (153, Payload format invalid). Nothing is stored, and the connection stays open.

Same as with the rescue column.

Record

With the rescue column

Without the rescue column

A value of the wrong type, or a field that the table doesn't have

PUBACK succeeds. The nonmatching fields are stored in rescue, and the connection stays open.

The server closes the connection with reason code 0x83 (131, Implementation specific error). No PUBACK arrives, and the record isn't stored.

A payload that isn't valid JSON

PUBACK fails with reason code 0x99 (153, Payload format invalid). Nothing is stored, and the connection stays open.

Same as with the rescue column.

The retry behavior after these outcomes differs by client. Reconnect with a new token and retry shows each one.

Reconnect with a new token and retry​

A connection ends when the server closes it after its bounded lifetime, or when the network drops. The client code reconnects, so the new connection gets a new token. A retry can store a duplicate, as Durability and acknowledgments describes.

The reconnect() method drops the open connection and connects with a new token:

Python
def reconnect(self, reason: str) -> None:
"""Drop the current connection and connect with a new token.

Records in flight are retried. This close is ours, not the server's, so no record is charged.
"""
with self._connect_lock:
self._teardown(reason)
self.connect()

The _teardown() method closes the open connection. It stops the network loop first, so no more acknowledgments arrive for that connection. It then applies the acknowledgments that did arrive, and requeues only the records that are still unacknowledged:

Python
def _teardown(self, reason: str) -> None:
"""Close the current connection, if any, and requeue what it left unacknowledged.

The order matters:
1. Mark the attempt as closing, so the DISCONNECT that Paho echoes back charges nobody.
2. Disconnect and stop the network thread. loop_stop() joins that thread, so every callback
this connection will make is queued when it returns.
3. Drain the queue while this attempt is still the current one. Acknowledgments that arrived
before the close are applied, so their records are not resent.
4. Requeue only the records still unacknowledged, and retire the attempt.

A close the server reported before this point is charged first, as in _handle_disconnect().
"""
with self._lock:
old = self._client
attempt = self._current
if attempt is not None:
attempt.closing = True
if old is not None:
old.disconnect()
old.loop_stop() # joins the network thread; keep it outside self._lock
with self._lock:
self._drain()
self._requeue_inflight(reason, charge=False)
self._client = None
self._current = None
self._connected.clear()

The _handle_disconnect() method handles a close that the server starts:

Python
def _handle_disconnect(self, reason_code) -> None:
log.warning("disconnected: %s", reason_code)
self._current = None
self._connected.clear()
self._requeue_inflight(f"disconnected: {reason_code}", charge=True)

The _requeue_inflight() method puts the unacknowledged records back in the queue:

Python
def _requeue_inflight(self, reason: str, charge: bool) -> None:
"""Requeue the records a connection left unacknowledged.

charge=True: the server closed the connection. If one record was in flight, the close is
pinned on it, and it gives up after MAX_CONNECTION_LOSS_ATTEMPTS closes. If several were in
flight, nobody is charged: each becomes a suspect and is sent alone until it's answered.
charge=False: this client closed the connection (token rotation, shutdown). Nobody is charged.

A record whose PUBACK was lost may already be durable, so a retry can create a duplicate row.
"""
lost = list(self._inflight.values())
self._inflight.clear()
if not lost:
return
if not charge:
self._queue.extend(lost)
return
if len(lost) == 1:
pending = lost[0]
pending.suspect = False
pending.connection_losses += 1
pending.last_reason = reason
if pending.connection_losses >= MAX_CONNECTION_LOSS_ATTEMPTS:
self._fail(pending, reason)
return
pending.not_before = time.monotonic() + min(2 ** pending.connection_losses, MAX_BACKOFF_SECONDS)
self._queue.append(pending)
return
for pending in lost:
pending.suspect = True
pending.last_reason = reason
self._queue.append(pending)

The example charges a close that the server causes only to a record that was alone in flight. It abandons that record after MAX_CONNECTION_LOSS_ATTEMPTS (two) such closes. When several records were in flight, the example charges none of them and sends each one alone until the server answers it, so a bad record can't get valid records abandoned. A reconnect that your code starts charges no record.

A record whose PUBACK has a failure reason code gets MAX_ATTEMPTS (five) attempts, except reason code 0x99 (153, Payload format invalid), which gets MAX_BAD_RECORD_ATTEMPTS (two). The example's limits are these constants in zerobus_mqtt.py:

Python
# The CONNACK Receive Maximum is 4,096. Stay well below it.
MAX_INFLIGHT = 100
# Complete packet limit after CONNECT is 64 KiB. Keep a margin for the topic and header.
MAX_PUBLISH_PAYLOAD_BYTES = 64 * 1024 - 1024
# Attempts per record. A record that keeps failing is usually malformed, so the publisher gives up
# after a small number of tries instead of retrying forever.
MAX_ATTEMPTS = 5 # PUBACK with a failure reason code other than 0x99
MAX_CONNECTION_LOSS_ATTEMPTS = 2 # connection closed while this record was the only one in flight
MAX_BAD_RECORD_ATTEMPTS = 2 # PUBACK 0x99 (Payload format invalid): the payload isn't valid JSON
PAYLOAD_FORMAT_INVALID = 0x99
MAX_BACKOFF_SECONDS = 30
# Durable records, failures and rejections are counted in full. Only the last few are kept.
RECENT_RECORDS = 50

The ensure_connected() method reconnects with backoff when the connection is down, and it returns only when a connection is up. The example calls it before each pump() in its loop, and in flush() at shutdown. A service with its own loop must call it before each pump() too. Without that call, records queued after a server close wait until shutdown.

Shut down cleanly​

On SIGINT or SIGTERM, stop producing records, then call close(). The close() method flushes the queue, waits until every record is stored or has been abandoned, and then sends DISCONNECT and stops the network thread:

Python
def flush(self, timeout: float = 60.0) -> bool:
"""Wait until every record is durable or has been given up on."""
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
with self._lock:
self._drain()
done = not self._queue and not self._inflight
if done:
return True
if not self._connected.is_set():
self.ensure_connected()
self.pump()
time.sleep(0.1)
return False

def close(self, timeout: float = 60.0) -> bool:
"""Flush, then send DISCONNECT and stop the network thread."""
clean = self.flush(timeout)
with self._connect_lock:
self._teardown("closing")
return clean

If the timeout passes first, close() returns False. Queued records aren't sent, and unacknowledged records might or might not be stored when the process exits. Check the result before you exit, and log or save the records your service can't lose. The example logs its counts and exits with a nonzero status when shutdown isn't clean or a record isn't stored.

Run the example​

The complete examples are in the example_clients folder of the Zerobus Ingest examples repository. The Python example is in the mqtt_paho_python_zerobus folder, the Java example is in the mqtt_paho_java_zerobus folder, and the Node.js example is in the mqtt_mqttjs_zerobus folder.

Change to the src directory and publish 20 rolls:

Bash
cd src
python dice_roller.py --rolls 20 --interval 0.5

A successful run ends with a line like this:

Text
connections=1 durable=20 failed=0 rejected=0 clean_shutdown=True

The exit status is 0 when every record is stored and the shutdown was clean. Otherwise, it is 1. Use --force-reconnect-after to test a reconnect with a new token. Use --send-invalid-record to see how the table handles records that don't match it. A run with --send-invalid-record exits 1, because the non-JSON record isn't stored.

Query the table​

Stored records can take a short time to appear, because Zerobus Ingest writes them to the table asynchronously. See Durability and acknowledgments.

Rows with a value in rescue came from records that didn't match the table:

SQL
SELECT roll_id, sides, rescue FROM <catalog>.<schema>.dice_rolls WHERE rescue IS NOT NULL;

Troubleshooting​

The following table lists common symptoms, causes, and fixes:

Symptom

Cause

Fix

CONNECT is refused.

The Authorization token or the x-databricks-zerobus-table-name property doesn't match the target table, or the service principal lacks the grants on it.

Fetch a token for the same table, send both User Properties as Connect with a new token shows, and check the grants in Requirements. See Troubleshooting.

The connection closes with DISCONNECT reason code 0x83 (131, Implementation specific error), and no PUBACK arrives for a record.

The table has no column tagged zerobus-rescue, and the record has a field the table doesn't have or a value of the wrong type.

Add the rescue column as Create the target table shows, and wait for the tag delay that step describes. The record that caused the close isn't stored, so send it again.

PUBACK has reason code 0x99 (153, Payload format invalid).

The payload isn't one valid UTF-8 JSON object.

Serialize each record as one JSON object before you publish it.

Duplicate rows after a retry or a reconnect.

A PUBACK was lost when the connection closed, so the record was sent again.

Deduplicate by a unique ID in the table, such as roll_id in the Python example, or make the table tolerate duplicates.

Python or Java, in your own publish loop: publishes fail with a disconnect after the application has run for a while, or records stay queued.

The server closes each connection after its bounded lifetime. Both examples reconnect in their own code, so a loop that doesn't reconnect fails after the close.

Follow Reconnect with a new token and retry.

Node.js: a rejected record is sent again on every reconnect, and the process keeps reconnecting.

MQTT.js keeps an unacknowledged QoS 1 publish and sends it again on the next connection.

Remove the record from MQTT.js when the connection closes, as the close handler in Reconnect with a new token and retry does.

Node.js: a TIMESTAMP column shows dates in January 1970.

A JSON number in a TIMESTAMP column is read as epoch microseconds. Epoch milliseconds read that way fall in January 1970.

Multiply epoch milliseconds by 1000, as dice.js does with now.getTime() * 1000.

Node.js: a publish rejects with no connection within 30000 ms; the record was not sent.

The connection didn't reconnect within 30 seconds. The reconnect can fail when the token request fails, or when outbound TLS to port 8883 is blocked.

Read the token request failed and reconnecting in lines that the example logs, and check outbound TLS to the MQTT host on port 8883. The record wasn't sent, so publish it again after the connection is up.

Node.js: a reconnect sends the token from the previous connection.

The token was set after connect() or reconnect() ran, or the automatic reconnect started before the token request finished.

Set client.options.properties before you call connect() or reconnect(), and set reconnectPeriod to 0, as the example does.

Symptom

Cause

Fix

CONNECT is refused.

The Authorization token or the x-databricks-zerobus-table-name property doesn't match the target table, or the service principal lacks the grants on it.

Fetch a token for the same table, send both User Properties as Connect with a new token shows, and check the grants in Requirements. See Troubleshooting.

The connection closes with DISCONNECT reason code 0x83 (131, Implementation specific error), and no PUBACK arrives for a record.

The table has no column tagged zerobus-rescue, and the record has a field the table doesn't have or a value of the wrong type.

Add the rescue column as Create the target table shows, and wait for the tag delay that step describes. The record that caused the close isn't stored, so send it again.

PUBACK has reason code 0x99 (153, Payload format invalid).

The payload isn't one valid UTF-8 JSON object.

Serialize each record as one JSON object before you publish it.

Duplicate rows after a retry or a reconnect.

A PUBACK was lost when the connection closed, so the record was sent again.

Deduplicate by a unique ID in the table, such as roll_id in the Python example, or make the table tolerate duplicates.

Python or Java, in your own publish loop: publishes fail with a disconnect after the application has run for a while, or records stay queued.

The server closes each connection after its bounded lifetime. Both examples reconnect in their own code, so a loop that doesn't reconnect fails after the close.

Follow Reconnect with a new token and retry.

Node.js: a rejected record is sent again on every reconnect, and the process keeps reconnecting.

MQTT.js keeps an unacknowledged QoS 1 publish and sends it again on the next connection.

Remove the record from MQTT.js when the connection closes, as the close handler in Reconnect with a new token and retry does.

Node.js: a TIMESTAMP column shows dates in January 1970.

A JSON number in a TIMESTAMP column is read as epoch microseconds. Epoch milliseconds read that way fall in January 1970.

Multiply epoch milliseconds by 1000, as dice.js does with now.getTime() * 1000.

Node.js: a publish rejects with no connection within 30000 ms; the record was not sent.

The connection didn't reconnect within 30 seconds. The reconnect can fail when the token request fails, or when outbound TLS to port 8883 is blocked.

Read the token request failed and reconnecting in lines that the example logs, and check outbound TLS to the MQTT host on port 8883. The record wasn't sent, so publish it again after the connection is up.

Node.js: a reconnect sends the token from the previous connection.

The token was set after connect() or reconnect() ran, or the automatic reconnect started before the token request finished.

Set client.options.properties before you call connect() or reconnect(), and set reconnectPeriod to 0, as the example does.

Additional resources​