Send data to Zerobus Ingest from an MQTT client library
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.
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
8883on the Zerobus Ingest hostname. Each connection targets one table, and a connection can't switch tables.CONNECTcarries two User Properties:Authorization, with a table-scoped OAuth token, andx-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 newCONNECTproperties. All three examples disable the client's automatic reconnect and reconnect in their own code. - Acknowledgments: A record counts as stored only after its
PUBACKarrives with a successful reason code. If the connection closes before thePUBACKarrives, 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 pinsrequests2.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 startscript readsconfig.envwith--env-file, which needs 20.6. - An existing Unity Catalog table that meets the requirements in Table requirements, with a rescue column: a
rescue VARIANTcolumn with thezerobus-rescuetag. 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, andMODIFYon 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.
- Python
- Java
- Node.js
The Python example writes to a table named dice_rolls:
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 Java example writes to a table named mqtt_paho_java:
CREATE TABLE IF NOT EXISTS <catalog>.<schema>.mqtt_paho_java (
device_name STRING,
temp INT,
humidity INT,
rescue VARIANT
);
ALTER TABLE <catalog>.<schema>.mqtt_paho_java
ALTER COLUMN rescue SET TAGS ('zerobus-rescue');
The Node.js example writes to a table named dice_rolls. Its columns differ from the Python example's dice_rolls table, so give each example its own table name if you run both in one schema:
CREATE TABLE IF NOT EXISTS <catalog>.<schema>.dice_rolls (
player_name STRING,
die_sides INT,
roll INT,
rolled_at TIMESTAMP,
rescue VARIANT
);
-- Tag the rescue column. Tag changes can take up to 5 minutes to take effect, so
-- publish only after this statement has been in place for at least 5 minutes.
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
- Python
- Java
- Node.js
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:
pip install -r requirements.txt
Add the Eclipse Paho Java client to pom.xml. The example sets the version in a property:
<paho.version>1.2.5</paho.version>
Then add the dependency:
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.mqttv5.client</artifactId>
<version>${paho.version}</version>
</dependency>
The client depends on org.eclipse.paho.mqttv5.common, which Maven resolves for you.
Install MQTT.js, which is the mqtt npm package, and the other dependencies with npm ci. The command installs the versions in the example's package-lock.json, which pins mqtt to 5.16.1:
npm ci
Set the connection values
- Python
- Java
- Node.js
The example reads its settings from environment variables. The file config.example.env shows each variable with a placeholder value:
# 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:
cp config.example.env config.env
# edit config.env, then:
source config.env
Copy the example's properties file to config.properties. The file is git-ignored. Replace the placeholders:
# Copy to config.properties (git-ignored) and replace the placeholders.
# Environment variables with the same names override these values.
# The service principal's client ID and secret are not stored here. Export
# DATABRICKS_CLIENT_ID and DATABRICKS_CLIENT_SECRET instead.
# Workspace URL, for the OAuth token request.
workspace.url=https://<workspace-url>
# Workspace ID, used in the token resource name.
workspace.id=<workspace-id>
# Target table in catalog.schema.table form.
table.name=<catalog>.<schema>.mqtt_paho_java
# Zerobus Ingest MQTT hostname, without https:// or a port. The port is always 8883.
mqtt.host=<workspace-id>.zerobus.<region>.<cloud-domain>
# Simulator settings.
sensor.device=sensor-1
sensor.records=20
sensor.interval.ms=1000
# Reconnect with a new token every N records. 0 turns this off.
sensor.reconnect.every=0
Set the service principal's client ID and OAuth secret as environment variables, not in the file. The example reads DATABRICKS_CLIENT_ID and DATABRICKS_CLIENT_SECRET only from the environment. An environment variable overrides the matching setting in the file. For example, DATABRICKS_TABLE_NAME overrides table.name.
The example reads its settings from config.env, which npm start loads with --env-file. The file config.example.env shows each variable with a placeholder value:
# Copy this file to config.env and fill in the values. Never commit config.env.
# Start the simulator with: npm start (Node 20.6+ reads config.env with --env-file)
# Your workspace URL, for example https://<workspace-url>
DATABRICKS_WORKSPACE_URL=https://<workspace-url>
# Your workspace ID, used in the zerobusDirectWriteApi resource of the token request
DATABRICKS_WORKSPACE_ID=<workspace-id>
# Service principal application (client) ID and OAuth secret
DATABRICKS_CLIENT_ID=<service-principal-client-id>
DATABRICKS_CLIENT_SECRET=<service-principal-client-secret>
# Target Unity Catalog table, three-level name
DATABRICKS_TABLE_NAME=<catalog>.<schema>.dice_rolls
# Zerobus Ingest MQTT hostname, without https://
ZEROBUS_MQTT_HOST=<workspace-id>.zerobus.<region>.<cloud-domain>
# Simulator settings (optional)
# Milliseconds between rolls
ROLL_INTERVAL_MS=1000
# Number of rolls to send, 0 keeps going until you press Ctrl+C
ROLL_COUNT=0
Copy the file to config.env and replace the placeholders with your values. Keep config.env out of version control, because it holds the OAuth secret.
Set ZEROBUS_MQTT_HOST to the Zerobus Ingest hostname from Requirements.
The hostname format is <workspace-id>.zerobus.<region>.cloud.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.
- Python
- Java
- Node.js
The fetch_token() function requests the token:
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:
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:
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:
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.
TokenClient.fetchToken() requests the token:
String fetchToken() throws IOException, InterruptedException {
Map<String, String> fields = new LinkedHashMap<>();
fields.put("grant_type", "client_credentials");
fields.put("scope", "all-apis");
fields.put("resource", "api://databricks/workspaces/" + settings.workspaceId() + "/zerobusDirectWriteApi");
fields.put("authorization_details", authorizationDetailsJson(settings.tableName()));
String credentials = settings.clientId() + ":" + settings.clientSecret();
HttpRequest request = HttpRequest.newBuilder(URI.create(settings.workspaceUrl() + "/oidc/v1/token"))
.timeout(Duration.ofSeconds(30))
.header("Authorization", "Basic " + Base64.getEncoder()
.encodeToString(credentials.getBytes(StandardCharsets.UTF_8)))
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString(form(fields)))
.build();
HttpResponse<String> response = http.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
// Print the status only. The body is not logged, so nothing sensitive reaches the output.
throw new IOException("Token request failed with HTTP " + response.statusCode());
}
JsonNode accessToken = JSON.readTree(response.body()).get("access_token");
if (accessToken == null || accessToken.asText().isBlank()) {
throw new IOException("Token response has no access_token");
}
return accessToken.asText();
}
The publisher creates one Eclipse Paho Java client, with a unique client ID and the ssl:// URI for port 8883:
ZerobusMqttPublisher(Settings settings, TokenClient tokens) throws MqttException {
this.settings = settings;
this.tokens = tokens;
String clientId = "sensor-simulator-" + UUID.randomUUID();
this.client = new MqttClient("ssl://" + settings.mqttHost() + ":" + MQTT_PORT, clientId,
new MemoryPersistence());
this.client.setCallback(new ConnectionEvents());
this.client.setTimeToWait(PUBACK_TIMEOUT_MS);
}
connect() fetches a token, sends it with the table name as User Properties, and opens the connection. The example disables automatic reconnect:
void connect() throws IOException, InterruptedException, MqttException {
String token = tokens.fetchToken();
List<UserProperty> userProperties = new ArrayList<>();
userProperties.add(new UserProperty("Authorization", "Bearer " + token));
userProperties.add(new UserProperty("x-databricks-zerobus-table-name", settings.tableName()));
MqttConnectionOptions options = new MqttConnectionOptions();
options.setCleanStart(true);
options.setKeepAliveInterval(60);
options.setConnectionTimeout(10);
options.setAutomaticReconnect(false);
options.setUserProperties(userProperties);
client.connect(options);
System.out.println("Connected to " + settings.tableName() + " (token " + fingerprint(token) + ")");
}
The fetchZerobusToken() function in the example's token.js file requests the token:
async function fetchZerobusToken(config, fetchImpl = fetch) {
const basic = Buffer.from(`${config.clientId}:${config.clientSecret}`).toString('base64');
const body = new URLSearchParams({
grant_type: 'client_credentials',
scope: 'all-apis',
resource: `api://databricks/workspaces/${config.workspaceId}/zerobusDirectWriteApi`,
authorization_details: JSON.stringify(authorizationDetails(config.tableName)),
});
const response = await fetchImpl(`${config.workspaceUrl}/oidc/v1/token`, {
method: 'POST',
headers: {
Authorization: `Basic ${basic}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
body,
signal: AbortSignal.timeout(30_000),
});
if (!response.ok) {
throw new Error(`Token request failed with HTTP ${response.status}`);
}
const json = await response.json();
return json.access_token;
}
The connectProperties() function in zerobus-mqtt.js builds the two User Properties from a token:
function connectProperties(token, tableName) {
return {
userProperties: {
Authorization: `Bearer ${token}`,
[TABLE_PROPERTY]: tableName,
},
};
}
The createZerobusConnection() function creates the MQTT.js client with automatic reconnect disabled. The reconnectPeriod option is 0, and manualConnect is true, so the client doesn't connect until the example has a token:
const client = connectFn({
protocol: 'mqtts',
host,
port: MQTT_PORT,
servername: host,
protocolVersion: 5,
clientId: `zerobus-mqttjs-${process.pid}-${Date.now()}`,
clean: true,
keepalive: 60,
reconnectPeriod: 0,
manualConnect: true,
connectTimeout: 30_000,
});
The connectWithFreshToken() function requests a token, sets client.options.properties, and then calls connect() the first time and reconnect() after that:
async function connectWithFreshToken() {
const token = await getToken();
// mqtt.js reads this object when it builds the next CONNECT packet.
client.options.properties = connectProperties(token, tableName);
if (firstConnect) {
firstConnect = false;
client.connect();
} else {
client.reconnect();
}
}
MQTT.js reads client.options.properties when it builds each CONNECT packet, so the token set here is the one that goes out. The client ID is set when the client is created, so each reconnect sends the same ID.
Publish records and track each PUBACK
- Python
- Java
- Node.js
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.
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)
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.
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))
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))
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.
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 publish() method sends one record at QoS 1 and waits for its PUBACK, up to 30 seconds. It returns only when the record is stored. It throws MqttException when the reason code is 0x80 (128, Unspecified error) or higher, or when no PUBACK arrives before the timeout:
void publish(String json) throws MqttException {
MqttMessage message = new MqttMessage(json.getBytes(StandardCharsets.UTF_8));
message.setQos(1);
MqttToken token = client.getTopic(settings.tableName()).publish(message);
token.waitForCompletion(PUBACK_TIMEOUT_MS);
int[] reasonCodes = token.getReasonCodes();
if (reasonCodes != null && reasonCodes.length > 0 && reasonCodes[0] >= PUBACK_ERROR_THRESHOLD) {
throw new MqttException(reasonCodes[0]);
}
}
MqttClient.publish() doesn't return a token. The method publishes through the topic object for the table name, which returns the token it waits on. Each record is acknowledged before the next one is sent, so the example has at most one record in flight.
The publish() function sends one record at QoS 1. It resolves when the PUBACK has a successful reason code. It rejects when the PUBACK has an error reason code, when the connection closes before the PUBACK arrives, or when the record doesn't finish within PUBLISH_ACK_TIMEOUT_MS, which is 30 seconds. That 30 seconds covers the wait for a connection and the wait for the PUBACK together:
function publish(record) {
const payload = typeof record === 'string' ? record : JSON.stringify(record);
return new Promise((resolve, reject) => {
const entry = { messageId: undefined, sent: false, resolve, reject, timer: null };
const send = () => {
if (pending !== entry) return; // timed out while it waited: never hand it to mqtt.js
entry.sent = true;
client.publish(tableName, payload, { qos: 1 }, (err) => {
// A late callback after a timeout or a close finds pending settled and is ignored.
if (pending !== entry) return;
clearTimeout(entry.timer);
pending = null;
if (err) reject(err);
else resolve();
});
};
pending = entry;
entry.timer = setTimeout(() => {
if (pending !== entry) return; // already settled
// Clear pending before removeOutgoingMessage: it calls the publish callback with an
// error, and that callback must find nothing to settle.
pending = null;
if (entry.sent) {
if (entry.messageId !== undefined) client.removeOutgoingMessage(entry.messageId);
reject(new Error(`no PUBACK within ${publishAckTimeoutMs} ms; the record was not acknowledged`));
} else {
connectWaiters = connectWaiters.filter((run) => run !== send);
reject(new Error(`no connection within ${publishAckTimeoutMs} ms; the record was not sent`));
}
}, publishAckTimeoutMs);
if (ready) send();
else connectWaiters.push(send);
});
}
If the connection is down, publish() holds the record until the next connection. It doesn't give the record to MQTT.js while the connection is down, because MQTT.js would queue it and send it after a reconnect, even though publish() had rejected it. A record whose timeout passes while it waits isn't sent.
If the record was sent and no PUBACK arrives within the timeout, publish() removes the record from MQTT.js and rejects. The connection stays open. A PUBACK that arrives after the timeout is ignored.
The loop in main.js awaits each publish() call, because the connection tracks one unacknowledged record. It logs a rejected record and moves on:
for (let i = 0; !stopping && (config.count === 0 || i < config.count); i += 1) {
const roll = nextRoll(i);
try {
await connection.publish(roll);
console.log(`PUBACK ${roll.player_name} rolled ${roll.roll} on a d${roll.die_sides}`);
} catch (err) {
console.log(`publish not acknowledged: ${err.message}`);
}
await sleep(config.intervalMs);
}
Each record is one JSON object. A JSON number for a TIMESTAMP column is epoch microseconds. The example's dice.js sends the roll time as now.getTime() * 1000.
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 |
| The server closes the connection with reason code |
A payload that isn't valid JSON |
| 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.
- Python
- Java
- Node.js
The reconnect() method drops the open connection and connects with a new token:
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:
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:
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:
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:
# 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.
The reconnect() method closes the connection if it's still open, and then calls connect(), which fetches a new token:
void reconnect() throws IOException, InterruptedException, MqttException {
if (client.isConnected()) {
client.disconnect();
}
connect();
}
The publishWithRetry() method publishes one record and makes up to three attempts. Before each new attempt, it reconnects with a new token. If all three attempts fail, the method throws, and the exception ends the run:
private static void publishWithRetry(ZerobusMqttPublisher publisher, String json, int record)
throws IOException, InterruptedException, MqttException {
for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
try {
publisher.publish(json);
System.out.println("Record " + record + " acknowledged (PUBACK)");
return;
} catch (MqttException e) {
System.out.println("Record " + record + " not acknowledged on attempt " + attempt
+ " (reason code " + e.getReasonCode() + ")");
if (attempt == MAX_ATTEMPTS) {
throw e;
}
System.out.println("Reconnecting with a new token; this record may be a duplicate if it was stored");
publisher.reconnect();
}
}
}
When the connection closes, the close handler rejects the record in flight, removes it from MQTT.js so the next connection doesn't resend it, and schedules a reconnect:
client.on('close', () => {
log('connection closed');
ready = false;
// A record that is still waiting for a connection stays waiting. It is sent on the next
// connection, or it times out.
if (pending && pending.sent) {
// Without this, mqtt.js would resend the record on the next connection.
const { reject, messageId, timer } = pending;
pending = null;
clearTimeout(timer);
if (messageId !== undefined) client.removeOutgoingMessage(messageId);
const reason = lastDisconnectReason === null ? '' : ` (server DISCONNECT reason ${lastDisconnectReason})`;
reject(new Error(`connection closed before PUBACK${reason}`));
}
scheduleReconnect();
});
The scheduleReconnect() function waits before it reconnects. The delay starts at 2 seconds and doubles after each attempt that doesn't connect, up to 30 seconds. Each attempt calls connectWithFreshToken(), so every reconnect sends a new token:
function scheduleReconnect() {
if (stopped || retryTimer) return;
const delay = Math.min(reconnectDelayMs * 2 ** attempt, maxReconnectDelayMs);
attempt += 1;
log(`reconnecting in ${delay} ms`);
retryTimer = setTimeout(async () => {
retryTimer = null;
try {
await connectWithFreshToken();
} catch (err) {
log(`token request failed: ${err.message}`);
scheduleReconnect();
}
}, delay);
}
The example's scheduleReconnect() timer reconnects with a new token, so your loop doesn't need to call a reconnect method.
Shut down cleanly
- Python
- Java
- Node.js
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:
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.
The close() method disconnects if the connection is open, and then closes the client:
public void close() throws MqttException {
if (client.isConnected()) {
client.disconnect();
}
client.close();
}
The simulator calls close() through a try-with-resources block, so it runs even when a publish throws. Each publish() returns only after its PUBACK, so no record is in flight at this point.
On SIGINT (Ctrl+C), the loop ends after the roll in progress. The example then calls close(), which stops the reconnect timer and ends the client:
function close() {
stopped = true;
clearTimeout(retryTimer);
return new Promise((resolve) => client.end(false, () => resolve()));
}
No record is in flight at that point, because the loop awaits each publish() call.
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.
- Python
- Java
- Node.js
Change to the src directory and publish 20 rolls:
cd src
python dice_roller.py --rolls 20 --interval 0.5
A successful run ends with a line like this:
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.
Build the simulator, which writes target/sensor-simulator.jar:
mvn -B package
Run it with the properties file:
java -jar target/sensor-simulator.jar config.properties
The output starts like this. The token fingerprint is the first bytes of a SHA-256 digest, so it identifies a token without revealing it:
Connected to <catalog>.<schema>.mqtt_paho_java (token sha256:<fingerprint>)
Record 1 acknowledged (PUBACK)
...
To see how the table handles records that don't match it, add --bad-records. The simulator sends three bad payloads, one time each without retries, and then one valid record. With the rescue column, all four go on the same connection:
java -jar target/sensor-simulator.jar config.properties --bad-records
From the example folder, start the simulator. ROLL_COUNT in config.env sets how many rolls to send, and 0 runs until you press Ctrl+C:
npm start
Each roll prints one line after its PUBACK. The output looks like this, with different rolls:
CONNACK success
PUBACK Ada rolled 5 on a d6
PUBACK Grace rolled 3 on a d6
Run the unit tests with npm test. They don't connect to the network:
npm test
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.
- Python
- Java
- Node.js
Rows with a value in rescue came from records that didn't match the table:
SELECT roll_id, sides, rescue FROM <catalog>.<schema>.dice_rolls WHERE rescue IS NOT NULL;
After a normal run, the row count matches the number of records that got a successful PUBACK:
SELECT count(*) FROM <catalog>.<schema>.mqtt_paho_java;
Each acknowledged record is one row. Rows with a value in rescue came from records that didn't match the table. To find them, filter the table with WHERE rescue IS NOT NULL. After a normal run, the row count matches the number of records that got a successful PUBACK.
Troubleshooting
The following table lists common symptoms, causes, and fixes:
Symptom | Cause | Fix |
|---|---|---|
| The | 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 | The table has no column tagged | 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. |
| 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 | Deduplicate by a unique ID in the table, such as |
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. | |
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 |
Node.js: a | A JSON number in a | Multiply epoch milliseconds by 1000, as |
Node.js: a publish rejects with | The connection didn't reconnect within 30 seconds. The reconnect can fail when the token request fails, or when outbound TLS to port | Read the |
Node.js: a reconnect sends the token from the previous connection. | The token was set after | Set |
Additional resources
-
- Use MQTT with Zerobus Ingest
- The endpoint, the authentication model, the acknowledgment rules, and the basic Python example.
-
- Zerobus rescue column
- How Zerobus Ingest routes fields that don't match the table.