↓Skip to main content

Consuming Postgres Native logical replication stream from rust

·3 mins

In this post I will discuss the steps to create a logical replication publication from postgresql and how to read from the replication slot using a rust program. We will be using the native postgres default decoder, pgoutput in these steps. When you read from the replication slot you get the data in a binary protocol (So you dont see actual insert/update/delete statements).

Pre-requisites #

  • In the postgres database set the configuration parameter wal_level=‘logical’,max_wal_senders=10 and max_replication_slots=10 (10 or a reasonable number)

Postgresql steps #

From the psql client connect to the postgresql database and do the following

create table books (bookid serial,bookname varchar(100),bookauthor varchar(50),bookprice numeric(5,2));
insert into books
SELECT floor(30000 * random()),'Author 1',ceil(random() * 50 + 1) FROM generate_series(1, 10);
alter table books replica identity full;
SELECT pg_create_logical_replication_slot('rkrepslot1', 'pgoutput');
CREATE PUBLICATION rklrpub1 FOR TABLE books;

This creates a table books, enables replica identity full on the table ,creates a replication slot and creates a publication.

Rust steps #

This assumes that you have a rust environment setup and cargo available to create and compile the rust programs.

cargo new pg-lr
cd pg-lr
cargo add pgwire_replication

This creates a new rust project and adds the crate pgwire_replication to the project. We will use pwire_replication to read from the the postgres replication slot.

Add the following code to src/main.rs

use pgwire_replication::{ReplicationClient, ReplicationConfig, ReplicationEvent, Lsn};
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // FIX: Build it with new() and chain the configuration modifiers
    let config = ReplicationConfig::new(
        "localhost",       // host
        "pg1user",        // user
        "pg1pwd",               // password
        "pg1db",            // database
        "rkrepslot1",         // logical replication slot
        "rklrpub1",  // Postgres publication name
    )
    .with_port(5432)
    .with_start_lsn(Lsn::ZERO);

    println!("Connecting to PostgreSQL logical replication stream...");
    let mut client = ReplicationClient::connect(config).await?;
    println!("Successfully connected. Awaiting database records...");

    while let Some(event) = client.recv().await? {
        match event {
            ReplicationEvent::XLogData { wal_end, data, .. } => {
                println!("--- New WAL Record Received ---");
                println!("WAL End LSN: {}", wal_end);
                println!("Raw Data Size: {} bytes", data.len());
                println!("Raw Bytes (Lossy String): {:?}", String::from_utf8_lossy(&data));

                client.update_applied_lsn(wal_end);
            }
            _ => {}
        }
    }

    Ok(())
}

Modify the hostname, username, password, database name,replication slot name and publication name in the code above to be appropriate for your environment.

cargo run

As you perform dml on the postgresql database the rust program will read from the replication slot and display the binary stream like shown below.

Connecting to PostgreSQL logical replication stream...
Successfully connected. Awaiting database records...
--- New WAL Record Received ---
WAL End LSN: 0/0
Raw Data Size: 94 bytes
Raw Bytes (Lossy String): "R\0\0@\u{2}public\0books\0f\0\u{4}\u{1}bookid\0\0\0\0\u{17}����\u{1}bookname\0\0\0\u{4}\u{13}\0\0\0h\u{1}bookauthor\0\0\0\u{4}\u{13}\0\0\06\u{1}bookprice\0\0\0\u{6}�\0\u{5}\0\u{6}"
--- New WAL Record Received ---
WAL End LSN: 0/1C185B0
Raw Data Size: 51 bytes
Raw Bytes (Lossy String): "I\0\0@\u{2}N\0\u{4}t\0\0\0\u{5}22437t\0\0\0\u{b}Second Bookt\0\0\0\u{2}42t\0\0\0\u{5}22.00"
--- New WAL Record Received ---
WAL End LSN: 0/1C18A60
Raw Data Size: 97 bytes
Raw Bytes (Lossy String): "U\0\0@\u{2}O\0\u{4}t\0\0\0\u{5}22437t\0\0\0\u{b}Second Bookt\0\0\0\u{2}42t\0\0\0\u{5}22.00N\0\u{4}t\0\0\0\u{5}22437t\0\0\0\u{b}Second Bookt\0\0\0\u{2}42t\0\0\0\u{5}22.50"