# Connect PostgreSQL (/docs/guides/ingest/postgres-connector)



Connect PostgreSQL [#connect-postgresql]

Use a PostgreSQL connector to capture row changes from a PostgreSQL database and write them to RawTree tables.
The connector reads a publication through a logical replication slot with the `pgoutput` plugin.
It can copy the existing rows of each table before it streams inserts, updates, and deletes.
Each row contains the source columns plus `_rt_op`, `_rt_ts`, and `_rt_lsn`.
The connector runs in RawTree Cloud or RawTree BYOC where connector management is enabled.

Before you begin [#before-you-begin]

* Sign in as an organization administrator.
* Create the destination databases in RawTree. The connector creates the destination tables.
* For API requests, [find the destination cluster ID and routing headers](/docs/reference/authentication#user-sessions-and-oauth).
* Send the cluster ID in the `X-RawTree-Cluster-Id` header on API requests.
* If you used deployment and region headers to find the cluster, keep them on API requests.
* Use PostgreSQL 10 or newer. The initial load needs PostgreSQL 15 or newer.
* Prepare a reachable database host, a database name, and a user with a password.

RawTree accepts only publicly routable database addresses.
It refuses `localhost`, `.local` names, and hosts that resolve to loopback, link-local, private, or reserved addresses.
Allow connections from RawTree in your firewall, security group, or provider IP allowlist.

RawTree offers TLS on every connection and uses it when the server supports it.
It does not verify the server certificate. Custom CA certificates and client certificates are not supported.
Keep the database password out of shared files and shell history.

Create a PostgreSQL connector in the dashboard or through the API.
Use the dashboard to add destinations, edit batch settings, pause or resume ingestion, or delete the connector.
Use the API to change source connection settings or replace the destination list.

Prepare the database [#prepare-the-database]

Run these steps on the source database before you create the connector.
RawTree does not create the publication.

1. Set `wal_level` to `logical`, then restart the server.
   On Amazon RDS and Aurora, set `rds.logical_replication = 1` in the parameter group instead.

2. Create a dedicated user for RawTree:

   ```sql
   CREATE ROLE rawtree_cdc WITH LOGIN REPLICATION PASSWORD 'replace-with-a-secret';
   ```

   On Amazon RDS, run `GRANT rds_replication TO rawtree_cdc;` instead of the `REPLICATION` attribute.

3. Give the user read access to the tables. The initial load needs it:

   ```sql
   GRANT USAGE ON SCHEMA public TO rawtree_cdc;
   GRANT SELECT ON public.orders, public.customers TO rawtree_cdc;
   ```

4. Create a publication for the tables to capture:

   ```sql
   CREATE PUBLICATION rawtree_pub FOR TABLE public.orders, public.customers;
   ```

5. Make sure each published table has a primary key.
   For a table without one, set a replica identity:

   ```sql
   ALTER TABLE public.events REPLICA IDENTITY FULL;
   ```

While a table is published, PostgreSQL refuses `UPDATE` and `DELETE` on it when it has no primary key or replica identity.

To add a table later, run `ALTER PUBLICATION rawtree_pub ADD TABLE public.invoices;`.
Add the table to a connector destination too. The connector streams changes for it from that moment.

Provider notes [#provider-notes]

| Provider              | Notes                                                                                                                                   |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| Amazon RDS and Aurora | Set `rds.logical_replication = 1` and grant `rds_replication`. Databases that set `rds.force_ssl` work, because the connector uses TLS. |
| Supabase              | Use the direct connection host, not the connection pooler. Direct hosts can be IPv6-only.                                               |
| Neon                  | Use the direct, unpooled host.                                                                                                          |

Create a connector in the dashboard [#create-a-connector-in-the-dashboard]

1. Open **Connectors** in the destination cluster.
2. Select **New connector**.
3. Select **PostgreSQL**.
4. Enter the connection name and database connection details.
5. On the replication step, enter `rawtree_pub` in **Publication** and `rawtree_orders` in **Replication slot**.
6. If you want to use an existing slot, turn off **Create the slot if it does not exist**.
7. Select **Next** to check the database.
8. If a check blocks setup, fix the problem and select **Check again**.
9. Select the tables to capture.
10. Map the source tables to RawTree destinations.
11. To skip the initial load for a destination, turn off **Copy existing rows**.
12. Optional: Under **Delivery tuning**, set **Batch size** (default `1000`) and &#x2A;*Batch timeout (seconds)** (default `1`).
13. Review the connector settings.
14. Select **Start ingesting**.

To copy existing rows, keep **Create the slot if it does not exist** on and use a new slot name.
If the check cannot reach PostgreSQL, you can enter the source table names manually.

Check the connection [#check-the-connection]

Send a connection check before you create the connector.
Send `POST /v1/connectors/preview` to `https://api.rawtree.com` with the cluster ID in the `X-RawTree-Cluster-Id` header:

```json
{
  "type": "postgres",
  "operation": "check_connection",
  "settings": {
    "host": "db.example.com",
    "database": "app",
    "user": "rawtree_cdc",
    "password": "replace-with-a-secret",
    "publication": "rawtree_pub",
    "slot": "rawtree_orders"
  }
}
```

The response is a report, not an error. Each check has a `status` of `pass`, `warn`, or `fail` and a `message`:

```json
{
  "type": "postgres",
  "observed_at": "2026-11-16T10:00:00Z",
  "operation": "check_connection",
  "data": {
    "server_version": "16.4",
    "checks": [
      { "name": "connection", "status": "pass", "message": "Connected to app as rawtree_cdc." },
      { "name": "server_version", "status": "pass", "message": "PostgreSQL 16.4." },
      { "name": "wal_level", "status": "pass", "message": "wal_level is logical." },
      { "name": "replication_privilege", "status": "pass", "message": "rawtree_cdc can use replication." },
      { "name": "publication", "status": "pass", "message": "rawtree_pub publishes 2 tables." },
      { "name": "replication_slot", "status": "pass", "message": "Slot rawtree_orders does not exist yet and will be created." },
      { "name": "replica_identity", "status": "pass", "message": "Every published table identifies its rows." },
      { "name": "table_access", "status": "pass", "message": "rawtree_cdc can read every published table." }
    ],
    "tables": [
      { "name": "public.customers", "replica_identity": "default", "has_primary_key": true, "can_select": true },
      { "name": "public.orders", "replica_identity": "default", "has_primary_key": true, "can_select": true }
    ],
    "tables_truncated": false
  }
}
```

A `fail` identifies a problem to fix. A `warn` identifies a condition that can limit what the connector does.
When the connection fails, the report contains only the `connection` check.
The `tables` list shows up to 1,000 published tables. Use it to choose the source tables for each destination.

| Check                   | Fails when                                                                                                                                                 | Warns when                                                                    |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| `connection`            | The server is unreachable or refuses the user.                                                                                                             |                                                                               |
| `server_version`        | The server is older than PostgreSQL 10.                                                                                                                    | The server is older than PostgreSQL 15, so the initial load is not available. |
| `wal_level`             | `wal_level` is not `logical`.                                                                                                                              |                                                                               |
| `replication_privilege` | The user cannot use replication.                                                                                                                           |                                                                               |
| `publication`           | The publication does not exist.                                                                                                                            | The publication has no tables.                                                |
| `replication_slot`      | The slot is in use, is not a logical `pgoutput` slot, or belongs to another database. It also fails when the slot is missing and RawTree cannot create it. |                                                                               |
| `replica_identity`      |                                                                                                                                                            | A published table has no primary key or replica identity.                     |
| `table_access`          |                                                                                                                                                            | The user cannot read a published table, so the initial load cannot copy it.   |

To check a saved connector with its stored password, send `{ "operation": "check_connection" }` to `POST /v1/connectors/{connector_id}/preview`.

Create a connector through the API [#create-a-connector-through-the-api]

Send `POST /v1/connectors` to `https://api.rawtree.com` with the cluster ID in the `X-RawTree-Cluster-Id` header.
Use a user session or user OAuth token with `full_access`. Connector management does not accept API keys or workload tokens.

Set the connector `type` to `postgres`. This example writes two source tables to two RawTree tables in the existing `analytics` database:

```json
{
  "name": "app-cdc",
  "type": "postgres",
  "destinations": [
    {
      "postgres_tables": ["public.orders"],
      "initial_load": true,
      "database": "analytics",
      "table": "orders"
    },
    {
      "postgres_tables": ["customers"],
      "initial_load": false,
      "database": "analytics",
      "table": "customers"
    }
  ],
  "settings": {
    "host": "db.example.com",
    "port": 5432,
    "database": "app",
    "user": "rawtree_cdc",
    "password": "replace-with-a-secret",
    "publication": "rawtree_pub",
    "slot": "rawtree_orders",
    "create_slot_if_missing": true,
    "batch": {
      "max_events": 1000,
      "timeout_secs": 1
    }
  }
}
```

Before it saves the connector, RawTree checks that the publication exists and that no other consumer uses the slot.
When RawTree cannot reach the database, it still creates the connector. It then does not own the slot.

The API returns HTTP `201` with the connector, destination IDs, status, `slot_owned`, revision, and runtime state.
It encrypts the stored password and omits it from responses.
Save the connector `id` for later requests.

Connection settings [#connection-settings]

| Field                    | Type    | Required | Notes                                                                                                             |
| ------------------------ | ------- | -------- | ----------------------------------------------------------------------------------------------------------------- |
| `host`                   | string  | Yes      | Hostname or IP address, up to 255 characters. Must be publicly routable.                                          |
| `port`                   | integer | No       | 1–65535; default `5432`.                                                                                          |
| `database`               | string  | Yes      | 1–63 characters.                                                                                                  |
| `user`                   | string  | Yes      | 1–63 characters. The user needs replication permission.                                                           |
| `password`               | string  | Yes      | Write-only. Omit it on `PATCH` to keep the stored password.                                                       |
| `publication`            | string  | Yes      | An existing publication. Use an unquoted identifier: letters, digits, and underscores, not starting with a digit. |
| `slot`                   | string  | Yes      | 1–63 lowercase letters, digits, or underscores.                                                                   |
| `create_slot_if_missing` | boolean | No       | Default `true`. When `false`, the slot must already exist.                                                        |
| `batch.max_events`       | integer | No       | 1–100000; default `1000`.                                                                                         |
| `batch.timeout_secs`     | number  | No       | Greater than 0 and at most 60; default `1`.                                                                       |

Each connector reads one slot, and each slot has one consumer.
Use a different slot for each connector on the same database.

Destinations [#destinations]

Each destination sends one or more source tables to one RawTree table.

| Field             | Type             | Required | Notes                                                                                                                                   |
| ----------------- | ---------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `postgres_tables` | array of strings | Yes      | 1–100 source tables as `table` or `schema.table`. RawTree stores them as lowercase `schema.table`, with `public` as the default schema. |
| `initial_load`    | boolean          | No       | Copies the existing rows of these tables before it streams changes. See [Initial load](#initial-load).                                  |
| `database`        | string           | Yes      | RawTree database name.                                                                                                                  |
| `table`           | string           | Yes      | RawTree table name. The connector creates the table when it does not exist.                                                             |

Pass 1–32 destinations.
A source table can appear in only one destination of a connector.
Each database and table pair must be unique within the connector.
Use the published tables from the connection check. A destination table that the publication does not publish receives no rows.

Connect several databases [#connect-several-databases]

Each connector reads one PostgreSQL database through one slot and writes to one RawTree cluster.
To capture several databases, create a connector for each database.
You can put the connectors in the same RawTree cluster or in different clusters.
Within an organization, connectors cannot share the same host, port, database, and slot combination, even across clusters.

Use separate destination tables for different source databases.
WAL positions (`_rt_lsn`) from different PostgreSQL servers do not share an order.
The [latest-state query](#read-the-latest-state) assumes that all rows in the destination come from the same source table.

Initial load [#initial-load]

The initial load copies the existing rows of a destination's tables.
Then the connector streams the changes that follow, with no gap and no overlap.
Initial load rows have `_rt_op` set to `read`. All of them arrive before the first streamed change.

PostgreSQL exports the matching view of the tables only when it creates the slot.
Because of this, these rules apply:

* `initial_load` defaults to `true` for the destinations of a new connector.
* A new connector with an initial load always creates its slot. RawTree sets `create_slot_if_missing` to `true`.
* When the slot already exists, the connector streams from the slot position and copies no rows.
* A destination that you add to an existing connector streams changes only. It cannot request an initial load.
* An existing destination keeps the `initial_load` value that it had at creation.
* When you move a connector to a new slot, the connector loads the tables of its `initial_load` destinations again.

The initial load needs PostgreSQL 15 or newer and `SELECT` permission on each table.
When the load stops before it completes, the connector starts it again from the beginning.
To load the existing rows of only some tables, set `initial_load` to `false` on the other destinations.

Row format [#row-format]

The connector writes one row for each change. The source columns become top-level columns.
These columns describe the change:

| Column    | Value                                                                                            |
| --------- | ------------------------------------------------------------------------------------------------ |
| `_rt_op`  | `read` for an initial load row. `insert`, `update`, or `delete` for a streamed change.           |
| `_rt_ts`  | The commit time of the transaction. For an initial load row, the time that RawTree read the row. |
| `_rt_lsn` | The WAL position of the change, such as `16/B374D848`.                                           |

The connector decodes some PostgreSQL values into JSON numbers and booleans.
Other values retain PostgreSQL's text format. SQL `NULL` arrives as JSON `null`.
Initial load and streamed rows use the same conversion.

| PostgreSQL type                        | JSON value                                                                   |
| -------------------------------------- | ---------------------------------------------------------------------------- |
| `boolean`                              | `true` or `false`                                                            |
| `smallint`, `integer`, `bigint`, `oid` | A number, such as `42`                                                       |
| `real`, `double precision`             | A number, such as `1.5`. `NaN` and infinities stay strings.                  |
| `numeric`                              | A string, such as `"19.90"`, to preserve precision                           |
| `timestamptz`                          | A string in the server output format, such as `"2026-11-17 16:43:00.123+00"` |
| `json`, `jsonb`                        | A string containing JSON text, not a nested object                           |
| Arrays                                 | A string, such as `"{1,2,3}"`                                                |
| `bytea`                                | A string in the server output format                                         |

An `update` row contains the new values, except for unchanged TOAST columns, which PostgreSQL does not resend.
A `delete` row contains the old replica identity values, with `null` for other columns.
By default, the replica identity is the primary key. You can also use a replica identity index or `REPLICA IDENTITY FULL`.
With `REPLICA IDENTITY FULL`, a `delete` row contains the old values instead of only the identity columns.
The connector does not write rows for `TRUNCATE` or for transactions that roll back.

Schema changes [#schema-changes]

When PostgreSQL sends updated relation metadata, the connector uses the new column names and types to decode subsequent changes.
It does not rewrite earlier rows in RawTree.

Read the latest state [#read-the-latest-state]

Updates and deletes append change rows instead of modifying earlier rows in the destination.
To read the latest version of each row, group by the primary key.
Order the versions of a row by WAL position, with initial load rows first:

```sql test
SELECT
  id,
  argMax(status, version) AS latest_status,
  argMax(_rt_op, version) AS latest_op
FROM (
  SELECT
    id,
    status,
    _rt_op,
    tuple(
      _rt_op != 'read',
      reinterpretAsUInt64(reverse(unhex(concat(
        leftPad(splitByChar('/', toString(_rt_lsn))[1], 8, '0'),
        leftPad(splitByChar('/', toString(_rt_lsn))[2], 8, '0')
      ))))
    ) AS version
  FROM analytics.orders
)
GROUP BY id
HAVING latest_op != 'delete'
ORDER BY id;
```

The query converts `_rt_lsn` to a number, because the text form does not sort in WAL order.
Do not order versions by `_rt_ts`. Changes from one transaction share one commit time.
An initial load row can also have a later `_rt_ts` than a change that PostgreSQL committed during the load.

Verify ingestion [#verify-ingestion]

Insert a row in the source database:

```sql
INSERT INTO public.orders (id, status) VALUES (900001, 'connector_test');
```

Query the destination table to verify the change:

```sql test
SELECT id, status, _rt_op, _rt_ts
FROM analytics.orders
WHERE id = 900001
LIMIT 10;
```

The result should contain an `insert` row. Duplicates are possible because delivery is at least once.

Open the connector details in the dashboard to check its status and delivered-event metrics.
For API checks, read `GET /v1/connectors/{connector_id}` with the same `X-RawTree-Cluster-Id` header.
A `runtime.state` of `configured` confirms configuration publication, not successful delivery.
Use `GET /v1/metrics` for telemetry, as described in [Monitor usage](/docs/guides/operate/monitor-usage).
The `rawtree.connector.source.replication_lag_bytes` metric shows the WAL that the source server keeps for the slot.

Update, pause, resume, or delete [#update-pause-resume-or-delete]

In the dashboard, open the connector to use **Add destination**, **Pause ingestion**, or **Resume ingestion**.
Use **Connection details** to edit batch settings. Use **Connector actions** to delete the connector.

Send `PATCH /v1/connectors/{connector_id}` with the same `X-RawTree-Cluster-Id` header.
To pause the connector, use:

```json
{ "status": "paused" }
```

To resume it, use:

```json
{ "status": "active" }
```

Omitted settings and the password remain unchanged.
When you update destinations, include existing destination IDs to keep their identities.
The supplied destination list replaces the existing list.

The slot keeps its position while the connector is paused, so the connector resumes without data loss.
PostgreSQL keeps WAL for the slot during this time. Do not pause a connector for longer than the source disk can hold.

Send `DELETE /v1/connectors/{connector_id}` to remove the connector. The response contains `deleted: true`.
RawTree leaves the publication and the destination tables in place.

Paused clusters [#paused-clusters]

RawTree does not pause a cluster for inactivity while the cluster has an active connector.
A paused connector does not prevent the cluster from pausing for inactivity.
You can still pause the cluster yourself. The connector then retries delivery until you resume the cluster.
The slot keeps its position, so the connector delivers the waiting changes after the cluster resumes.

PostgreSQL keeps WAL for the slot while the cluster is paused.
Do not pause the cluster for longer than the source disk can hold.

If the source server sets `max_slot_wal_keep_size`, PostgreSQL invalidates the slot when the kept WAL exceeds that limit.
The connector cannot continue from an invalidated slot, and the changes after its last position are lost.
Before you pause the cluster for a long time, check the limit on the source server:

```sql
SHOW max_slot_wal_keep_size;
```

A value of `-1` means that PostgreSQL keeps all WAL for the slot.

Replication slot ownership [#replication-slot-ownership]

The `slot_owned` field shows whether RawTree created the slot and removes it later.
RawTree owns the slot only when the slot did not exist at creation and `create_slot_if_missing` was `true`.

When you delete the connector or move it to another slot, RawTree drops a slot that it owns.
It retries the drop until it succeeds.
RawTree never drops a slot that existed before the connector, or a slot that it could not verify at creation.

An unused slot makes PostgreSQL keep WAL until the disk fills.
When `slot_owned` is `false`, drop the slot yourself after you delete the connector:

```sql
SELECT pg_drop_replication_slot('rawtree_orders');
```

Delivery and retries [#delivery-and-retries]

The connector writes change events to a disk buffer.
It confirms a position to PostgreSQL after the events of that transaction enter the buffer.
The ingestion service then delivers them and retries retryable write failures.
A confirmed position does not mean that the row is already queryable.
A restart continues from the last confirmed position. Loss of the buffer storage can lose confirmed events that remain undelivered.

Troubleshoot setup [#troubleshoot-setup]

Setup errors return HTTP `400` with one of these messages:

| Message                                  | Action                                                                                                                                   |
| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `Invalid Postgres host.`                 | Use a publicly routable database address.                                                                                                |
| `Publication not found.`                 | Create the publication with `CREATE PUBLICATION`, then try again.                                                                        |
| `Replication slot in use.`               | Stop the other consumer, or choose a different slot name.                                                                                |
| `Duplicate connector destination table.` | Move each source table to only one destination.                                                                                          |
| `Invalid connector configuration.`       | Read the hint. For `initial_load is only available when the connector is created`, remove `initial_load: true` from the new destination. |

Connection check failures:

| Message                                 | Action                                                                |
| --------------------------------------- | --------------------------------------------------------------------- |
| `Could not resolve <host>.`             | Check the hostname and DNS.                                           |
| `Timed out connecting to <host>:<port>` | Allow connections from RawTree in the firewall or provider allowlist. |
| `Authentication failed for <user>.`     | Check the user and password.                                          |
| `The server refused <user>`             | Check `pg_hba.conf` or the provider's allowed IP addresses.           |
| `Database <database> does not exist.`   | Check the database name.                                              |

The connection check returns HTTP `503` when too many checks run at the same time. Try again later.
It returns HTTP `422` when the server does not return its settings in time.

If no rows arrive, check that the publication includes the table and that the destination lists it.
Check that the table has changes after the slot was created, or that its destination requested an initial load.
Check the connector metrics for write failures, buffer growth, and replication lag.
