# Capture Connection Acknowledge Event Topic Messages via Data Integration

The **Connection Acknowledge Event Topic** `$events/client_connack` is triggered whenever the server sends a `CONNACK` packet to a client. The `reason_code` field indicates whether the connection was successful and, if not, provides the specific failure reason, making it a key reference for diagnosing client connection issues. Although regular clients cannot directly subscribe to this topic, you can capture these event messages through the Rule Engine for further processing, such as writing them to a database, forwarding them to other topics, or enabling real-time monitoring and analysis.

Since EMQX Broker functions as an MQTT broker rather than a storage service, and due to security and privacy constraints, it does not store client historical state data or debug-level event logs by default. Therefore, it is recommended to configure **Data Integration rules** based on this event topic to gain real-time visibility into device connection status and to retain essential behavioral records, which are crucial for troubleshooting and audit analysis.

This page introduces the use cases of the connection acknowledgement event topic, demonstrates how to capture and process event messages through the Rule Engine, and shows how to use [MQTTX Desktop](https://mqttx.app/) to simulate receiving event messages from this topic.

## Use Cases

The connection acknowledgement event topic can be applied in various scenarios, including:

- **Diagnosing connection failures**: Capture and record the `reason_code` and other relevant fields to identify the cause of connection failures.
- **Monitoring device access quality**: Track connection attempts in real time, identify devices or regions with frequent failures, and optimize access configurations, network conditions, or authentication strategies.
- **Security auditing and access tracing**: Forward connection event data to external platforms to support security audits and compliance analysis.

## Trigger Conditions and Key Fields

### Connection Acknowledge Event (`$events/client_connack`)

- **Trigger condition**: Fired when the server sends a `CONNACK` packet to a client.
- **Key fields**:

| Field           | Description                                                  |
| --------------- | ------------------------------------------------------------ |
| reason_code     | Reason code indicating connection success or the cause of failure |
| clientid        | Client ID of the connecting client                           |
| username        | Username used during authentication                          |
| peername        | Client's IP address and port                                 |
| keepalive       | MQTT keepalive interval (heartbeat interval between client and broker) |
| clean_start     | MQTT `clean_start` flag (whether the client reuses a previous session) |
| expiry_interval | MQTT session expiry interval (how long the broker should retain the session after disconnection) |
| timestamp       | Timestamp (in milliseconds) when the event was triggered     |

::: tip

For the full list of fields in connection acknowledgement events, see the official documentation: [Data Source and Fields](../rule_engine/rule_engine_events.md#connection-acknowledge-event-events-client_connack).

:::

## Analyzing Connection Failure Scenarios

The `reason_code` field in the connection acknowledgement event provides detailed reasons for connection errors, helping you diagnose issues and optimize client logic.

In MQTT v3.1.1, the following reason codes are defined:

| Reason Code                    | Description                                                  |
| ------------------------------ | ------------------------------------------------------------ |
| connection_accepted            | The client was accepted and successfully connected.          |
| unacceptable_protocol_version  | The broker does not support the MQTT protocol version requested by the client. |
| client_identifier_not_valid    | Client ID is UTF-8 compliant but disallowed (e.g., Clean Start = 0 with an empty Client ID, or ID exceeds broker limits). |
| server_unavailable             | Network established, but the broker is temporarily unavailable (e.g., high system load, authentication backend issues). |
| malformed_username_or_password | Username or password is malformed (invalid characters, encoding errors, missing fields). |
| unauthorized_client            | The client is not authorized to connect due to invalid credentials or unauthorized operations. |

In MQTT 5.0, many more reason codes are available, allowing more granular failure diagnostics. Common examples include:

| Reason Code                   | Description                                                  |
| ----------------------------- | ------------------------------------------------------------ |
| success                       | The connection was successful.                               |
| unspecified_error             | An unspecified error not covered by other reason codes.      |
| malformed_packet              | The CONNECT packet was malformed (missing fields, invalid encoding). |
| protocol_error                | Protocol misuse or violation (e.g., sending multiple CONNECT packets). |
| implementation_specific_error | Packet is valid but rejected by the broker implementation.   |
| unacceptable_protocol_version | The broker does not support the client's protocol version.   |
| client_identifier_not_valid   | Client ID is UTF-8 compliant but disallowed by the broker.   |
| bad_username_or_password      | Invalid username or password.                                |
| not_authorized                | The client is not authorized (e.g., username not matched).   |
| server_unavailable            | The broker is temporarily unavailable.                       |
| server_busy                   | The broker is busy and cannot accept new connections.        |
| banned                        | The client is banned (e.g., abnormal behavior, blacklist).   |
| bad_authentication_method     | Authentication method not supported or changed during re-authentication. |
| topic_name_invalid            | Topic name is valid in format but rejected by the broker or client. |
| packet_too_large              | Packet size exceeds limits (e.g., oversized Will message).   |
| quota_exceeded                | Client exceeded the broker’s connection quota.               |
| retain_not_supported          | Broker does not support retained messages, but Will message was marked retain. |
| qos_not_supported             | Client requested a QoS level not supported by the broker.    |
| use_another_server            | Broker instructs the client to temporarily switch to another server. |
| server_moved                  | Broker instructs a permanent switch to another server.       |
| connection_rate_exceeded      | Connection rate exceeded broker limits (e.g., frequent reconnects). |

## Configure Data Integration to Capture Event Topic Messages

In practice, event topics are typically processed in one of two ways:

1. **Republishing messages**: Forward event messages to another MQTT topic. This is lightweight, real-time, and works seamlessly with the MQTT ecosystem.
2. **Forwarding to external services**: Send event messages to external systems such as databases, message queues, or HTTP services. This enables persistent storage and downstream integration.

This page demonstrates message republishing and forwarding to an HTTP service. For other integrations, refer to: [EMQX Cloud Data Integration](../data_integration/introduction.md).

### Republish Messages

This section shows how to republish connection acknowledgement event messages to another topic.

#### Create a Rule and Action

1. In the **Data Integration** page, under **Data Forward**, select **Republish**. If connectors already exist, click **Create Connector**, then choose **Republish**.

2. In the **SQL Editor**, define the rule SQL. To diagnose connection failures, you can use the following SQL:

   ```sql
   SELECT
       clientid,
       username,
       reason_code,
       timestamp
   FROM
       "$events/client_connack"
   ```

3. Click **Next** to add an action.

4. In the **New Action** step, configure:

   - **Connector**: Use the default `Republish`.

   - **Topic**: Set the target topic to `client_connack`.

   - **Payload**, **QoS**, **Retain**: Keep default values.

5. Click **Confirm** to complete.

#### Test the Rule and Action

It is recommended to use [MQTTX](https://mqttx.app/) to simulate client connections, though any MQTT client is acceptable.

1. Use MQTTX to connect to the deployment with ClientID `sub`.
2. Subscribe to the republished topic `client_connack`.
3. Create another connection `conn`. The `sub` client should receive:

```json
{
    "clientid": "conn",
    "username": "u_emqx",
    "reason_code": "success",
    "timestamp": 1645003578856
}
```

### Forward Event Topic Messages to an HTTP Service

This section demonstrates how to forward connection acknowledgement event messages to an HTTP service. Before starting, ensure you have created a [VPC Peering Connection](../deployments/vpc_peering.md) to access the connector via an internal IP address, or enabled a [NAT Gateway](../vas/nat-gateway.md) to access the connector via a public IP.

#### Create an HTTP Server Connector

1. In **Data Integration**, under **Web Service**, choose **HTTP Server**. If connectors already exist, click **Create Connector** and choose **HTTP Server**.

2. Enter the URL and adjust other settings as needed.

   The URL should point to the HTTP service that will receive the forwarded event messages. The connector will send POST requests to this URL using the payload defined in the rule.

3. Click **Test** to verify that EMQX can successfully reach the specified URL.

4. Click **New** to complete the connector creation.

#### Create a Rule and Action

1. Click **Create Rule** to start.

2. In the **SQL Editor**, define the SQL, such as:

   ```sql
   SELECT
       clientid,
       username,
       reason_code,
       timestamp
   FROM
       "$events/client_connack"
   ```

3. Click **Next** to create an action.

4. Select the previously created HTTP Server connector. Keep other settings default.

5. Click **Confirm** to complete the rule creation.

::: tip
For the full workflow of forwarding MQTT data to an HTTP service, see: [Ingest MQTT Data into HTTP Server](../data_integration/http_server.md).
:::

#### Test the Rule and Action

1. Use MQTTX to connect with ClientID `conn`.
2. The HTTP service should receive a POST request with a payload similar to:

```json
{
    "clientid": "conn",
    "username": "u_emqx",
    "reason_code": "success",
    "timestamp": 1645003578856
}
```