Replicant
Replicant is an Elixir library for PostgreSQL change data capture. Use it to stream committed transactions from a logical replication slot into a sink you write, starting with an optional snapshot of existing rows.
- Acknowledges delivered changes only after the durable checkpoint advances.
- Supports effect-once writes when the sink commits its changes and checkpoint atomically.
- Applies the publication's column lists and row filters during snapshots and streaming.
- Keeps row values out of its errors and telemetry and stops on unaccepted destructive schema changes.
Install
Add {:replicant, "~> 4.0"} to your Mix dependencies.
Record committed changes
In a demo database with wal_level = logical, run this SQL as the table owner.
For the pipeline, use a role with replication access, read access to the source
table, and read and insert access to the ledger.
CREATE TABLE orders (id integer PRIMARY KEY, note text);
CREATE PUBLICATION orders_pub FOR TABLE orders;
CREATE TABLE cdc_ledger (commit_lsn numeric(20, 0) PRIMARY KEY, payload bytea NOT NULL);Set PGHOST, PGPORT, PGDATABASE, PGUSER and PGPASSWORD for the connection.
In your application's IEx session, use a ledger row to commit the change and its
checkpoint in the same write. Use one ledger per source and slot.
defmodule OrdersLedger do
@behaviour Replicant.Sink
@impl true
def checkpoint do
case Postgrex.query!(__MODULE__, "SELECT max(commit_lsn) FROM cdc_ledger", []).rows do
[[nil]] -> {:ok, nil}
[[lsn]] -> {:ok, Decimal.to_integer(lsn)}
end
end
@impl true
def handle_transaction(%Replicant.Transaction{commit_lsn: lsn, changes: changes}) do
Postgrex.query!(
__MODULE__,
"""
INSERT INTO cdc_ledger (commit_lsn, payload)
SELECT $1, $2
WHERE NOT EXISTS (SELECT 1 FROM cdc_ledger WHERE commit_lsn >= $1)
ON CONFLICT (commit_lsn) DO NOTHING
""",
[Decimal.new(lsn), :erlang.term_to_binary(changes)]
)
{:ok, lsn}
end
end
connection = [
hostname: System.fetch_env!("PGHOST"),
port: String.to_integer(System.get_env("PGPORT", "5432")),
database: System.fetch_env!("PGDATABASE"),
username: System.fetch_env!("PGUSER"),
password: System.fetch_env!("PGPASSWORD")
]
{:ok, _} = Postgrex.start_link(connection ++ [name: OrdersLedger])
{:ok, _} =
Replicant.start_link(
connection: connection,
slot_name: "replicant_orders",
publication: "orders_pub",
sink: OrdersLedger,
go_forward_only: true
)Once the slot is active, insert an order and check the ledger.
INSERT INTO orders VALUES (1, 'ready');
SELECT commit_lsn FROM cdc_ledger;Documentation
- Tutorials. Getting started in Livebook (run the notebook).
- Topics. Delivery guarantees, snapshot coverage, and source decoders.
- How-to. Run a reference pipeline, recover a stalled or halted pipeline, and upgrade a source.
- Reference. Modules and callbacks.
See Compatibility for supported versions and dependency floors.