> For the complete documentation index, see [llms.txt](https://crypto-chief.gitbook.io/chief-event-stream/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://crypto-chief.gitbook.io/chief-event-stream/sinks/clickhouse.md). Agents can also search and read this documentation through its [MCP server](https://crypto-chief.gitbook.io/chief-event-stream/~gitbook/mcp).

# ClickHouse

## ClickHouse

A `clickhouse` sink inserts each matched event into a ClickHouse table over HTTPS (`FORMAT JSONEachRow`) on port `443` or `8443`. Inserts are synchronous (`async_insert=0`, `wait_end_of_query=1`): a delivery is acknowledged only after ClickHouse reports the result of the write.

### Before you start

1. Expose ClickHouse's HTTPS interface on a publicly routable hostname or public IP on TCP port `443` or `8443` (such as ClickHouse Cloud `:8443` or self-hosted `https_port`). Native TCP ports (`9000`, `9440`) and plain HTTP (`8123`) are not supported. If your server certificate is signed by a private CA, pass the PEM bundle in `credentials.ca_certificate`.
2. Create `config.database` and `config.table` before you create the sink. EventStream never creates databases or tables.
   * Declare `subscription_id` as `String` rather than `UUID`: [`sinks/test`](#test-delivery) sends `""` for `subscription_id`.
   * Declare `event` as `String`. The event JSON is sent as an escaped JSON string inside `JSONEachRow`; read its fields with `JSONExtract*` functions.
   * `received_at` is sent as `YYYY-MM-DDTHH:MM:SS.sssZ`. EventStream sends each insert with `date_time_input_format=best_effort`, so a `DateTime64(3, 'UTC')` column accepts it without changes to the server settings. A non-empty `date_time_input_format` query parameter in `config.url` takes precedence:

```sql
CREATE TABLE analytics.eventstream_events
(
    event_id        String,
    subscription_id String,
    sequence        UInt64,
    received_at     DateTime64(3, 'UTC'),
    event           String
)
ENGINE = ReplacingMergeTree(received_at)
ORDER BY (event_id);
```

3. Configure a non-empty password for the ClickHouse user and grant `INSERT` on the target table:

```sql
GRANT INSERT ON analytics.eventstream_events TO es_ingester;
```

#### **Create a ClickHouse sink**

<mark style="color:green;">`POST`</mark> `https://api-eventstream.crypto-chief.com/v1/sinks/create`

**Headers**

| Name            | Value                                                                                                                        |
| --------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| Content-Type    | `application/json`                                                                                                           |
| Merchant        | Your Merchant ID                                                                                                             |
| X-CC-Timestamp  | Unix time in seconds                                                                                                         |
| X-CC-Nonce      | A new random value for every request                                                                                         |
| X-CC-Signature  | [Request signature](https://crypto-chief.gitbook.io/chief-event-stream/getting-started/authentication.md)                    |
| Idempotency-Key | **Required.** [Format](https://crypto-chief.gitbook.io/chief-event-stream/getting-started/authentication.md#idempotency-key) |

**Body**

Unknown fields return `400` `UNKNOWN_FIELD`.

| Name                             | Type    | Required    | Description                                                                                                                                                                                                                                                                                                                                |
| -------------------------------- | ------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `kind`                           | string  | true        | Must be `"clickhouse"`.                                                                                                                                                                                                                                                                                                                    |
| `config`                         | object  | true        | Configuration.                                                                                                                                                                                                                                                                                                                             |
| `config.url`                     | string  | true        | ClickHouse HTTPS URL (`^https://`, up to `2,048` characters, port `443` or `8443`, no `user:pass@` and no `#` fragment). Its path and query parameters are kept; EventStream sets `async_insert`, `wait_end_of_query`, `database`, and `query`, and adds `date_time_input_format=best_effort` when the URL does not set a non-empty value. |
| `config.database`                | string  | true        | Database identifier matching `^[A-Za-z_][A-Za-z0-9_]{0,62}$` (`1`–`63` characters).                                                                                                                                                                                                                                                        |
| `config.table`                   | string  | true        | Table identifier matching `^[A-Za-z_][A-Za-z0-9_]{0,62}$` (`1`–`63` characters, no `.` prefix).                                                                                                                                                                                                                                            |
| `config.label`                   | string  | false       | Optional display label, `0`–`100` characters. No default stored.                                                                                                                                                                                                                                                                           |
| `config.rate_per_second`         | integer | false       | Maximum deliveries per second for this sink, `1`–`20`. Default `20`.                                                                                                                                                                                                                                                                       |
| `config.enabled`                 | boolean | false       | Default `true`. With `false`, unsent deliveries stay `"queued"` and `status` stays `"active"`; see [`config.enabled`](https://crypto-chief.gitbook.io/chief-event-stream/api-reference/sinks.md#create-a-sink).                                                                                                                            |
| `credentials`                    | object  | true        | Write-only. Combined PEM size across `ca_certificate`, `client_certificate`, and `client_key` must not exceed `65,536` bytes (`64 KiB`). In `sinks/get`, `credentials_meta.username.last4` exposes the last `4` characters; `last4` is `null` on all other fields.                                                                         |
| `credentials.username`           | string  | true        | ClickHouse username sent in `X-ClickHouse-User` (non-empty after trimming whitespace, no `\r` or `\n`).                                                                                                                                                                                                                                    |
| `credentials.password`           | string  | true        | ClickHouse password sent in `X-ClickHouse-Key` (non-empty, no `\r` or `\n`).                                                                                                                                                                                                                                                               |
| `credentials.ca_certificate`     | string  | false       | Optional PEM `CERTIFICATE` bundle used to verify the ClickHouse server certificate instead of the public root store.                                                                                                                                                                                                                       |
| `credentials.client_certificate` | string  | conditional | Optional PEM X.509 client certificate for mTLS (`ExtKeyUsageClientAuth`, currently valid). Required when `client_key` is set.                                                                                                                                                                                                              |
| `credentials.client_key`         | string  | conditional | Optional unencrypted PEM private key matching `client_certificate`. Required when `client_certificate` is set.                                                                                                                                                                                                                             |

```json
{
  "kind": "clickhouse",
  "config": {
    "url": "https://ch.merchant.example:8443",
    "database": "analytics",
    "table": "eventstream_events",
    "label": "Analytics ClickHouse",
    "rate_per_second": 20
  },
  "credentials": {
    "username": "es_ingester",
    "password": "ExampleClickHousePassword_ChangeMe_2026!"
  }
}
```

**Response**

{% tabs %}
{% tab title="201" %}

```json
{
  "ok": true,
  "data": {
    "sink_id": "019a0000-0000-7000-8000-000000000001",
    "kind": "clickhouse",
    "status": "active",
    "secret": null,
    "secret_version": 0,
    "config": {
      "url": "https://ch.merchant.example:8443",
      "database": "analytics",
      "table": "eventstream_events",
      "label": "Analytics ClickHouse",
      "rate_per_second": 20
    }
  },
  "request_id": "019a0000-0000-7000-8000-000000000099"
}
```

{% endtab %}

{% tab title="422" %}

```json
{
  "ok": false,
  "error": "DESTINATION_FORBIDDEN",
  "msg": "destination is forbidden by egress policy",
  "request_id": "019a0000-0000-7000-8000-000000000099",
  "details": {
    "field": "config.url"
  }
}
```

{% endtab %}

{% tab title="429" %}

```json
{
  "ok": false,
  "error": "PROJECT_LIMIT_EXCEEDED",
  "msg": "sink limit reached",
  "request_id": "019a0000-0000-7000-8000-000000000099",
  "details": {}
}
```

{% endtab %}
{% endtabs %}

### What arrives

Each matched event is sent as an HTTP `POST` to `<config.url>` with the query parameters `async_insert=0`, `database=<database>`, `date_time_input_format=best_effort` (unless `config.url` sets it), `query=INSERT INTO "<database>"."<table>" FORMAT JSONEachRow`, and `wait_end_of_query=1`. The headers are `Content-Type: application/x-ndjson; charset=utf-8`, `User-Agent: CryptoChief-EventStream/1`, `X-ClickHouse-User`, and `X-ClickHouse-Key`. The body is one newline-terminated `JSONEachRow` object:

```json
{"event_id":"019a0000-0000-7000-8000-000000000011","subscription_id":"019a0000-0000-7000-8000-000000000003","sequence":42,"received_at":"2026-10-27T00:00:24.200Z","event":"{\"schema_version\":1,\"event_id\":\"019a0000-0000-7000-8000-000000000011\",\"project_id\":\"3f2a1b4c-5d6e-7f80-9a1b-2c3d4e5f6071\",\"subscription_id\":\"019a0000-0000-7000-8000-000000000003\",\"type\":\"transfer.token\",\"network\":\"ETH_MAINNET\",\"stage\":\"confirmed\",...}"}
```

| Field             | JSON Type | Value                                                                                                                                |
| ----------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `event_id`        | `string`  | Event UUIDv7 (`delivery_id` on `sinks/test`).                                                                                        |
| `subscription_id` | `string`  | Subscription UUIDv7 (`""` on `sinks/test`).                                                                                          |
| `sequence`        | `integer` | Event `sequence` (project-wide, unsigned 64-bit; `0` on `sinks/test`).                                                               |
| `received_at`     | `string`  | UTC attempt timestamp formatted as `YYYY-MM-DDTHH:MM:SS.sssZ`.                                                                       |
| `event`           | `string`  | JSON-encoded string containing the full [`Envelope`](https://crypto-chief.gitbook.io/chief-event-stream/webhooks/event-envelope.md). |

### Retries and errors

A delivery is acknowledged only when ClickHouse returns HTTP `200`, the `X-ClickHouse-Exception-Code` response header is empty, the response body does not contain `"DB::Exception"`, and the response body is at most `16 KiB`.

* **Retried (`transient`, up to `12` attempts over `24` hours):** network or DNS timeouts (`10`-second attempt limit), ClickHouse exception codes `159` (`TIMEOUT_EXCEEDED`), `202` (`TOO_MANY_SIMULTANEOUS_QUERIES`), `241` (`MEMORY_LIMIT_EXCEEDED`), `252` (`TOO_MANY_PARTS`), and `999` (`KEEPER_EXCEPTION`), mid-stream `DB::Exception` inside HTTP `200` (other than `UNKNOWN_TABLE`, `UNKNOWN_DATABASE`, or `AUTHENTICATION_FAILED`), response bodies interrupted or exceeding `16 KiB`, and HTTP `408`, `425`, `429`, `500`–`599` when no permanent ClickHouse exception code is present, with the schedule and `Retry-After` rules in [Retries and Ordering](https://crypto-chief.gitbook.io/chief-event-stream/webhooks/retries-and-ordering.md).
* **Permanent failures (no retries; delivery moves to `dead`):**
  * Non-public IP in DNS resolution, invalid or expired PEM in `credentials`, or TLS verification failure: pauses the **entire sink** with `pause_reason: "security_blocked"`.
  * ClickHouse exception codes `516` (`AUTHENTICATION_FAILED`), `497` (`ACCESS_DENIED`), `192` (`UNKNOWN_USER`), `60` (`UNKNOWN_TABLE`), `81` (`UNKNOWN_DATABASE`), `47` (`UNKNOWN_IDENTIFIER`), `53` (`TYPE_MISMATCH`), `62` (`SYNTAX_ERROR`), a response body containing `AUTHENTICATION_FAILED`, `UNKNOWN_TABLE`, or `UNKNOWN_DATABASE`, and HTTP `3xx` or `4xx` other than `408`, `425`, `429` (including `400` for a value a column cannot parse). The pause follows the HTTP status: `401`/`403` pause the **entire sink** with `"destination_auth"`, `404`/`410` with `"destination_gone"`, and `400`/`422` pause **only that lane** (`"destination_rejected"`). Any other status pauses the **entire sink** with `"destination_rejected"`.
* **How to resume:** create the database or table, grant `INSERT`, or fix the `config` / `credentials` value that caused the pause, then resume the sink as described in [Ordering, retries, and auto-pause](https://crypto-chief.gitbook.io/chief-event-stream/sinks/overview.md#ordering-retries-and-auto-pause).

### Duplicates

ClickHouse `INSERT` over HTTP appends rows and does not reject duplicate keys, so retries and [`deliveries/resend`](https://crypto-chief.gitbook.io/chief-event-stream/api-reference/deliveries.md) can add duplicate rows. Use `ENGINE = ReplacingMergeTree(received_at) ORDER BY (event_id)`: background merges collapse them. To deduplicate at read time before merges finish, query with `SELECT ... FROM <table> FINAL` or `argMax(..., received_at) GROUP BY event_id`.

### Test delivery

Calling [`sinks/test`](https://crypto-chief.gitbook.io/chief-event-stream/api-reference/sinks.md) with `{"sink_id": "<uuidv7>", "sample_type": "system.test"}` inserts `1` `JSONEachRow` line into `"<database>"."<table>"` with:

```json
{"event_id":"019a0000-0000-7000-8000-000000000002","subscription_id":"","sequence":0,"received_at":"2026-10-27T00:00:00.000Z","event":"{\"schema_version\":1,\"event_id\":\"019a0000-0000-7000-8000-000000000002\",\"project_id\":\"3f2a1b4c-5d6e-7f80-9a1b-2c3d4e5f6071\",\"type\":\"system.test\",\"is_test\":true,\"created_at\":\"2026-10-27T00:00:00.000Z\",\"payload\":{\"message\":\"EventStream test\",\"sink_id\":\"019a0000-0000-7000-8000-000000000001\",\"generated_at\":\"2026-10-27T00:00:00.000Z\"}}"}
```

### What it costs

ClickHouse deliveries have no channel fee (`0` credits, `$0`). Only the base event fee applies, and `sinks/test` costs `0` credits. See [Billing](https://crypto-chief.gitbook.io/chief-event-stream/getting-started/billing.md).

### Network access

Allow inbound traffic on the configured port in your ClickHouse IP access list or firewall; see [Network access](https://crypto-chief.gitbook.io/chief-event-stream/sinks/overview.md#network-access).

### Example

`request()` is defined in [Authentication](https://crypto-chief.gitbook.io/chief-event-stream/getting-started/authentication.md). Both `sinks/create` and `sinks/test` require an `Idempotency-Key`.

{% tabs %}
{% tab title="JavaScript" %}

```javascript
import crypto from "node:crypto";

const sink = await request(
  "sinks/create",
  {
    kind: "clickhouse",
    config: {
      url: "https://ch.merchant.example:8443",
      database: "analytics",
      table: "eventstream_events",
      label: "Analytics ClickHouse",
      rate_per_second: 20,
    },
    credentials: {
      username: "es_ingester",
      password: "ExampleClickHousePassword_ChangeMe_2026!",
    },
  },
  crypto.randomUUID()
);

const test = await request(
  "sinks/test",
  {
    sink_id: sink.sink_id,
    sample_type: "system.test",
  },
  crypto.randomUUID()
);

console.log(sink.sink_id, test.delivery_id);
```

{% endtab %}

{% tab title="PHP" %}

```php
$sink = request(
    'sinks/create',
    [
        'kind' => 'clickhouse',
        'config' => [
            'url'             => 'https://ch.merchant.example:8443',
            'database'        => 'analytics',
            'table'           => 'eventstream_events',
            'label'           => 'Analytics ClickHouse',
            'rate_per_second' => 20,
        ],
        'credentials' => [
            'username' => 'es_ingester',
            'password' => 'ExampleClickHousePassword_ChangeMe_2026!',
        ],
    ],
    bin2hex(random_bytes(16))
);

$test = request(
    'sinks/test',
    [
        'sink_id'     => $sink['sink_id'],
        'sample_type' => 'system.test',
    ],
    bin2hex(random_bytes(16))
);

echo $sink['sink_id'] . ' ' . $test['delivery_id'] . "\n";
```

{% endtab %}

{% tab title="GO" %}

```go
sink, err := request("sinks/create", map[string]any{
	"kind": "clickhouse",
	"config": map[string]any{
		"url":             "https://ch.merchant.example:8443",
		"database":        "analytics",
		"table":           "eventstream_events",
		"label":           "Analytics ClickHouse",
		"rate_per_second": 20,
	},
	"credentials": map[string]any{
		"username": "es_ingester",
		"password": "ExampleClickHousePassword_ChangeMe_2026!",
	},
}, rand.Text())
if err != nil {
	panic(err)
}

test, err := request("sinks/test", map[string]any{
	"sink_id":     sink["sink_id"],
	"sample_type": "system.test",
}, rand.Text())
if err != nil {
	panic(err)
}

fmt.Println(sink["sink_id"], test["delivery_id"])
```

{% endtab %}

{% tab title="Python" %}

```python
import secrets

sink = request(
    "sinks/create",
    {
        "kind": "clickhouse",
        "config": {
            "url": "https://ch.merchant.example:8443",
            "database": "analytics",
            "table": "eventstream_events",
            "label": "Analytics ClickHouse",
            "rate_per_second": 20,
        },
        "credentials": {
            "username": "es_ingester",
            "password": "ExampleClickHousePassword_ChangeMe_2026!",
        },
    },
    secrets.token_hex(16),
)

test = request(
    "sinks/test",
    {
        "sink_id": sink["sink_id"],
        "sample_type": "system.test",
    },
    secrets.token_hex(16),
)

print(sink["sink_id"], test["delivery_id"])
```

{% endtab %}

{% tab title="curl" %}

```bash
sink=$(request sinks/create \
  '{"kind":"clickhouse","config":{"url":"https://ch.merchant.example:8443","database":"analytics","table":"eventstream_events","label":"Analytics ClickHouse","rate_per_second":20},"credentials":{"username":"es_ingester","password":"ExampleClickHousePassword_ChangeMe_2026!"}}' \
  "$(openssl rand -hex 16)")

sink_id=$(jq -r '.sink_id' <<< "$sink")

request sinks/test \
  "{\"sink_id\":\"$sink_id\",\"sample_type\":\"system.test\"}" \
  "$(openssl rand -hex 16)"
```

{% endtab %}
{% endtabs %}
