NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / SETUP SCRIPTS / TWO REPLICATED NODES

Two replicated nodes

Sets up two servers on two machines that both accept writes and send every committed transaction to each other. The link is TLS, and each node only talks to the exact certificate of the other (pinned mode). Use it for a second copy of the database that can take over at once, or to serve two sites. Both nodes start empty; to add a second node to a database that already holds data, use the add-replica-node recipe.

Before you start

  • Two machines that can reach each other, each with the server binary (see the install recipe).
  • Each node's address, for example 10.0.0.1 and 10.0.0.2.
  • The replication port, 61171 by default, open between the two nodes only. Applications use the SQL ports (5432, 61170) as usual.
  • The same password for the role rasterized on both nodes, in RASTERIZEDDB_PG_PASSWORD. Each node creates its first role at its own first start; that is not replicated.

Settings

bash variablePowerShell parameterDefaultWhat it does
RDB_BIN-RdbBinrasterizeddb / rasterizeddb.exeThe server binary.
RDB_DATA-Data./dataThe database directory.
RDB_IDENTITY_DIR-IdentityDir./replication-identityThis node's replication certificate, key (mode 0600) and saved fingerprint.
RDB_NODE_ID-NodeIdrequiredThis node's id: unique in the cluster and not 0. Use 1 and 2.
RDB_NODE_ADDR-NodeAddrrequiredThis node's address. The replication listener binds it, and it goes into the certificate.
RDB_PEER_ADDR-PeerAddrrequiredThe other node's address.
RDB_PEER_NAME-PeerNamepeerThe other node's name in SHOW REPLICATION.
RDB_PEER_FINGERPRINT-PeerFingerprintnoneThe other node's certificate fingerprint. Without it the script only makes and prints this node's.
RDB_REPL_PORT-ReplPort61171This node's replication port.
RDB_PEER_PORT-PeerPort61171The other node's replication port.
RDB_REPL_MODE-ModeasyncHow long a commit waits for the peer: async (not at all), sync, quorum:N or all.
RDB_REPL_CONFLICT-ConflictabortWhat happens to a transaction that will not apply: abort, skip or last-writer-wins.
RDB_CLUSTER-ClusterrasterizeddbThe cluster's name. Nodes refuse peers that name another.
RDB_PG_LISTEN-PgListen0.0.0.0Where applications reach PostgreSQL.
RDB_TLS_CERT, RDB_TLS_KEY-CertPath, -KeyPathnoneYour certificate for the SQL listeners. The replication link uses its own identity regardless.

Run it

  1. On each node, make its identity. The script prints the fingerprint and stops:

    sh
    # node 1
    RDB_NODE_ID=1 RDB_NODE_ADDR=10.0.0.1 RDB_PEER_ADDR=10.0.0.2 ./setup.sh
    # node 2
    RDB_NODE_ID=2 RDB_NODE_ADDR=10.0.0.2 RDB_PEER_ADDR=10.0.0.1 ./setup.sh
    text
    wrote /home/you/replication-identity/replication-cert.pem
    wrote /home/you/replication-identity/replication-key.pem (mode 0600)
    
    fingerprint: f954bd37c0086d024b2dd4c790adc0e502b634f62c12efc324a9fbb0ab4ece98
  2. Start each node with the other's fingerprint:

    sh
    export RASTERIZEDDB_PG_PASSWORD='use-a-long-secret'
    # node 1
    RDB_NODE_ID=1 RDB_NODE_ADDR=10.0.0.1 RDB_PEER_ADDR=10.0.0.2 RDB_PEER_NAME=two \
      RDB_PEER_FINGERPRINT=<node 2's fingerprint> ./setup.sh
    # node 2
    RDB_NODE_ID=2 RDB_NODE_ADDR=10.0.0.2 RDB_PEER_ADDR=10.0.0.1 RDB_PEER_NAME=one \
      RDB_PEER_FINGERPRINT=<node 1's fingerprint> ./setup.sh
    powershell
    $env:RASTERIZEDDB_PG_PASSWORD = 'use-a-long-secret'
    .\setup.ps1 -NodeId 1 -NodeAddr 10.0.0.1 -PeerAddr 10.0.0.2 -PeerName two -PeerFingerprint <node 2's fingerprint>

The fingerprint is the SHA-256 of the certificate, the same value openssl x509 -in replication-cert.pem -noout -fingerprint -sha256 prints. Each node also logs its own at start.

Check that it works

On node 1:

sh
export PGPASSWORD='use-a-long-secret'
psql "postgresql://rasterized@10.0.0.1:5432/postgres?sslmode=require" -c "SHOW REPLICATION"

The peer's line reads up:

text
 peer             address                  node   state      acked    lag      queued   codec
 two              10.0.0.2:61171           2      up         361      0        0        zstd

Write on one node and read on the other:

sh
psql "postgresql://rasterized@10.0.0.1:5432/postgres?sslmode=require" \
  -c "CREATE TABLE kv (k TEXT PRIMARY KEY, v TEXT)" -c "INSERT INTO kv VALUES ('from', 'node 1')"
psql "postgresql://rasterized@10.0.0.2:5432/postgres?sslmode=require" -c "SELECT * FROM kv"

REPLICATION CHECK compares every table with the peer, row for row, rather than trusting the stream's counters.

Stop or undo

Ctrl+C stops a node cleanly. The other keeps taking writes and holds them for the stopped node (up to --replication-retention-mb, 256 MiB by default); when it comes back it catches up. To stop replicating while running, REPLICATION DISABLE; at the next start the command line decides again. Changes made with REPLICATION … statements are not saved: a node always comes up as its flags say.

Limits

  • This is not consensus. There is no leader and no split-brain protection: if the nodes cannot reach each other, both keep taking writes, and the conflict policy decides what happens when they meet. Writes to the same table on both nodes at once can conflict.
  • last-writer-wins resolves per table, not per row.
  • Statements are replicated, not rows. NOW(), RANDOM() and other values computed while a statement runs come out different on each node: compute them in the application and send the value.
  • A node that falls further behind than the retention needs a fresh base copy (see add-replica-node).

The files

setup.sh · Linux and macOS (Bash)DOWNLOAD ↓
#!/usr/bin/env bash
# RasterizedDB: two servers that both take writes and replicate every commit to
# each other, over TLS, each node pinning the other's certificate.
#
# Run it on each node. The first run makes this node's replication identity,
# prints its fingerprint and stops; give each node the other's fingerprint in
# RDB_PEER_FINGERPRINT and run it again to start the server (foreground).
#
# Node 1 (10.0.0.1):  RDB_NODE_ID=1 RDB_NODE_ADDR=10.0.0.1 RDB_PEER_ADDR=10.0.0.2 ./setup.sh
# Node 2 (10.0.0.2):  RDB_NODE_ID=2 RDB_NODE_ADDR=10.0.0.2 RDB_PEER_ADDR=10.0.0.1 ./setup.sh
set -euo pipefail

RDB_BIN="${RDB_BIN:-rasterizeddb}"
RDB_DATA="${RDB_DATA:-./data}"
RDB_IDENTITY_DIR="${RDB_IDENTITY_DIR:-./replication-identity}"  # this node's certificate and key
RDB_NODE_ID="${RDB_NODE_ID:-}"               # required: 1 on one node, 2 on the other
RDB_NODE_ADDR="${RDB_NODE_ADDR:-}"           # required: this node's address, which the peer connects to
RDB_PEER_ADDR="${RDB_PEER_ADDR:-}"           # required: the other node's address
RDB_PEER_NAME="${RDB_PEER_NAME:-peer}"       # a label for the other node in SHOW REPLICATION
RDB_PEER_FINGERPRINT="${RDB_PEER_FINGERPRINT:-}"
RDB_REPL_PORT="${RDB_REPL_PORT:-61171}"      # this node's replication port
RDB_PEER_PORT="${RDB_PEER_PORT:-61171}"      # the other node's replication port
RDB_REPL_MODE="${RDB_REPL_MODE:-async}"      # async, sync, quorum:N or all
RDB_REPL_CONFLICT="${RDB_REPL_CONFLICT:-abort}"  # abort, skip or last-writer-wins
RDB_CLUSTER="${RDB_CLUSTER:-rasterizeddb}"   # both nodes must use the same name
RDB_PG_LISTEN="${RDB_PG_LISTEN:-0.0.0.0}"    # where applications reach PostgreSQL
RDB_TLS_CERT="${RDB_TLS_CERT:-}"             # optional certificate for the SQL listeners
RDB_TLS_KEY="${RDB_TLS_KEY:-}"

die() { echo "error: $*" >&2; exit 1; }

command -v "$RDB_BIN" >/dev/null 2>&1 || die "'$RDB_BIN' not found; set RDB_BIN to the server binary"
[ -n "$RDB_NODE_ID" ] && [ "$RDB_NODE_ID" != 0 ] || die "set RDB_NODE_ID (1 on one node, 2 on the other; never 0)"
[ -n "$RDB_NODE_ADDR" ] || die "set RDB_NODE_ADDR to this node's address"
[ -n "$RDB_PEER_ADDR" ] || die "set RDB_PEER_ADDR to the other node's address"

# This node's identity: made once, kept.
mkdir -p "$RDB_IDENTITY_DIR"
RDB_IDENTITY_DIR="$(cd "$RDB_IDENTITY_DIR" && pwd)"
cert="$RDB_IDENTITY_DIR/replication-cert.pem"
key="$RDB_IDENTITY_DIR/replication-key.pem"
if [ ! -f "$cert" ] || [ ! -f "$key" ]; then
  out="$("$RDB_BIN" --replication-generate-identity "$RDB_IDENTITY_DIR" --replication-addr "$RDB_NODE_ADDR")"
  echo "$out"
  echo "$out" | sed -n 's/^fingerprint: *//p' > "$RDB_IDENTITY_DIR/fingerprint"
fi
mine="$(cat "$RDB_IDENTITY_DIR/fingerprint" 2>/dev/null || true)"
[ -n "$mine" ] || die "no fingerprint saved in $RDB_IDENTITY_DIR/fingerprint; delete the identity files there to make a new one"

if [ -z "$RDB_PEER_FINGERPRINT" ]; then
  echo
  echo "This node's fingerprint: $mine"
  echo "Run this script on the other node too, then here again with"
  echo "  RDB_PEER_FINGERPRINT=<the other node's fingerprint>"
  exit 0
fi

: "${RASTERIZEDDB_PG_PASSWORD:?set RASTERIZEDDB_PG_PASSWORD (the same on both nodes) for the role rasterized}"
export RASTERIZEDDB_PG_PASSWORD

mkdir -p "$RDB_DATA"
RDB_DATA="$(cd "$RDB_DATA" && pwd)"

args=(--location "$RDB_DATA" --protocol both --pg-addr "$RDB_PG_LISTEN"
  --replication --node-id "$RDB_NODE_ID" --replication-cluster "$RDB_CLUSTER"
  --replication-addr "$RDB_NODE_ADDR" --replication-port "$RDB_REPL_PORT"
  --replication-auth pinned --replication-cert "$cert" --replication-key "$key"
  --replication-peer-fingerprint "$RDB_PEER_FINGERPRINT"
  --peer "$RDB_PEER_NAME@$RDB_PEER_ADDR:$RDB_PEER_PORT"
  --replication-mode "$RDB_REPL_MODE" --replication-conflict "$RDB_REPL_CONFLICT")
if [ -n "$RDB_TLS_CERT" ]; then
  args+=(--pg-cert "$RDB_TLS_CERT" --pg-key "$RDB_TLS_KEY" --rdb-cert "$RDB_TLS_CERT" --rdb-key "$RDB_TLS_KEY")
fi

echo "Node $RDB_NODE_ID: replication on $RDB_NODE_ADDR:$RDB_REPL_PORT, peer $RDB_PEER_NAME at $RDB_PEER_ADDR:$RDB_PEER_PORT."
echo "Open port $RDB_REPL_PORT to the other node only."
echo "PostgreSQL: postgresql://rasterized@$RDB_NODE_ADDR:5432/postgres?sslmode=require"
echo "Check:      psql … -c 'SHOW REPLICATION'"
echo

exec "$RDB_BIN" "${args[@]}"
setup.ps1 · Windows (PowerShell)DOWNLOAD ↓
#Requires -Version 5.1
<#
.SYNOPSIS
  RasterizedDB: two servers that both take writes and replicate every commit
  to each other, over TLS, each node pinning the other's certificate.
.DESCRIPTION
  Run it on each node. The first run makes this node's replication identity,
  prints its fingerprint and stops; give each node the other's fingerprint
  with -PeerFingerprint and run it again to start the server (foreground).
.EXAMPLE
  .\setup.ps1 -NodeId 1 -NodeAddr 10.0.0.1 -PeerAddr 10.0.0.2
.EXAMPLE
  $env:RASTERIZEDDB_PG_PASSWORD = 'use-a-long-secret'
  .\setup.ps1 -NodeId 1 -NodeAddr 10.0.0.1 -PeerAddr 10.0.0.2 -PeerFingerprint 9f86d081…
#>
[CmdletBinding()]
param(
    [string]$RdbBin = $(if ($env:RDB_BIN) { $env:RDB_BIN } else { 'rasterizeddb.exe' }),
    [string]$Data = $(if ($env:RDB_DATA) { $env:RDB_DATA } else { '.\data' }),
    # This node's certificate and key.
    [string]$IdentityDir = $(if ($env:RDB_IDENTITY_DIR) { $env:RDB_IDENTITY_DIR } else { '.\replication-identity' }),
    # 1 on one node, 2 on the other; never 0.
    [int]$NodeId = $(if ($env:RDB_NODE_ID) { [int]$env:RDB_NODE_ID } else { 0 }),
    # This node's address, which the peer connects to.
    [string]$NodeAddr = $env:RDB_NODE_ADDR,
    [string]$PeerAddr = $env:RDB_PEER_ADDR,
    # A label for the other node in SHOW REPLICATION.
    [string]$PeerName = $(if ($env:RDB_PEER_NAME) { $env:RDB_PEER_NAME } else { 'peer' }),
    [string]$PeerFingerprint = $env:RDB_PEER_FINGERPRINT,
    [int]$ReplPort = $(if ($env:RDB_REPL_PORT) { [int]$env:RDB_REPL_PORT } else { 61171 }),
    [int]$PeerPort = $(if ($env:RDB_PEER_PORT) { [int]$env:RDB_PEER_PORT } else { 61171 }),
    # async, sync, quorum:N or all.
    [string]$Mode = $(if ($env:RDB_REPL_MODE) { $env:RDB_REPL_MODE } else { 'async' }),
    [ValidateSet('abort', 'skip', 'last-writer-wins')]
    [string]$Conflict = $(if ($env:RDB_REPL_CONFLICT) { $env:RDB_REPL_CONFLICT } else { 'abort' }),
    # Both nodes must use the same name.
    [string]$Cluster = $(if ($env:RDB_CLUSTER) { $env:RDB_CLUSTER } else { 'rasterizeddb' }),
    [string]$PgListen = $(if ($env:RDB_PG_LISTEN) { $env:RDB_PG_LISTEN } else { '0.0.0.0' }),
    [string]$CertPath = $env:RDB_TLS_CERT,
    [string]$KeyPath = $env:RDB_TLS_KEY
)
$ErrorActionPreference = 'Stop'

$cmd = Get-Command $RdbBin -ErrorAction SilentlyContinue
if (-not $cmd) { throw "'$RdbBin' not found; pass -RdbBin with the path of rasterizeddb.exe." }
if ($NodeId -le 0) { throw 'Pass -NodeId (1 on one node, 2 on the other; never 0).' }
if (-not $NodeAddr) { throw "Pass -NodeAddr with this node's address." }
if (-not $PeerAddr) { throw "Pass -PeerAddr with the other node's address." }

# This node's identity: made once, kept.
New-Item -ItemType Directory -Force -Path $IdentityDir | Out-Null
$IdentityDir = (Resolve-Path -LiteralPath $IdentityDir).Path
$cert = Join-Path $IdentityDir 'replication-cert.pem'
$key = Join-Path $IdentityDir 'replication-key.pem'
$fpFile = Join-Path $IdentityDir 'fingerprint'
if (-not (Test-Path -LiteralPath $cert) -or -not (Test-Path -LiteralPath $key)) {
    $out = & $cmd.Source --replication-generate-identity $IdentityDir --replication-addr $NodeAddr
    if ($LASTEXITCODE -ne 0) { throw 'Could not generate the replication identity; the message is above.' }
    $out | ForEach-Object { Write-Host $_ }
    $fp = $out | ForEach-Object { if ($_ -match '^fingerprint:\s*(\S+)') { $Matches[1] } } | Select-Object -First 1
    Set-Content -LiteralPath $fpFile -Value $fp -Encoding ascii
    # The key is the node's identity in the cluster: SYSTEM, Administrators and you only.
    & icacls.exe $key /inheritance:r /grant:r "$($env:USERNAME):F" '*S-1-5-18:F' '*S-1-5-32-544:F' | Out-Null
}
$mine = if (Test-Path -LiteralPath $fpFile) { (Get-Content -LiteralPath $fpFile -Raw).Trim() } else { '' }
if (-not $mine) { throw "No fingerprint saved in $fpFile; delete the identity files there to make a new one." }

if (-not $PeerFingerprint) {
    Write-Host ''
    Write-Host "This node's fingerprint: $mine"
    Write-Host 'Run this script on the other node too, then here again with'
    Write-Host "  -PeerFingerprint <the other node's fingerprint>"
    exit 0
}

if (-not $env:RASTERIZEDDB_PG_PASSWORD) { throw 'Set $env:RASTERIZEDDB_PG_PASSWORD (the same on both nodes) for the role rasterized.' }
New-Item -ItemType Directory -Force -Path $Data | Out-Null
$Data = (Resolve-Path -LiteralPath $Data).Path

$serverArgs = @('--location', $Data, '--protocol', 'both', '--pg-addr', $PgListen,
    '--replication', '--node-id', "$NodeId", '--replication-cluster', $Cluster,
    '--replication-addr', $NodeAddr, '--replication-port', "$ReplPort",
    '--replication-auth', 'pinned', '--replication-cert', $cert, '--replication-key', $key,
    '--replication-peer-fingerprint', $PeerFingerprint,
    '--peer', "$PeerName@${PeerAddr}:$PeerPort",
    '--replication-mode', $Mode, '--replication-conflict', $Conflict)
if ($CertPath) {
    $c = (Resolve-Path -LiteralPath $CertPath).Path
    $k = (Resolve-Path -LiteralPath $KeyPath).Path
    $serverArgs += @('--pg-cert', $c, '--pg-key', $k, '--rdb-cert', $c, '--rdb-key', $k)
}

Write-Host "Node ${NodeId}: replication on ${NodeAddr}:$ReplPort, peer $PeerName at ${PeerAddr}:$PeerPort."
Write-Host "Open port $ReplPort to the other node only, for example:"
Write-Host "  New-NetFirewallRule -DisplayName 'RasterizedDB replication' -Direction Inbound -Protocol TCP -LocalPort $ReplPort -RemoteAddress $PeerAddr -Action Allow"
Write-Host "PostgreSQL: postgresql://rasterized@${NodeAddr}:5432/postgres?sslmode=require"
Write-Host "Check:      psql … -c 'SHOW REPLICATION'"
Write-Host ''

& $cmd.Source @serverArgs
exit $LASTEXITCODE
✓ page rendered in 291 µs axum + tera + htmx · no other javascript