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 / DOCKER RECIPES / COMPOSE WITH REPLICATION

Compose with replication

Two RasterizedDB nodes that replicate every committed transaction to each other. Both accept reads and writes (multi-primary). Use it to try replication on one machine, or as the template for two hosts: each service becomes one host's Compose file.

What you get

  • node1 on 127.0.0.1:5432 (native protocol on 61170) and node2 on 127.0.0.1:5433 (native protocol on 61180), each with its own data volume.
  • Replication between them on port 61171, on the project network only. Every database replicates, CREATE DATABASE and DROP DATABASE included.
  • Mutual authentication: each node presents its own certificate and accepts only the other node's, by SHA-256 fingerprint (--replication-auth pinned). The link is TLS-encrypted.
  • Asynchronous replication: a commit returns once it is durable on the node that took it, and reaches the other node shortly after.

Prerequisites

  • Docker with the Compose plugin.
  • psql to check the result.
  • Two empty nodes. This recipe starts both from nothing. A node that already holds data needs a base copy first (see Limits).

What to edit

  1. Copy .env.example to .env and set RASTERIZEDDB_PG_PASSWORD. Each node creates the role rasterized with it on its own first start; that first role is not replicated.

  2. Create the identities, once. This writes replication-cert.pem and replication-key.pem into each node's data volume and both fingerprints into .env:

    sh
    ./init-identities.sh
    powershell
    .\init-identities.ps1
    text
    node1 fingerprint: 3f0c…
    node2 fingerprint: 9a41…
    Written to .env. Start the nodes with: docker compose up -d

    Running it again refuses, because new identities break the pins the running nodes hold. REGENERATE=1 ./init-identities.sh (or -Regenerate) replaces both, after which both nodes must be recreated.

The replication flags in compose.yaml:

FlagHereDefaultWhat it does
--replicationonoffTurns replication on
--node-id1, 2noneUnique, non-zero id of each node
--replication-addr0.0.0.0127.0.0.1Address the replication listener binds
--replication-port61171the native port plus one, 61171Port of the replication listener
--replication-authpinnedinsecure, or pinned when a certificate is givenpinned, ca, or insecure, which is refused on any address but loopback
--replication-cert, --replication-keyin the data volumenoneThis node's certificate and key
--replication-peer-fingerprintthe other node'snoneA peer certificate to accept. Repeatable.
--peernode2@node2:61171, node1@node1:61171noneA peer, as name@host:port. Repeatable.
--replication-modenot setasyncsync, quorum:N or all make a commit wait for that many peers
--replication-conflictnot setabortWhat to do with a transaction that will not apply: abort, skip or last-writer-wins

For two hosts, put one service in each host's Compose file, publish port 61171 to the other host only (firewall it from everything else), and set --peer to the other host's address.

Run it

sh
docker compose up -d
docker compose ps

Check that it works

Write on node 1:

sh
psql "host=127.0.0.1 port=5432 user=rasterized dbname=postgres sslmode=require" \
  -c "CREATE TABLE notes (id INT PRIMARY KEY, body TEXT)" \
  -c "INSERT INTO notes VALUES (1, 'written on node 1')"

Read on node 2 (replication is asynchronous, so allow it a moment), and write there too:

sh
psql "host=127.0.0.1 port=5433 user=rasterized dbname=postgres sslmode=require" \
  -c "SELECT * FROM notes" \
  -c "INSERT INTO notes VALUES (2, 'written on node 2')"
text
 id |       body
----+-------------------
  1 | written on node 1
(1 row)

INSERT 0 1

See each node's view of the link. The peer's line should read up, with a lag of 0 once both are idle:

sh
psql "host=127.0.0.1 port=5432 user=rasterized dbname=postgres sslmode=require" -c "SHOW REPLICATION"

Sequence numbers show how much of each stream a node has applied, not that both hold the same rows. To compare the rows themselves, table by table, run this while nothing is writing:

sh
psql "host=127.0.0.1 port=5432 user=rasterized dbname=postgres sslmode=require" -c "REPLICATION CHECK"

If the peer stays down, read the log. A wrong fingerprint is named there:

sh
docker compose logs node1

Stop and clean up

sh
docker compose down        # keeps both volumes and their identities
docker compose down -v     # deletes both nodes' data and identities

After down -v, run init-identities again before the next start.

Limits

  • This is eventually consistent multi-primary replication, not consensus. There is no leader and no split-brain protection: two nodes cut off from each other both keep accepting writes, and the conflict policy decides what happens when they meet again.
  • Statements are replayed on the other node, so a value computed by the server, such as the current time or a random number written in the statement, can differ between nodes. Compute such values in the application and send them as literals.
  • A node that already holds data, or that joins an existing pair, needs a base copy from a backup first, with every db_replication.* file removed from the copy. See Replication.
  • Peers added with REPLICATION ADD PEER are forgotten at restart. Keep the cluster's shape in compose.yaml.

The files

compose.yaml · Docker ComposeDOWNLOAD ↓
# Two RasterizedDB nodes replicating to each other (multi-primary: both
# accept writes). Peers prove who they are with pinned certificates.
#
# First: copy .env.example to .env, set the password, then run
# ./init-identities.sh (or .\init-identities.ps1) once. It writes each node's
# certificate into its volume and both fingerprints into .env.
name: rasterizeddb-replication

x-node: &node
  image: ${RASTERIZEDDB_IMAGE:-milendenev/rasterizeddb:1.1.0}
  environment:
    RASTERIZEDDB_PG_PASSWORD: ${RASTERIZEDDB_PG_PASSWORD:?set RASTERIZEDDB_PG_PASSWORD in .env}
  restart: unless-stopped
  stop_grace_period: 60s
  healthcheck:
    test: ["CMD", "bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/5432"]
    interval: 10s
    timeout: 5s
    retries: 6
    start_period: 30s

services:
  node1:
    <<: *node
    hostname: node1
    command:
      - --replication
      - --node-id
      - "1"
      - --replication-addr
      - 0.0.0.0
      - --replication-port
      - "61171"
      - --replication-auth
      - pinned
      - --replication-cert
      - /var/lib/rasterizeddb/replication-cert.pem
      - --replication-key
      - /var/lib/rasterizeddb/replication-key.pem
      - --replication-peer-fingerprint
      - ${NODE2_FINGERPRINT:?run init-identities first}
      - --peer
      - node2@node2:61171
      - --log-level
      - warn
    ports:
      - "127.0.0.1:5432:5432"
      - "127.0.0.1:61170:61170"
    volumes:
      - node1-data:/var/lib/rasterizeddb

  node2:
    <<: *node
    hostname: node2
    command:
      - --replication
      - --node-id
      - "2"
      - --replication-addr
      - 0.0.0.0
      - --replication-port
      - "61171"
      - --replication-auth
      - pinned
      - --replication-cert
      - /var/lib/rasterizeddb/replication-cert.pem
      - --replication-key
      - /var/lib/rasterizeddb/replication-key.pem
      - --replication-peer-fingerprint
      - ${NODE1_FINGERPRINT:?run init-identities first}
      - --peer
      - node1@node1:61171
      - --log-level
      - warn
    ports:
      - "127.0.0.1:5433:5432"
      - "127.0.0.1:61180:61170"
    volumes:
      - node2-data:/var/lib/rasterizeddb

volumes:
  node1-data:
  node2-data:
init-identities.sh · Linux and macOS (Bash)DOWNLOAD ↓
#!/usr/bin/env bash
# Gives each node a replication identity (a self-signed certificate and its
# key, in the node's own data volume) and writes both fingerprints into .env,
# where compose.yaml reads them. Run once, before the first `docker compose up`.
#
#   ./init-identities.sh                  # refuses if a node already has one
#   REGENERATE=1 ./init-identities.sh     # replace both identities
set -euo pipefail

cd "$(dirname "$0")"

if [ ! -f .env ]; then
  echo "Copy .env.example to .env and set the password first." >&2
  exit 1
fi

# compose.yaml needs both fingerprints to load at all. Stand-ins for the
# commands below, which override the nodes' command lines anyway.
placeholder="$(printf '0%.0s' $(seq 64))"
compose() {
  NODE1_FINGERPRINT="$placeholder" NODE2_FINGERPRINT="$placeholder" docker compose "$@"
}

has_identity() {
  compose run --rm --no-deps -T --entrypoint test "$1" \
    -e /var/lib/rasterizeddb/replication-cert.pem
}

generate() {
  compose run --rm --no-deps -T --entrypoint rasterizeddb "$1" \
    --replication-generate-identity /var/lib/rasterizeddb --replication-addr "$1" \
    | sed -n 's/^fingerprint: \([0-9a-f]\{64\}\)$/\1/p'
}

if [ "${REGENERATE:-0}" != 1 ]; then
  for node in node1 node2; do
    if has_identity "$node"; then
      echo "$node already has a replication identity. To replace both, run:" >&2
      echo "  REGENERATE=1 $0" >&2
      exit 1
    fi
  done
fi

fp1="$(generate node1)"
fp2="$(generate node2)"
if [ ${#fp1} -ne 64 ] || [ ${#fp2} -ne 64 ]; then
  echo "Could not read a fingerprint from the server's output." >&2
  exit 1
fi

tmp="$(mktemp .env.XXXXXX)"
grep -v -E '^NODE[12]_FINGERPRINT=' .env > "$tmp" || true
printf 'NODE1_FINGERPRINT=%s\nNODE2_FINGERPRINT=%s\n' "$fp1" "$fp2" >> "$tmp"
mv "$tmp" .env

echo "node1 fingerprint: $fp1"
echo "node2 fingerprint: $fp2"
echo "Written to .env. Start the nodes with: docker compose up -d"
echo "(If they were already running, recreate them: docker compose up -d --force-recreate)"
init-identities.ps1 · Windows (PowerShell)DOWNLOAD ↓
# Gives each node a replication identity (a self-signed certificate and its
# key, in the node's own data volume) and writes both fingerprints into .env,
# where compose.yaml reads them. Run once, before the first `docker compose up`.
#
#   .\init-identities.ps1                 # refuses if a node already has one
#   .\init-identities.ps1 -Regenerate     # replace both identities
param(
    [switch] $Regenerate
)
$ErrorActionPreference = 'Stop'

Set-Location $PSScriptRoot

if (-not (Test-Path .env)) { throw 'Copy .env.example to .env and set the password first.' }

# compose.yaml needs both fingerprints to load at all. Stand-ins for the
# commands below, which override the nodes' command lines anyway.
$placeholder = '0' * 64
$saved = @{ NODE1_FINGERPRINT = $env:NODE1_FINGERPRINT; NODE2_FINGERPRINT = $env:NODE2_FINGERPRINT }
$env:NODE1_FINGERPRINT = $placeholder
$env:NODE2_FINGERPRINT = $placeholder

try {
    if (-not $Regenerate) {
        foreach ($node in 'node1', 'node2') {
            docker compose run --rm --no-deps -T --entrypoint test $node -e /var/lib/rasterizeddb/replication-cert.pem
            if ($LASTEXITCODE -eq 0) {
                throw "$node already has a replication identity. To replace both, run: .\init-identities.ps1 -Regenerate"
            }
        }
    }

    $fingerprints = @{}
    foreach ($node in 'node1', 'node2') {
        $output = docker compose run --rm --no-deps -T --entrypoint rasterizeddb $node `
            --replication-generate-identity /var/lib/rasterizeddb --replication-addr $node
        if ($LASTEXITCODE -ne 0) { throw "generating the identity of $node failed" }
        $line = $output | Where-Object { $_ -match '^fingerprint: ([0-9a-f]{64})$' } | Select-Object -First 1
        if (-not $line) { throw "Could not read the fingerprint of $node from the server's output." }
        $fingerprints[$node] = ($line -replace '^fingerprint: ', '')
    }
}
finally {
    $env:NODE1_FINGERPRINT = $saved.NODE1_FINGERPRINT
    $env:NODE2_FINGERPRINT = $saved.NODE2_FINGERPRINT
}

$kept = Get-Content .env | Where-Object { $_ -notmatch '^NODE[12]_FINGERPRINT=' }
$lines = @($kept) + "NODE1_FINGERPRINT=$($fingerprints.node1)" + "NODE2_FINGERPRINT=$($fingerprints.node2)"
Set-Content -Path .env -Value $lines -Encoding ascii

Write-Host "node1 fingerprint: $($fingerprints.node1)"
Write-Host "node2 fingerprint: $($fingerprints.node2)"
Write-Host 'Written to .env. Start the nodes with: docker compose up -d'
Write-Host '(If they were already running, recreate them: docker compose up -d --force-recreate)'
.env.example · Environment fileDOWNLOAD ↓
# Copy to .env next to compose.yaml and change the password. Each node
# creates the role `rasterized` with it on its own first start.
RASTERIZEDDB_PG_PASSWORD=change-me-to-a-long-random-password

# The image and tag. Pin a full version, the same on both nodes.
RASTERIZEDDB_IMAGE=milendenev/rasterizeddb:1.1.0

# NODE1_FINGERPRINT and NODE2_FINGERPRINT are added below by
# init-identities.sh / init-identities.ps1.
✓ page rendered in 123 µs axum + tera + htmx · no other javascript