Replicant (Replicant v4.0.0)

Copy Markdown View Source

Starts and stops PostgreSQL change data capture pipelines for Elixir applications. Each pipeline delivers committed transactions to a Replicant.Sink. The facade also converts PostgreSQL log sequence numbers (LSNs) to and from their display form.

Summary

Types

A Postgres LSN as a single 64-bit integer (file <<< 32) ||| offset.

Functions

Parse a PostgreSQL pg_lsn display string ("0/16E3778") into a 64-bit LSN. The inverse of lsn_to_string/1 accepts upper or lowercase hex. Each half must fit 32 bits. Returns {:ok, lsn} or a value-free {:error, :invalid_lsn} for malformed strings.

The hex display form of an LSN, e.g. lsn_to_string(0x16E3778) == "0/16E3778". Postgres displays pg_lsn as uppercase file/offset hex with no padding.

Start a supervised change data capture pipeline. Replicant validates the options and checks the start intent before creating the pipeline.

Stop a running pipeline by slot name (idempotent).

Whether Replicant supports the PostgreSQL server reporting server_version_num (the integer from SHOW server_version_num, e.g. 170010 for 17.10).

Types

lsn()

@type lsn() :: non_neg_integer()

A Postgres LSN as a single 64-bit integer (file <<< 32) ||| offset.

Integer comparison (<=, >) is correct WAL ordering, so the exactly-once watermark is txn.commit_lsn <= checkpoint.

Functions

lsn_from_string(string)

@spec lsn_from_string(String.t()) :: {:ok, lsn()} | {:error, :invalid_lsn}

Parse a PostgreSQL pg_lsn display string ("0/16E3778") into a 64-bit LSN. The inverse of lsn_to_string/1 accepts upper or lowercase hex. Each half must fit 32 bits. Returns {:ok, lsn} or a value-free {:error, :invalid_lsn} for malformed strings.

lsn_to_string(lsn)

@spec lsn_to_string(lsn()) :: String.t()

The hex display form of an LSN, e.g. lsn_to_string(0x16E3778) == "0/16E3778". Postgres displays pg_lsn as uppercase file/offset hex with no padding.

start_link(opts)

@spec start_link(term()) :: {:ok, pid()} | {:error, term()}

Start a supervised change data capture pipeline. Replicant validates the options and checks the start intent before creating the pipeline.

Use a keyword list with the keys in the table below. Replicant refuses unknown keys and duplicates, including in its nested option lists. Source and checkpoint connection settings are Postgrex options.

Options

OptionDefaultPurpose
:connectionRequiredPostgrex connection keyword list for the source.
:slot_nameRequiredValidated replication slot name.
:publicationRequired for pgoutputOne validated publication name or a nonempty list.
:replication_setsRequired for pglogicalOne validated replication-set name or a nonempty list.
:sinkRequiredModule implementing the applicable Replicant.Sink callbacks.
:decoder:pgoutputSelects :pgoutput or :pglogical.
:originDecoder default:any streams changes from every origin. :none streams locally originated changes. See source decoders for defaults and source requirements.
:go_forward_onlyfalseSet to true to start a fresh state mirror with future changes. Accepts only booleans. Mutually exclusive with a snapshot.
:snapshotfalsetrue takes a point-in-time snapshot. [mode: :incremental, chunk_rows: 1000, max_pending_chunks: 4] enables resumable backfill.
:checkpoint_storeOffEnables library-owned checkpoints. Supply :connection. Optional settings are :table (replicant_checkpoints), :progress_table (replicant_snapshot_progress), :max_retries (5), :retry_backoff_ms (1000) and :batch (the same two settings as :batch_delivery).
:batch_deliveryOffSink-owned atomic batches. The keyword list defaults to max_transactions: 100 and max_delay_ms: 1000.
:streamingOffpgoutput in-progress streaming. The keyword list defaults to max_concurrent_txns: 64. An optional :spill list accepts :dir (the replicant_spill subdirectory of the system temporary directory) and :max_spill_bytes (16 times :max_inflight_lag).
:max_inflight_lag64 MiBBudgets queued payload bytes and separately bounds retained transaction and batch payload.
:receive_timeout:infinityEnable receive-silence recovery with an integer from 2 to 4,294,967,295 milliseconds. Applies during unpaused streaming, including incremental backfill.
:max_command_retries5Caps repeated failures of pre-stream replication commands.
:messagesfalseDelivers pgoutput logical-decoding messages. Requires Replicant.Sink.handle_message/2.
:failoverfalseRequests a pgoutput failover slot on a compatible source.

Intake pauses at the byte budget or 512 queued messages and resumes at or below half of both thresholds. During a pause the source receives feedback at the durable checkpoint on a cadence derived from its session timeout. These budgets measure payload, separate from PostgreSQL's WAL retention.

The receive watchdog asks PostgreSQL to reply after half the effective timeout. It warns and raises the deadline when needed to allow a walsender time to read replies during a large filtered transaction. With a positive wal_sender_timeout, the minimum deadline is half that setting plus the greater of a quarter of that setting and 100 milliseconds. See the recovery guide.

A batch can flush on count, delay, LSN span, a standalone message, or retained payload pressure (:max_buffer_bytes). Streamed rows can spill to disk. If payload cannot be reclaimed within the retained budget, the pipeline halts with :buffer_limit_exceeded. With spill enabled, an ordinary transaction can use up to max_inflight_lag + max_spill_bytes in memory, subject to the combined limit across retained payload.

Returns {:ok, pipeline_pid} or {:error, reason}. See Replicant.Config.validate/1 and Replicant.Config.guard/1 for start-time refusals. After startup, the source connection can halt on an unsupported server, a missing publication or an invalidated slot. See Replicant.Telemetry for the events.

stop(slot_name)

@spec stop(String.t()) :: :ok

Stop a running pipeline by slot name (idempotent).

supported_server_version?(server_version_num)

@spec supported_server_version?(term()) :: boolean()

Whether Replicant supports the PostgreSQL server reporting server_version_num (the integer from SHOW server_version_num, e.g. 170010 for 17.10).

Connection startup applies this same check before creating a replication slot and halts {:config, :server_version_unsupported} when it fails. Call it when admitting a source to refuse an unsupported server before any slot exists.

Anything other than an integer in the supported range returns false, including the text form "170010"; never raises.

iex> Replicant.supported_server_version?(150_000)
true
iex> Replicant.supported_server_version?(190_002)
true
iex> Replicant.supported_server_version?(149_999)
false
iex> Replicant.supported_server_version?(200_000)
false