> 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/postgres.md). Agents can also search and read this documentation through its [MCP server](https://crypto-chief.gitbook.io/chief-event-stream/~gitbook/mcp).

# PostgreSQL

## PostgreSQL

A `postgres` sink inserts each matched event as a row into a PostgreSQL table over TLS (`verify-full`) on port `5432` or `6432`.

### Before you start

1. Expose PostgreSQL (or PgBouncer configured with TLS and extended query protocol support) on a publicly routable hostname or public IP on TCP port `5432` or `6432`. TLS `1.2`+ with `verify-full` hostname verification against `config.host` is always required. If a private CA signed the server certificate, pass its PEM bundle in `credentials.ca_certificate`.
2. Configure `pg_hba.conf` (`hostssl`) for `scram-sha-256`, `password` (cleartext over verified TLS), or `cert` authentication. With `cert`, `credentials.password` is still required; any non-empty value works, and it is not sent. Legacy `md5` password authentication is not supported and fails permanently (`pg_auth_28000`).
3. Create `config.database` and `config.table` in the role's default schema (`search_path`, usually `public`) before you create the sink. EventStream never runs `CREATE TABLE`, and schema-qualified names such as `public.eventstream_events` are rejected. Add a `PRIMARY KEY` or unconditional `UNIQUE` constraint on `event_id`. Declare `subscription_id` as `TEXT`: [`sinks/test`](#test-delivery) inserts `""` for `subscription_id`, which a `UUID` column rejects. For example:

```sql
CREATE TABLE eventstream_events (
    event_id        TEXT        PRIMARY KEY,
    subscription_id TEXT        NOT NULL,
    sequence        BIGINT      NOT NULL,
    received_at     TIMESTAMPTZ NOT NULL,
    event           JSONB       NOT NULL
);
```

Other columns must be nullable or have defaults.

4. Grant `CONNECT` on the database, plus `INSERT` and `SELECT` on `event_id` on the table (PostgreSQL checks `SELECT` on the columns named in `ON CONFLICT (event_id)`):

```sql
GRANT CONNECT ON DATABASE analytics TO es_writer;
GRANT INSERT, SELECT (event_id) ON TABLE eventstream_events TO es_writer;
```

#### **Create a PostgreSQL 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 `"postgres"`.                                                                                                                                                                                                                                              |
| `config`                         | object  | true        | Configuration.                                                                                                                                                                                                                                                     |
| `config.host`                    | string  | true        | Publicly routable hostname or public IP literal (`1`–`253` characters, without scheme, `:port`, `@`, or `/`).                                                                                                                                                      |
| `config.port`                    | integer | false       | `5432` or `6432`. Default `5432` when omitted; the default is not added to the stored `config`.                                                                                                                                                                    |
| `config.database`                | string  | true        | Database identifier matching `^[A-Za-z_][A-Za-z0-9_]{0,62}$` (`1`–`63` characters).                                                                                                                                                                                |
| `config.table`                   | string  | true        | Unqualified table name matching `^[A-Za-z_][A-Za-z0-9_]{0,62}$` (`1`–`63` characters, no `.` schema prefix). It is sent as a quoted identifier and is case-sensitive: a table created without quotes is stored in lowercase.                                       |
| `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        | PostgreSQL role name (non-empty after trimming whitespace, no NUL bytes).                                                                                                                                                                                          |
| `credentials.password`           | string  | true        | PostgreSQL password (non-empty, no NUL bytes). SCRAM iteration counts up to `100,000` are accepted.                                                                                                                                                                |
| `credentials.ca_certificate`     | string  | false       | Optional PEM `CERTIFICATE` bundle used to verify the PostgreSQL server certificate instead of the public root store.                                                                                                                                               |
| `credentials.client_certificate` | string  | conditional | Optional PEM X.509 client certificate for mTLS (Extended Key Usage `clientAuth`, within its validity period). 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": "postgres",
  "config": {
    "host": "pg-ingest.merchant.example",
    "port": 5432,
    "database": "analytics",
    "table": "eventstream_events",
    "label": "Primary Analytics PG",
    "rate_per_second": 15
  },
  "credentials": {
    "username": "es_writer",
    "password": "ExamplePgPassword_ChangeMe_2026!"
  }
}
```

**Response**

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

```json
{
  "ok": true,
  "data": {
    "sink_id": "019a0000-0000-7000-8000-000000000001",
    "kind": "postgres",
    "status": "active",
    "secret": null,
    "secret_version": 0,
    "config": {
      "host": "pg-ingest.merchant.example",
      "port": 5432,
      "database": "analytics",
      "table": "eventstream_events",
      "label": "Primary Analytics PG",
      "rate_per_second": 15
    }
  },
  "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.host"
  }
}
```

{% 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

EventStream opens a PostgreSQL session with `application_name = "CryptoChief-EventStream"` and `client_encoding = "UTF8"`, then executes `1` parameterized statement per event:

```sql
INSERT INTO "eventstream_events" (event_id, subscription_id, sequence, received_at, event)
VALUES ($1, $2, $3, $4, $5::jsonb)
ON CONFLICT (event_id) DO NOTHING
```

All `5` parameters are sent in PostgreSQL text format:

| Parameter | Column            | Value                                                                                                                                         |
| --------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `$1`      | `event_id`        | Event UUIDv7 string (`delivery_id` on `sinks/test`).                                                                                          |
| `$2`      | `subscription_id` | Subscription UUIDv7 string (`""` on `sinks/test`).                                                                                            |
| `$3`      | `sequence`        | Base-10 integer string of the event `sequence` (`"0"` on `sinks/test`).                                                                       |
| `$4`      | `received_at`     | UTC attempt timestamp formatted as `YYYY-MM-DDTHH:MM:SS.sssZ` (for example, `"2026-10-27T00:00:24.200Z"`).                                    |
| `$5`      | `event`           | Full UTF-8 JSON [`Envelope`](https://crypto-chief.gitbook.io/chief-event-stream/webhooks/event-envelope.md), cast to `jsonb` via `$5::jsonb`. |

Each delivery opens a new TLS connection and closes it after the statement; a sink holds at most `2` connections at a time.

### Retries and errors

A delivery is acknowledged when the `INSERT` commits, including when `ON CONFLICT` skips an existing `event_id`. Each attempt has an `8`-second socket deadline within the `10`-second attempt timeout.

* **Retried (`transient`, up to `12` attempts over `24` hours):** TCP/DNS timeouts, SSL negotiation socket drops, SQLSTATE `40001` (`serialization_failure`), `40P01` (`deadlock_detected`), class `08*` (connection exceptions), class `53*` (such as `53300` `too_many_connections` and disk/memory exhaustion), and class `57*` (such as `57P03` `cannot_connect_now` during server restart). Any other SQLSTATE (for example `23502` from an extra `NOT NULL` column without a default, or `25006` when `config.host` is a read-only standby) and protocol errors are also retried, until the lane pauses with `paused_exhausted`. See [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, a server that does not accept TLS, invalid or expired PEM in `credentials`, or TLS `verify-full` handshake failure: pauses the **entire sink** with `pause_reason: "security_blocked"`.
  * SQLSTATE `28000` or `28P01` (invalid username/password, missing `pg_hba.conf` entry, or unsupported `md5` auth): pauses the **entire sink** with `pause_reason: "destination_rejected"`.
  * SQLSTATE `3D000` (database does not exist), class `42*` (`42P01` undefined table, `42703` undefined column, `42501` insufficient privilege, `42804` datatype mismatch, `42P10` missing `PRIMARY KEY` or `UNIQUE` constraint on `event_id`), or class `22*` (`22P02` invalid text representation): pauses the **entire sink** with `pause_reason: "destination_rejected"`.
* **How to resume:** create or alter the table, grant the privileges from step 4, 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

Retries and [`deliveries/resend`](https://crypto-chief.gitbook.io/chief-event-stream/api-reference/deliveries.md) insert the same `event_id`; the first row is kept.

### 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` row into `"<table>"` with:

* `event_id`: `<delivery_id>` (for example, `"019a0000-0000-7000-8000-000000000002"`)
* `subscription_id`: `""` (empty string)
* `sequence`: `0`
* `received_at`: UTC timestamp of the test attempt
* `event`: the [`system.test`](https://crypto-chief.gitbook.io/pages/X84VQ5lQlasjJZqaqw9H#system.test) JSON object (`is_test: true`, `type: "system.test"`)

### What it costs

PostgreSQL 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 connections on the configured port in your database firewall or security group; 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: "postgres",
    config: {
      host: "pg-ingest.merchant.example",
      port: 5432,
      database: "analytics",
      table: "eventstream_events",
      label: "Primary Analytics PG",
      rate_per_second: 15,
    },
    credentials: {
      username: "es_writer",
      password: "ExamplePgPassword_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' => 'postgres',
        'config' => [
            'host'            => 'pg-ingest.merchant.example',
            'port'            => 5432,
            'database'        => 'analytics',
            'table'           => 'eventstream_events',
            'label'           => 'Primary Analytics PG',
            'rate_per_second' => 15,
        ],
        'credentials' => [
            'username' => 'es_writer',
            'password' => 'ExamplePgPassword_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": "postgres",
	"config": map[string]any{
		"host":            "pg-ingest.merchant.example",
		"port":            5432,
		"database":        "analytics",
		"table":           "eventstream_events",
		"label":           "Primary Analytics PG",
		"rate_per_second": 15,
	},
	"credentials": map[string]any{
		"username": "es_writer",
		"password": "ExamplePgPassword_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": "postgres",
        "config": {
            "host": "pg-ingest.merchant.example",
            "port": 5432,
            "database": "analytics",
            "table": "eventstream_events",
            "label": "Primary Analytics PG",
            "rate_per_second": 15,
        },
        "credentials": {
            "username": "es_writer",
            "password": "ExamplePgPassword_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":"postgres","config":{"host":"pg-ingest.merchant.example","port":5432,"database":"analytics","table":"eventstream_events","label":"Primary Analytics PG","rate_per_second":15},"credentials":{"username":"es_writer","password":"ExamplePgPassword_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 %}
