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 / RASTERIZEDDB SERVER / REPLICATION

Replication

Replication keeps two or more RasterizedDB servers holding the same data. Every node accepts reads and writes; a transaction committed on one node is shipped to the others and applied there. Use it to keep a warm second copy of a database in another machine or site, or to take writes in more than one place.

It is eventually consistent multi-primary replication, not consensus: there is no leader election and no split-brain protection. Read Limits before you rely on it.

How it works

  • Each committed transaction is shipped as the SQL statements that ran, in commit order, as one unit. A replica never applies half of a transaction.
  • Every node has a numeric node id. A transaction's identity is its origin node plus its position in that node's stream, so a transaction is applied once on each peer however often it arrives.
  • Nodes talk to each other over TLS 1.3 on a replication port of their own, separate from the SQL ports, so you can expose SQL to applications and replication only to the other nodes.
  • The intended layout is a full mesh: every node lists every other node as a peer.
  • Every database on the server replicates, each over its own stream. A database created with CREATE DATABASE while replication runs is created on the peers too, and DROP DATABASE is carried the same way.
  • Traffic is compressed with zstd when it pays (on by default).

Before you start

  • Give every node a unique, non-zero node id.
  • Decide how peers authenticate. On any address other than loopback you must use pinned (each node trusts the other nodes' exact certificates) or ca (each node trusts certificates signed by your cluster CA). Unauthenticated replication is refused off loopback.
  • Open the replication port (default 61171) between the nodes only.
  • A node that joins a cluster that already holds data needs a copy of that data first; see Adding a node to a cluster with data.

Set up two nodes with pinned certificates

This is the usual setup: each node has a self-signed certificate, and each node is told the SHA-256 fingerprints of the others.

1. Generate an identity on each node

Run once per node, with the address that node's replication listener will bind:

sh
# on node 1 (10.0.0.1)
rasterizeddb --replication-generate-identity /var/lib/rasterizeddb --replication-addr 10.0.0.1
text
wrote /var/lib/rasterizeddb/replication-cert.pem
wrote /var/lib/rasterizeddb/replication-key.pem (mode 0600)

fingerprint: f954bd37c0086d024b2dd4c790adc0e502b634f62c12efc324a9fbb0ab4ece98

The command writes the pair and exits. The certificate names localhost and the --replication-addr you gave. Do the same on node 2 with its own address, and note both fingerprints.

The fingerprint is SHA-256 over the certificate's DER encoding, the same value openssl x509 -noout -fingerprint -sha256 -in replication-cert.pem prints after Fingerprint=. Pass the 64 hex digits, with or without colons; a SHA256: prefix is also accepted. Each node also logs its own fingerprint at start-up.

2. Start each node with its peers

Put each other node's fingerprint in a variable (or straight on the command line):

sh
NODE1_FP=f954bd37c0086d024b2dd4c790adc0e502b634f62c12efc324a9fbb0ab4ece98   # printed on node 1
NODE2_FP=...                                                                # printed on node 2
sh
# node 1
rasterizeddb --location /var/lib/rasterizeddb \
  --replication --node-id 1 \
  --replication-addr 10.0.0.1 \
  --replication-auth pinned \
  --replication-cert /var/lib/rasterizeddb/replication-cert.pem \
  --replication-key  /var/lib/rasterizeddb/replication-key.pem \
  --replication-peer-fingerprint "$NODE2_FP" \
  --peer 'two@10.0.0.2:61171'
sh
# node 2
rasterizeddb --location /var/lib/rasterizeddb \
  --replication --node-id 2 \
  --replication-addr 10.0.0.2 \
  --replication-auth pinned \
  --replication-cert /var/lib/rasterizeddb/replication-cert.pem \
  --replication-key  /var/lib/rasterizeddb/replication-key.pem \
  --replication-peer-fingerprint "$NODE1_FP" \
  --peer 'one@10.0.0.1:61171'

Add the protocol and listener flags you normally run with (see Running the server); they are independent of replication.

--peer takes name@host:port or a bare host:port (the name is then the address). The name is how you refer to the peer in REPLICATION … statements and in the status output.

On either node, over SQL:

sql
SHOW REPLICATION;
text
node 1 of cluster 'rasterizeddb' — enabled
listening on 10.0.0.1:61171, mode async, conflict abort, compression auto:zstd:1
local sequence 0, clock 1787234791376.1, 1 peer(s), 0 open capture(s)
...
peer             address                  node   state        acked    lag      queued   codec
two              10.0.0.2:61171           2      up           0        0        0        zstd

Then write a row on node 1 and read it on node 2.

A wrong fingerprint fails the handshake and the peer line says so:

text
last error: could not connect to 10.0.0.2:61171: the server presented certificate
f954bd37…ce98, which is not among the pinned ones

Three or more nodes

List every other node on each node: one --peer and one --replication-peer-fingerprint per other node.

sh
# node 1 of three
rasterizeddb --location /var/lib/rasterizeddb \
  --replication --node-id 1 --replication-addr 10.0.0.1 \
  --replication-auth pinned \
  --replication-cert /var/lib/rasterizeddb/replication-cert.pem \
  --replication-key  /var/lib/rasterizeddb/replication-key.pem \
  --replication-peer-fingerprint "$NODE2_FP" \
  --replication-peer-fingerprint "$NODE3_FP" \
  --peer 'two@10.0.0.2:61171' --peer 'three@10.0.0.3:61171'

For a chain or a hub instead of a mesh, --replication-relay makes a node forward what it receives from one peer to its others. Leave it off in a full mesh, where it would send every transaction several times over.

Using a cluster CA instead

With --replication-auth ca, each node presents a certificate signed by your cluster's certificate authority and accepts any peer whose certificate that CA signed. Both directions are checked: the node dialling verifies the server's certificate, and the server requires and verifies the caller's.

sh
rasterizeddb --location /var/lib/rasterizeddb \
  --replication --node-id 1 --replication-addr 10.0.0.1 \
  --replication-auth ca \
  --replication-ca   /etc/rasterizeddb/cluster-ca.pem \
  --replication-cert /etc/rasterizeddb/node1-cert.pem \
  --replication-key  /etc/rasterizeddb/node1-key.pem \
  --peer 'two@10.0.0.2:61171'

The server's certificate is checked against the host in the peer address, so give each node's certificate the DNS name or IP address its peers dial.

If you pass certificate flags without --replication-auth, the mode is inferred: --replication-ca selects ca, and --replication-cert alone selects pinned.

Shared token and cluster name

Two lighter checks sit on top of TLS. Nodes refuse peers that give a different --replication-cluster name, and if --replication-token is set every member must present the same secret. Neither replaces certificate authentication; they catch a node pointed at the wrong cluster.

Command-line flags

FlagDefaultWhat it does
--replicationoffStart replicating at boot. Without it the settings below are still loaded, and REPLICATION ENABLE starts it later.
--node-id <N>noneThis node's id. Required to replicate; unique across the cluster and non-zero.
--peer <NAME@HOST:PORT>noneA peer. Repeat for each. Bare host:port is accepted.
--replication-addr <IP>127.0.0.1Address the replication listener binds.
--replication-port <PORT>61171Port the replication listener binds. This is the built-in native port plus one and does not follow --rdb-port; set it explicitly when running more than one node on a host.
--replication-cluster <NAME>rasterizeddbCluster name. Peers with a different name are refused.
--replication-token <SECRET>unsetShared secret every member presents in its handshake.
--replication-auth <MODE>insecure, or inferred from the certificate flagsinsecure, pinned or ca. insecure is refused on any non-loopback listen address.
--replication-cert <PATH>unsetPEM certificate this node presents, in both directions.
--replication-key <PATH>unsetPEM private key for that certificate.
--replication-ca <PATH>unsetPEM cluster CA, for ca mode.
--replication-peer-fingerprint <HEX>noneSHA-256 fingerprint of a peer's certificate, for pinned mode. Repeat once per other node.
--replication-generate-identity <DIR>Write replication-cert.pem and replication-key.pem into DIR, print the fingerprint, and exit.
--replication-compression <SPEC>auto:zstd:1none, zstd[:level] or auto[:zstd[:level]]. auto stops compressing while it is not paying off. Payloads under 512 bytes are sent uncompressed.
--replication-mode <MODE>asyncHow long a commit waits for peers: async, sync (one peer), quorum:N (N peers) or all (every connected peer).
--replication-ack-timeout-ms <MS>5000How long a sync/quorum/all commit waits before returning anyway.
--replication-conflict <POLICY>abortWhat to do with a transaction that will not apply: abort, skip or last-writer-wins. See Conflicts.
--replication-batch-records <N>256Records in one outbound batch.
--replication-batch-bytes <N>1048576 (1 MiB)Uncompressed bytes in one outbound batch.
--replication-pipeline-depth <N>8Batches a link keeps in flight before waiting for an answer. 1 waits for each. More helps a long, high-latency link.
--replication-linger-us <US>500How long a sender waits for more records before sending a partial batch.
--replication-queue <N>8192Records held in memory for a peer before it is served from the log.
--replication-relayoffForward transactions received from one peer to the others.
--replication-retention-mb <N>256History kept on disk for peers that fall behind, in MiB.

The replication log, state and related files are named db_replication.* and live in each database's directory next to its data.

Controlling replication from SQL

Replication statements work over both the PostgreSQL and the native protocol. Changes made this way are not persisted: a peer added with a statement is gone after a restart unless you also add the flag. What a node comes up as is always what its command line says.

sql
REPLICATION ENABLE;                 -- start (needs a node id); also REPLICATION START
REPLICATION DISABLE;                -- stop, for every database; also REPLICATION STOP

REPLICATION ADD PEER 'berlin' ADDRESS '10.0.0.2:61171';
REPLICATION ADD PEER 'tokyo'  ADDRESS '10.0.1.7:61171' WITH (COMPRESSION = 'zstd:3');
REPLICATION ADD PEER 'spare'  ADDRESS '10.0.0.9:61171' WITH (PAUSED = true);
REPLICATION DROP PEER 'berlin';
REPLICATION PAUSE PEER 'berlin';
REPLICATION RESUME PEER 'berlin';

REPLICATION RESYNC PEER 'berlin' FROM 0;   -- take berlin's stream again from a position
REPLICATION ADOPT PEER 'berlin';           -- see "A node restored to an earlier point"
REPLICATION CHECK;                          -- compare every table with every peer
REPLICATION CHECK PEER 'berlin' TABLE orders;
REPLICATION FLUSH;                          -- flush the replication log

REPLICATION SET mode = 'quorum:1';
REPLICATION SET conflict = 'last-writer-wins';

A peer added while replication is stopped starts with REPLICATION ENABLE. A server started without --node-id can be given one with REPLICATION SET node_id = 3 and then enabled; the node id cannot change while replication is running.

Settings REPLICATION SET accepts

SHOW REPLICATION KEYS lists them; SHOW REPLICATION SETTINGS shows current values. The token is never shown, only (set) or (unset).

KeyDefaultMeaning
node_idfrom --node-idThis node's id. Only while stopped.
clusterrasterizeddbCluster name.
tokenunsetShared handshake secret.
compressionauto:zstd:1As --replication-compression.
modeasyncasync, sync, quorum:N or all.
conflictabortabort, skip or last-writer-wins.
ack_timeout_ms5000Wait bound for synchronous modes.
batch_max_records256Records per batch.
batch_max_bytes1048576Bytes per batch.
batch_linger_us500Partial-batch wait.
pipeline_depth8Batches in flight per link.
queue_capacity8192In-memory records per peer.
relayfalseForward peers' transactions.
log_retention_mb256History kept for lagging peers.
connect_timeout_ms5000Dial timeout for a peer.
request_timeout_ms30000Per-request timeout on a peer link.
keepalive_ms10000Ping a link that has been quiet this long. 0 never pings; at most a third of request_timeout_ms is used.
reconnect_base_ms200First reconnect delay; doubles each retry.
reconnect_max_ms30000Longest reconnect delay.

Monitoring

Status and lag

sql
SHOW REPLICATION;          -- the same as SHOW REPLICATION STATUS
SHOW REPLICATION PEERS;    -- just the peer table

The status shows this node's sequence, counters (captured, published, applied, duplicates, conflicts, failures, gaps, ack timeouts), how much of each origin it has applied (applied through: node 2 → 5120), the size of its replication log, one line per peer, and one line per other database. The peer columns are:

ColumnMeaning
stateup: the peer takes what it is sent. down: not connected. paused: paused by you. stalled: the peer refuses the next transaction; it is offered again, less often, and the stream resumes by itself once the cause is gone. needs reseed: the peer needs history this node no longer holds, so nothing is sent.
ackedThe last of this node's transactions the peer has confirmed.
lagHow many of this node's transactions the peer has not yet confirmed.
queuedRecords waiting to be sent.
codecCompression in use on the link.

A last error: line under a peer gives the most recent failure on that link.

For tools and dashboards there are two row-shaped forms:

sql
SHOW REPLICATION STATS;        -- metric, value, detail
SHOW REPLICATION PEER STATUS;  -- one row per peer

SHOW REPLICATION STATS includes local_sequence, max_peer_lag, peers_connected, the counters above, per-database rows (database.<name>.max_lag, database.<name>.peers_connected, …) and timing counters. SHOW REPLICATION PEER STATUS returns peer, address, remote_node, connected, paused, acked_seq, lag, queued, records_sent, batches_sent, dropped, codec, last_ratio, last_error and state.

To find where a lagging peer's time goes, read push_round_trip_us on the sending node and apply_us / batches_applied on the receiving node before and after a period of load. If the receiver's apply time is nearly all of the sender's round trip, the peer is short of apply capacity and a faster network will not help; if it is a small part, look at the link.

Checking that the nodes hold the same rows

Sequence numbers say how much of each stream a node has applied, not that the rows match. To compare the data itself:

sql
REPLICATION CHECK;
text
node 1 and berlin (node 2) are in step: each has applied all the other has committed (5120 from here, 14 from there)
3 table(s) compared: 1 DIFFERENT, 0 on one node only
DIFFERENT  orders: 5100 rows here, 5099 on berlin

Each node reduces every user table to a row count and an order-independent checksum of its values, and the two are compared. Run it while the nodes are quiet: it only counts when nothing is committed or applied on either side while it reads, and otherwise retries a few times and reports NOT in step. A table of more than two million rows is counted but not checksummed, and the check names the table that differs, not the rows.

Conflicts

Two nodes may write the same row at the same time; that is what multi-primary allows. When a transaction from a peer will not apply, the policy decides:

PolicyBehaviour
abort (default)The transaction is not applied and that origin's stream stops (state stalled), with the error shown. Nothing is silently skipped.
skipThe failing statement is skipped, the rest of the transaction applies, and the stream moves on.
last-writer-winsA transaction older than this node's latest write to every table it touches is dropped; failures are skipped. Schema changes are never dropped this way.

last-writer-wins compares times per table, not per row: a transaction that is newer for any table it touches still applies. Ties are broken by node id, so both ends reach the same verdict.

To clear a stall under abort, fix the cause on the stalled node (for example remove the duplicate row that blocks an INSERT) and the stream resumes on its own. Do not undo a replicated change with a statement of your own on the stalled node: on a replicating node that statement is itself sent to the other nodes.

Keep schema changes in their own statements, outside transaction blocks that also write rows. A node that stops part-way through applying a block that mixes both can come back with the schema change done and the stream stalled on it; a fresh base copy (below) clears that.

Synchronous commits

With --replication-mode sync, quorum:N or all, a commit also waits until that many peers report the transaction applied, up to --replication-ack-timeout-ms. The local commit has already happened; the timeout only bounds how long a slow peer can hold the client. A timeout is counted (ack timeouts), and the commit still returns successfully.

Adding a node to a cluster with data

Replication ships what happens from now on, not what happened before. A new node, or one whose data you are replacing, must start from a copy of an existing node's data.

  1. Make a copy of an existing node's data directory: for example restore its S3 backup with --restore-to (see Backup and restore), or stop the node and copy its --location directory.

  2. Remove every db_replication.* file from the copy, in the root and in every database subdirectory, and do the same (with that node stopped) on the node it will pair with. These files describe the source node's stream and positions, not the new node's:

    sh
    find /var/lib/rasterizeddb-new -name 'db_replication.*' -delete
  3. Start the new node with its own --node-id, its own identity, and the other nodes as --peer; add it as a peer (and its fingerprint) on the existing nodes and restart them, or use REPLICATION ADD PEER for the running session.

  4. Run REPLICATION CHECK once the nodes are quiet.

Leaving the old db_replication.* files in place does not fail loudly: the new node can report its links up and still never ship its first writes. On the new node, acked greater than local sequence is the sign of it.

Databases that already existed on a node before it started replicating are not announced to the peers; they have to come over with the base copy.

Failure handling

A peer is down. The others keep accepting writes and keep its history in their replication log, up to --replication-retention-mb (and, for a connected peer still catching up, up to four times that). When the peer returns it catches up from where it left off. If it was away longer than that history reaches, its link shows needs reseed and nothing is sent: give it a fresh base copy as above.

A link keeps reconnecting. Reconnects back off from reconnect_base_ms to reconnect_max_ms. Look at the peer's last error: a fingerprint, CA, cluster name or token mismatch is reported there.

A stream is stalled. Under abort, the error on the stalled link says which statement failed. Fix the cause and it resumes. To take an origin's stream again from a known position, run REPLICATION RESYNC PEER '<name>' FROM <sequence> on the receiving node. It re-applies everything from that position, so on a table without a unique key it duplicates rows already applied; keep FROM as close as you can.

A node restored to an earlier point. A node restored from a backup to an earlier time than its peers have seen is behind its own stream: a peer holds transactions of this node that it no longer has. The link reports needs reseed and sends nothing. Either reseed one side from the other, or, to keep both nodes as they are, run REPLICATION ADOPT PEER '<name>', which moves this node's sequence past what the peer holds. Transactions the peer holds under those numbers stay only on the peer.

Restoring a node from its own backup. The db_replication.* files come back with the tables, to the same point. Keep them.

A disk sync fails while applying. The node stops accepting commits until it is restarted, and that origin's stream is halted; nothing is acknowledged or lost. Restart the node once the disk is healthy.

What replicates and what does not

Replicated: row writes, schema changes, CREATE DATABASE and DROP DATABASE, and writes to the key/value cache.

Each node's own, and run on every node that should have them (the client gets a warning when it runs one on a replicating node):

  • VACUUM and other space reclamation (Maintenance);
  • STORAGE … placement statements (Storage pools);
  • REPLICATION … settings;
  • backups (Backup and restore): each node backs itself up by its own flags, to its own prefix;
  • branches: a branch is that node's alone;
  • the role catalogue and first role every node creates for itself at first start.

Limits

  • Statements must be deterministic. Statements are re-run on each node, so NOW(), RANDOM(), CURRENT_TIMESTAMP, CURRENT_DATE, CURRENT_TIME, LOCALTIMESTAMP, CLOCK_TIMESTAMP(), STATEMENT_TIMESTAMP(), TRANSACTION_TIMESTAMP() and NEXTVAL() can produce different rows on each node. The server logs a warning the first time it replicates each of them. Compute such values in the client and send literals.
  • Not consensus. Two halves of a partitioned cluster both keep accepting writes, and the conflict policy decides what happens when they reconnect. If you need one serialisable history, this is the wrong tool.
  • Ordering is per origin. Each node's transactions apply in the order that node committed them; transactions from different nodes are ordered against each other only by their hybrid timestamps.
  • last-writer-wins is per table, not per row.
  • No per-node permissions. Every authenticated node is a full peer and may write anything. To remove a node, remove its fingerprint (or revoke its certificate) and restart the nodes that trusted it; there is no CRL or OCSP check.
  • One transaction travels in one frame of up to 64 MiB. A transaction whose statements do not fit is refused at commit.
  • Runtime changes are not saved. Statements change the running node only.
  • No downgrade of the replication files to a build older than the one that wrote them.
✓ page rendered in 298 µs axum + tera + htmx · no other javascript