> ## Documentation Index
> Fetch the complete documentation index at: https://docs.rootkey.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# PostgreSQL Connector

> Protect the rows of PostgreSQL tables in ROOTKey with a self-hosted agent that sends every insert, update and delete as a versioned record — using a read-only role, or logical decoding for very large tables.

> [!NOTE]
>
> **Preview.** The PostgreSQL connector is available as a preview. It was verified against real PostgreSQL servers, versions 13 to 18; see [What was verified](#what-was-verified-and-what-was-not) before relying on it for managed services or cluster-managed failover.

## How It Works

The PostgreSQL connector protects **table rows**, not files. A small agent (a single container) runs **inside your network**, reads the tables you choose, and sends every new or changed row to ROOTKey as a **versioned record**. When a row is deleted in PostgreSQL, its record is **marked deleted** in ROOTKey — it is not removed at once: the record and its whole version history stay and it can be restored, until ROOTKey purges it permanently 3 years after the delete.

```
PostgreSQL                   ROOTKey agent (your network)             ROOTKey API
──────────                   ────────────────────────────             ───────────
  Row inserted,       →      Finds what changed                →      POST /api-v1/connectors/records
  updated or deleted         (table read or write-ahead log)          (Connector API Key,
  and committed              Sends only real changes                   batches of up to 100 records)
                             Remembers what was accepted
```

Unlike the cloud-storage connectors there is no Terraform module: a PostgreSQL database can be on-premises or on any cloud, so the connector is one container that runs wherever it can reach both the database and `api.rootkey.ai`. The source is public: [github.com/ROOT-Key/rootkey-connectors/tree/main/postgres](https://github.com/ROOT-Key/rootkey-connectors/tree/main/postgres).

> [!NOTE]
>
> ROOTKey's cyber resilience guarantee covers recovery — not just detection. A hash alone can tell you a row was tampered with; it cannot give you the row back. Each record therefore carries the row's column values, and every change becomes a new version of that record.

**One connector = one PostgreSQL table = one ROOTKey table.** Every table you protect has its own connector and its own Connector API Key. One agent can serve many tables of one database.

***

## Choosing a Capture Mode

The agent finds changes in one of two ways. You choose with a single setting, `CAPTURE_MODE`.

| | `scan` (default) | `logical` |
| - | - | - |
| **How changes are found** | Every cycle reads each table in primary-key order and compares each row with what was last sent. | Reads the write-ahead log (WAL) through a replication slot, then re-reads only the rows it names. |
| **Cost of a cycle** | One ordered pass over the whole table, whatever changed. | Proportional to the WAL written since the last cycle, by the whole database. Independent of table size. |
| **Changes and deletes reach ROOTKey** | Within one cycle (every 5 minutes by default). | Within one poll interval (10 seconds by default). |
| **Database role** | `CONNECT`, `USAGE` on the schema, `SELECT` on the protected tables. | The same, plus the `REPLICATION` attribute (on that role or on a second one). |
| **Database settings changed** | None. | `wal_level = logical` (a restart if not already set), a publication, one replication slot. |
| **Where it connects** | Primary or a hot standby. | The primary. |
| **Who has to approve it** | The owner of the tables. | Your DBA and, usually, your security team. |
| **Full table reads** | Every cycle. | First run only (and after `TRUNCATE`, a column change or a lost slot). |

> [!NOTE]
>
> Why `scan` reads the whole table: PostgreSQL keeps no per-row change stamp a reader can ask "what changed since?" of. `xmin` wraps around and says nothing about deleted rows; an `updated_at` column silently misses rows written by a transaction that was still open during the poll. Without the WAL, the only complete answer is to read and compare.

### `scan` — read-only, nothing to change

**Advantages**

* Needs only a read-only role. No server setting is touched, no restart, no object created in your database.
* Deletes are found by the same pass as changes, within one cycle.
* Can read from a hot standby, keeping the load off the primary.
* Running in minutes: create the role, start the container.
* The role can read the protected tables and nothing else.
* Each table is independent: a problem with one does not hold back the others.

**Disadvantages**

* Every cycle reads the whole table. On a table with hundreds of millions of rows this is the wrong mode.
* Latency is the cycle time: minutes, not seconds.

**Best for**

* Reference data, configuration, contracts, master data: tables up to a few million rows.
* Proofs of concept and first deployments.
* Databases where nothing may be changed, or where the `REPLICATION` attribute is not allowed.
* Managed services where enabling logical decoding would require a restart you cannot schedule yet.

### `logical` — for large and busy tables

**Advantages**

* The cost of a cycle follows what changed, not the size of the table. An idle cycle takes a few hundredths of a second.
* Changes and deletes reach ROOTKey within seconds.
* The table is read in full only once, on the first run.
* Uses PostgreSQL's built-in `pgoutput` plugin: nothing to install on the server.
* Reads the slot over an ordinary SQL connection — **no `replication` entry in `pg_hba.conf` is needed**.

**Disadvantages**

* **A replication slot retains WAL.** While the agent is stopped or cannot reach ROOTKey, PostgreSQL keeps every WAL segment the agent has not confirmed — without limit by default, until the disk is full. Set `max_slot_wal_keep_size`; see [Security and blast radius](#security-and-blast-radius).
* Requires `wal_level = logical` — a restart if it is not already set — and the `REPLICATION` attribute.
* Decoding runs in the database and covers the WAL of the **whole database**, not only the protected tables. A database that writes heavily elsewhere costs decoding time even when nothing protected changed.
* The first run still reads and sends every row, and this mode does not make that faster. The initial load is bounded by the ROOTKey API, not by PostgreSQL. ROOTKey stores each request of up to 100 records in a single database transaction. In a local test of the API alone (one stream of 100-record requests against a local PostgreSQL 16, with no agent and no network in between) it stored about 1,100–1,200 new or changed rows per second. At that rate the API alone needs about 15 minutes per million rows and about a day per 100 million rows. This is a measurement on one test machine, not a guarantee for production: real throughput depends on your hardware, your network and the width of your rows, and the time the agent needs to read the rows and the round trip to ROOTKey come on top. We have not yet measured a complete initial load through an agent with this version of the API; the previous figure, measured end to end when ROOTKey stored records one at a time, was 50–90 rows per second per agent. Plan the initial load of a very large table with your account team before starting. After the initial load only changed rows are sent.
* The agent keeps one small entry per protected row on local disk: about **140 bytes per row, roughly 14 GB for 100 million rows**.
* One failing table stops the cycle for all tables of that agent: the slot is a single stream with a single position.
* Must connect to the primary, directly or through PgBouncer in session mode.

**Best for**

* Orders, ledgers, events, audit tables: large tables that are cheap to follow in this mode once loaded. It does not shorten the first load; see the limit above.
* Any table where a change must be reflected within seconds.
* Databases that already run with `wal_level = logical`.

### Quick decision guide

| Your situation | Use |
| - | - |
| Table under a few million rows, minutes of delay are fine | `scan` |
| Nothing may be changed in the database, or `REPLICATION` is not allowed | `scan` |
| You want to read from a standby | `scan` |
| Table with tens of millions of rows or more | `logical` |
| Changes must appear within seconds | `logical` |
| Trying the connector for the first time | `scan`, then switch |

***

## Security and Blast Radius

The agent **never writes to your tables** in either mode. What differs is what the role can read, and what it can cost operationally. This section states both plainly, with the controls for each.

### What each role can do

| | `scan` role | `logical` role (`REPLICATION`) |
| - | - | - |
| Insert, update, delete, DDL on your tables | No | No |
| Read tables | Only the tables you grant | Only the tables you grant (`REPLICATION` grants no `SELECT`) |
| Read the WAL | No | Yes. The agent decodes only the tables in the publication, but the attribute itself lets a role decode the changes of any table in the database |
| Create and drop replication slots | No | Yes |
| Operational impact | A table pass per cycle | Decoding CPU per cycle; **WAL retained on disk while the agent is behind** |

### Controls for `logical` mode

* **Bound the WAL the slot may retain.** This is the one operational risk that matters, and one setting removes it:

  ```sql theme={null}
  ALTER SYSTEM SET max_slot_wal_keep_size = '20GB';
  SELECT pg_reload_conf();
  ```

  Beyond that budget PostgreSQL invalidates the slot instead of filling the disk. The agent notices, creates a new slot and reads the tables again: a slower catch-up instead of an outage.

* **Monitor the slot**, and alert on `retained`:

  ```sql theme={null}
  SELECT slot_name, active, wal_status,
         pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained
    FROM pg_replication_slots;
  ```

* **No `replication` line in `pg_hba.conf`.** The agent does not use the replication protocol, so do not add one for its role. Without it, the role cannot open a replication connection and therefore cannot take a physical copy of the cluster.

* **Your DBA owns the publication.** The agent never creates or alters it, and refuses to run when a configured table is missing from it.

* **Separate the duties** if you prefer: a second role with `REPLICATION` and no table privilege (`POSTGRES_REPLICATION_USER`), next to a reading role without `REPLICATION`.

* **Drop the slot when you retire the connector.** An abandoned slot retains WAL forever.

### Controls that apply to both modes

* **The agent runs in your infrastructure.** Database credentials never leave it. ROOTKey has no access to your database and never receives a credential.
* **Restrict the role in `pg_hba.conf`** to the agent's address and the one database, over TLS. The agent verifies the server certificate by default (`POSTGRES_SSL_MODE=verify-full`).
* **Limit and audit the role**: `ALTER ROLE … CONNECTION LIMIT`, a `statement_timeout`, and `log_connections` or pgAudit for a record of what it did. Its sessions carry `application_name = 'rootkey-postgres-connector'`.
* **Row-level security applies.** The agent protects exactly the rows its role's policies let it see.
* **Close the egress.** The agent needs exactly one outbound destination: the ROOTKey API over HTTPS. With egress limited to it, even a compromised agent has nowhere else to send data.
* **Only what you list leaves.** Only the rows of the configured tables are sent. Columns named in `excludeColumns` are left out of the query itself, not filtered afterwards.
* **One API key per table.** A Connector API Key can only write records into its own ROOTKey table. It cannot read anything and cannot call any other endpoint.
* **Hardened container.** The example deployment runs as a non-root user with a read-only filesystem and secrets mounted as files.
* **Open source.** The agent's code is public and can be audited before it is deployed.

> [!TIP]
>
> If your security policy cannot accept a role with `REPLICATION`, use `scan`. You trade seconds of latency and efficiency on large tables for a strictly read-only, table-scoped role.

***

## Deletes

A delete is sent as its own operation and ROOTKey **marks the record deleted**. The record and its history remain and can be restored; ROOTKey purges a deleted record permanently 3 years after the delete. If the same key is inserted again later, it becomes a new live record next to the deleted one.

* In `scan` mode, every row read is stamped; the rows ROOTKey holds that were not stamped by a completed pass are gone, and a delete is sent for each. A pass that fails half-way never produces a delete.
* In `logical` mode, each `DELETE` is read from the WAL and sent within one poll interval.
* An `UPDATE` that changes a primary-key value marks the old key deleted and creates the new one.

### Mass-delete safety valve

A table that suddenly lost a large share of its rows is far more often an accident — a `TRUNCATE`, a failed load, a configuration pointing at the wrong schema — than an intent to delete them, and ROOTKey is the recovery copy for exactly that case.

If a full scan finds more than `MAX_DELETE_PERCENT` (default **20**) of a table's known rows missing, the agent sends **no** delete, logs `rootkey.postgres.mass_delete_suspected` and carries on; new and changed rows are still delivered. To confirm the deletions, set `MAX_DELETE_PERCENT=100` and restart the agent. Tables with fewer than 100 known rows are exempt.

The valve applies to deletions *inferred* by a full scan: every cycle in `scan` mode; in `logical` mode the re-read after a `TRUNCATE`, a lost slot or a column change. Individual `DELETE` statements read from the WAL are facts and are always sent.

***

## Prerequisites

* PostgreSQL **13 or later** (verified on 13, 14, 15, 16, 17 and 18).
* A ROOTKey **table** to receive the records, and one connector per PostgreSQL table, created in the dashboard.
* Network access from the agent to PostgreSQL and, outbound over HTTPS, to the ROOTKey API.
* A direct connection, or PgBouncer in **session** mode. PgBouncer in transaction or statement mode is **not supported**; see [Limitations](#limitations).
* Docker, or Node.js 22.13 or later to run the agent directly.
* A persistent local disk for the agent's state (about 140 bytes per protected row). Prefer a local SSD over network storage.
* A primary key on each table, or a set of `NOT NULL` columns that uniquely identifies a row.

For `logical` mode, additionally:

* A connection to the **primary**.
* `wal_level = logical`, with one free replication slot. On managed services this is a parameter: `rds.logical_replication = 1` (Amazon RDS / Aurora), `cloudsql.logical_decoding = on` (Cloud SQL).
* The `REPLICATION` attribute on the connector role or on a second role (on Amazon RDS: `GRANT rds_replication`).
* A publication containing every protected table, publishing `insert, update, delete, truncate`, with `publish_via_partition_root = true` if any table is partitioned.
* A primary key or `REPLICA IDENTITY FULL` on every table.
* `max_slot_wal_keep_size` set to a deliberate value. The agent does not check it; we strongly recommend it.

The server setting, the publication and each table's identity are checked at the start of every cycle. If one is missing the agent delivers nothing, creates no slot, and logs the statement that fixes it.

***

## Setup

**1. Create the ROOTKey table and the connector**

In the ROOTKey dashboard, create (or choose) a **table** for each PostgreSQL table you want to protect, then create a **PostgreSQL** connector that points at it. Copy the **Connector API Key** — it is shown only once.

**2. Create the database role**

Edit the password, database and table list in [`sql/create-connector-user.sql`](https://github.com/ROOT-Key/rootkey-connectors/blob/main/postgres/sql/create-connector-user.sql) and run it as a superuser or as the tables' owner.

For `logical` mode, also work through [`sql/create-replication-user.sql`](https://github.com/ROOT-Key/rootkey-connectors/blob/main/postgres/sql/create-replication-user.sql) with your DBA. Read it before running: unlike the default mode, it relies on a server setting and creates a publication in your database.

**3. Store the secrets as files**

```bash theme={null}
mkdir -p secrets && chmod 700 secrets
```

One key file per table:

```bash theme={null}
printf '%s' 'rk_conn_xxxxxxxxxxxxxxxxxxxx' > secrets/key_public_orders
```

```bash theme={null}
printf '%s' 'the-database-password' > secrets/postgres_password
```

```bash theme={null}
chmod 644 secrets/*
```

The agent runs as an unprivileged user inside the container (uid 1000) and has to read these files, so they are `644`; the `secrets` directory stays `700`, which is what keeps other users of the host away from them. With `600` the agent stops with `EACCES: permission denied` unless your own uid happens to be 1000.

Then list every file you created under `secrets:` in `docker-compose.example.yml`, in both places: the service's `secrets:` list and the top-level `secrets:` block. The example file ships with sample names (`key_public_orders`, `postgres_password`); a secret that is not listed there is not mounted, and the agent refuses to start because it cannot read the key.

> [!TIP]
>
> If you created the connector in the dashboard, its **Deploy** step gives you these commands ready to copy. They ask for the key at a prompt instead of taking it on the command line, so it stays out of your shell history, and they name the key file after the table plus the end of the connector's id (for example `key_public_orders_1a2b3c4d`). Use that file name in the compose file and in the `.env` lines the same step shows.

**4. Configure the agent**

Copy `.env.example` to `.env` and set at least the connection, the tables and the capture mode:

```bash theme={null}
POSTGRES_HOST=db.example.com
POSTGRES_DATABASE=appdb
POSTGRES_USER=rootkey_connector
POSTGRES_PASSWORD_FILE=/run/secrets/postgres_password
POSTGRES_TABLES=[{"schema":"public","table":"orders","apiKeyFile":"/run/secrets/key_public_orders"}]
CAPTURE_MODE=scan
```

**5. Start it**

```bash theme={null}
docker compose -f docker-compose.example.yml up -d --build
```

Pin the checkout to a release tag before building, so that two deployments a week apart run the same code.

**6. Verify**

Change a row in a protected table:

```sql theme={null}
UPDATE public.orders SET amount = amount + 1 WHERE id = 1042;
```

Within one poll interval the agent logs a `Synced public.orders … sent=1` line and a new version of record `1042` appears in ROOTKey.

***

## Configuration

| Variable | Required | Default | Description |
| - | - | - | - |
| `POSTGRES_HOST` | Yes | — | Host name of the server (`logical` mode: the primary). |
| `POSTGRES_PORT` | No | `5432` | Port of the server. |
| `POSTGRES_DATABASE` | Yes | — | The database that holds the tables. One agent serves one database. |
| `POSTGRES_USER` | Yes | — | The connector's database role. |
| `POSTGRES_PASSWORD` / `POSTGRES_PASSWORD_FILE` | Yes | — | Its password, or the path of a file containing it. |
| `POSTGRES_SSL_MODE` | No | `verify-full` | `verify-full`: TLS, verifying certificate and host name. `require`: TLS without verification. `disable`: no TLS. |
| `POSTGRES_SSL_CA_FILE` | No | System CAs | PEM file of the CA that signed the server certificate. |
| `POSTGRES_TABLES` | Yes | — | Tables to protect, each with its Connector API Key. See below. |
| `CAPTURE_MODE` | No | `scan` | `scan` or `logical`. |
| `REPLICATION_SLOT` | No | `rootkey_connector` | `logical`: name of the replication slot. The agent creates it. |
| `PUBLICATION` | No | `rootkey_connector` | `logical`: name of the publication your DBA created. |
| `POSTGRES_REPLICATION_USER`, `POSTGRES_REPLICATION_PASSWORD` / `_FILE` | No | The main role | `logical`: role used for the slot, when the reading role must not have `REPLICATION`. |
| `ROOTKEY_API_URL` | No | `https://api.rootkey.ai` | ROOTKey API base URL. Must use `https://`. |
| `POLL_INTERVAL_SECONDS` | No | `300` (`scan`), `10` (`logical`) | Pause between two cycles (5–86400). |
| `FULL_SCAN_INTERVAL_MINUTES` | No | `0` | `logical` only: how often to compare every row again as a safety net. `0` = never. |
| `MAX_DELETE_PERCENT` | No | `20` | A full scan that finds more than this share of a table missing sends no delete. `100` disables the check. |
| `BATCH_SIZE` | No | `100` | Maximum records per request (1–100). |
| `STATE_DIR` | No | `/var/lib/rootkey-postgres` | Where hashes, the slot position and the dead-letter file are kept. Must be persistent. |
| `POSTGRES_DATABASE_LABEL` | No | Database name | Name of this database as ROOTKey sees it. Do not change it afterwards. |

`POSTGRES_TABLES` is JSON, one entry per table, with names used exactly as written:

```json theme={null}
[
  { "schema": "public",  "table": "orders", "apiKeyFile": "/run/secrets/key_public_orders",  "excludeColumns": ["card_token"] },
  { "schema": "billing", "table": "ledger", "apiKeyFile": "/run/secrets/key_billing_ledger", "keyColumns": ["book", "entry_no"] }
]
```

| Field | Meaning |
| - | - |
| `apiKeyFile` | Path of a file holding the Connector API Key of this table's connector. The agent refuses to start when a table has no key or two tables share one, and never logs a key. |
| `excludeColumns` | Columns that must never leave the database. They are left out of the query itself. |
| `keyColumns` | The `NOT NULL` columns that uniquely identify a row, for tables with no `PRIMARY KEY`. They should be backed by a unique index. |

For a single table there is a short form, with the key in `ROOTKEY_API_KEY_FILE`:

```bash theme={null}
POSTGRES_TABLES=public.orders
ROOTKEY_API_KEY_FILE=/run/secrets/key_public_orders
```

The full reference is in the [repository README](https://github.com/ROOT-Key/rootkey-connectors/tree/main/postgres#configuration).

***

## Reliability

* **At-least-once, no gaps.** If anything fails — database unreachable, API down, agent killed mid-cycle — nothing is confirmed and the next cycle starts from the same place.
* **Idempotent.** A row re-sent with the same content is a no-op in ROOTKey, and so is a delete of a key that is unknown or already deleted. Replaying a batch changes nothing.
* **A request is all-or-nothing.** ROOTKey applies the records of a request in one transaction. If it refuses the request (`400` for an invalid record, naming its position in the request; `429` quota; `410` table deleted or paused; `503` lock wait), nothing of that request is stored, and the same request can be sent again as it is. Each record still gets its own version and its own audit entries.
* **A rejected record does not block the table.** The agent splits a refused batch in half, again and again, to isolate the record ROOTKey will not take, delivers the rest, and writes the rejected one to a dead-letter file.
* **A lost slot is repaired, not ignored** (`logical`). If the slot is gone, was invalidated by `max_slot_wal_keep_size`, or was re-created by someone else, the agent logs `rootkey.postgres.replication_gap`, creates a fresh slot, reads every table again and resumes.
* **A failover costs one full read, unless the slot survives it** (`logical`). The slot the agent creates exists on the primary only: after a promotion the agent reports `rootkey.postgres.replication_gap`, creates a new slot on the new primary and reads every table again. Nothing is lost; rows are compared and only differences are sent. On PostgreSQL 17 or later you can avoid the full read by creating the slot yourself, before the agent's first run, as a failover slot (`SELECT pg_create_logical_replication_slot('rootkey_connector', 'pgoutput', false, false, true);`) with slot synchronisation configured on the standby. In every case the standby must run with `wal_level = logical`.
* **The slot only moves after ROOTKey accepted the records.** A failure between delivery and confirmation re-reads the same WAL and sends nothing twice.
* **A fresh connection per cycle.** Database restarts and firewall idle timeouts need no handling.

***

## Limitations

* **Intermediate versions can be skipped.** If a row changes three times between two cycles, ROOTKey receives the last state only, in both modes. A row inserted and deleted between two cycles is never sent. Lower `POLL_INTERVAL_SECONDS` for finer granularity.
* **No transaction-mode pooling.** The agent pins its session settings after connecting, and PgBouncer in transaction (or statement) mode hands each statement to whichever server connection is free without carrying all of them over. Records are then sent with the wrong rendering: in our test the agent sent about twice the versions a directly connected agent sent, the same rows flipping between two renderings. A short trial may not show it. Use a direct connection or session mode.
* **Tables only.** Views, materialized views and foreign tables are refused. Unlogged tables work in `scan` mode only.
* **Partitioned tables** are protected as one table, under the name of the partitioned table.
* **One database per agent, one agent per state directory.**
* **Limits of a record.** A row beyond them is written to the dead-letter file, never truncated:
  * at most **100 columns** (list the ones to leave out in `excludeColumns`);
  * at most **65,536 bytes in any single value** — a `text` or `jsonb` value above 64 KB, or a `bytea` above about 32 KB;
  * at most **1 MB** for the whole record.
* **Limit of a request.** The API refuses a request larger than 5 MB (`413`), whatever the number of records in it. The agent keeps its requests below that and splits a batch by itself, so there is nothing to configure; with very wide rows, expect fewer than 100 records per request.
* **A schema change re-versions the table.** Adding, dropping, renaming or retyping a column changes every row, so every row is sent once more as a new version.
* **Do not change the key of a protected table.** ROOTKey identifies a record by its key; changing `keyColumns` would make every row a new record.
* **Usage and initial load.** Every stored version counts towards your plan's records quota, and every request towards its API quota. The initial load of a large table can take many hours or days, depending on your hardware and network (see the estimate and its limits under Capture modes above), so plan it with your account team before starting.

### Columns that are not sent

The agent sends a column only if it can render its value as text in a form that is the same in every session and on every server. In every case below **the rest of the row is still protected**, and the agent logs `rootkey.postgres.column_skipped` with the column's name.

| Column type | Why it is not sent |
| - | - |
| Composite (row) types, and arrays of them | Their text form nests the output of other types without a fixed contract. |
| Types from extensions or user-defined base types (PostGIS `geometry`, `vector`, …), other than `citext`, `ltree`, `hstore` | The output format belongs to the extension and may change between its versions. |
| `regclass` and other `reg*` types, `xid`, `tid`, `aclitem` | Internal identifiers whose rendering depends on the session or the database. |
| Arrays of `money`, ranges of user-defined types | Rendered with the server's locale or by code outside PostgreSQL's core. |
| Any column whose name is reserved by ROOTKey: it starts with `__`, contains `constructor`, or is exactly `prototype`, `eval`, `Function`, `setTimeout` or `setInterval` (case-sensitive) | A record cannot carry a field with such a name; the API refuses it. The agent leaves the column out so that the rest of the row is still protected, and logs `rootkey.postgres.column_skipped` with `reason=reserved_name`. |

If the content of such a column must be protected, expose it in a supported type — for a geometry, for example, a generated column holding `ST_AsEWKT(geom)`.

`jsonb`, `json`, arrays, enums, ranges, `uuid`, `bytea`, network and date/time types **are** sent. Values are rendered inside the database with pinned session settings (UTC, ISO dates), so a record does not depend on the server's locale or time zone.

***

## Observability

The agent logs to stdout/stderr. Use these **stable log markers** for alerting:

| Marker | Meaning | Suggested alert |
| - | - | - |
| `rootkey.connector.fatal` | ROOTKey refused the connector (wrong key, table deleted or paused), or the agent could not start. | Any occurrence → page. |
| `rootkey.postgres.cycle_failed` | The agent could not connect to the database, or a `logical` cycle failed. | More than a few in a row. **In `logical` mode a failing agent means WAL is being retained.** |
| `rootkey.postgres.table_failed` | `scan`: one table could not be synced. Other tables continue. | Any occurrence. |
| `rootkey.record.dead_letter` | A record was rejected for good or exceeds the size limits. | Any occurrence. |
| `rootkey.postgres.mass_delete_suspected` | A full scan found more than `MAX_DELETE_PERCENT` of a table missing. **No delete was sent.** | Any occurrence → a person decides. |
| `rootkey.postgres.replication_gap` | The slot is gone, invalidated, or not where the agent left it. Tables are being read again. | Any occurrence — check `max_slot_wal_keep_size`. |
| `rootkey.postgres.table_truncated` | A `TRUNCATE` of a protected table was read from the WAL. | Review. |
| `rootkey.postgres.schema_changed` | `logical`: the columns or key of a table changed. The table is being read again. | Review if unexpected. |
| `rootkey.postgres.column_skipped` | A column is not sent and not protected: unsupported type, or a reserved name. | Review once. |

***

## What Was Verified, and What Was Not

**Verified against real PostgreSQL servers** — everything below on 16, and the core flow of both modes on 13, 14, 15, 17 and 18 as well — in both modes unless noted: the initial load (including a partitioned table, composite keys and mixed-case names); inserts, updates and deletes; primary-key updates; updates that leave a large TOASTed column untouched; `TRUNCATE` with the safety valve; an agent restart and an API outage mid-cycle without duplicates or losses; TLS with certificate verification; reserved column names; and the example Docker Compose deployment as shipped. In `logical` mode also: concurrent writers during the initial load; 12,000 transactions in one cycle; one transaction of 150,000 changes; a slot dropped, re-created by someone else, or invalidated by `max_slot_wal_keep_size`; and every missing-prerequisite refusal.

Also verified: `scan` mode against a hot standby; a failover with the standby promoted while the agent was running (gap and full read on 16; no gap with a synchronised failover slot on 17); synchronous replication with a stalled standby (the cycle fails, nothing is sent, and the rows are delivered once when the standby resumes); PgBouncer 1.26 in session mode; and `citext`, `ltree` and `hstore` columns.

**Not verified — test these in your own environment first:**

* Managed services (Amazon RDS / Aurora, Cloud SQL, Azure). The notes for them come from their documentation, not from a test.
* Failover run by a cluster manager (Patroni, repmgr, pg\_auto\_failover): failover was staged by hand on one streaming standby.
* Poolers other than PgBouncer (Pgpool-II, Odyssey, RDS Proxy, Supavisor): use a direct connection unless you have tested yours.
* Extensions other than `citext`, `ltree` and `hstore`.
* Docker hosts other than Linux with the default setup (Docker Desktop, rootless Docker, Podman, SELinux-enforcing hosts): ownership of the mounted secret files behaves differently there.
* The real ROOTKey API over a real network: every run used a stand-in endpoint that enforces the documented contract.

If any of this matters for a table, run a periodic full comparison as a safety net in `logical` mode too (for example `FULL_SCAN_INTERVAL_MINUTES=10080` for weekly).

***

## Troubleshooting

> [accordion] Nothing arrives in ROOTKey
>
> Read the agent's log first: every failure mode has a marker from the table above, with the PostgreSQL or API error in the line. `rootkey.connector.fatal` means the key is wrong, belongs to a connector of another type, or the ROOTKey table was deleted or paused.

> [accordion] table not found
>
> The name's case does not match (use the JSON form of `POSTGRES_TABLES` for mixed-case names), or `POSTGRES_DATABASE` is not the database that holds it.

> [accordion] no pg\_hba.conf entry, or a certificate error
>
> The server's `pg_hba.conf` does not allow the agent's address, or the certificate cannot be verified. Give the CA in `POSTGRES_SSL_CA_FILE` and use the host name the certificate was issued for.

> [accordion] wal\_level, publication or REPLICA IDENTITY errors
>
> A prerequisite of `logical` mode is missing; the message names the statement that fixes it. See `sql/create-replication-user.sql`.

> [accordion] permission denied to use replication slots
>
> The role lacks the `REPLICATION` attribute (on Amazon RDS: `rds_replication`).

> [accordion] replication slot is active for PID
>
> Another process is reading the same slot: a second agent, or a tool pointed at it. Each consumer needs its own slot (`REPLICATION_SLOT`).

> [accordion] pg\_wal is growing
>
> The agent is stopped or failing, and its slot is retaining WAL. Fix the agent, or drop the slot with `SELECT pg_drop_replication_slot('rootkey_connector');` if the connector is retired. Set `max_slot_wal_keep_size` so this can never fill the disk.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.