Cluster RPC, Leader Routing and Replication Modes

This page covers the transport that carries Raft messages between nodes, how that transport is authenticated, how a client write reaches the Raft log, and how each wire protocol refuses writes on a follower. The consensus algorithm itself is in Raft internals. The operator view is in Operations: cluster mode.

1. Transport and framing

Every Raft RPC uses a fresh TCP connection that carries exactly one request and one response. The client side (RaftCluster) connects with a 5 second timeout, writes one frame, reads one frame and drops the connection. The server side (RaftRpcServer) accepts in a loop and spawns one tokio task per connection; an error in a connection task is logged and does not affect the listener. (source: src/distributed/rpc.rs, RaftRpcServer::start, RaftRpcServer::handle_connection, RaftRpcClient::send_message)

A frame is a big-endian u32 length followed by that many bytes. The bytes are a bincode-encoded RpcMessage, sealed with AES-256-GCM when a cluster secret is configured (section 2). (source: src/distributed/rpc.rs, handle_connection)

RpcMessage {
    id:       u64,
    msg_type: RpcMessageType,
    payload:  Vec<u8>,   // bincode of the request or response struct
}
RpcMessageType (declaration order) Payload type
RequestVote RequestVoteRequest
RequestVoteResponse RequestVoteResponse
AppendEntries AppendEntriesRequest
AppendEntriesResponse AppendEntriesResponse
InstallSnapshot InstallSnapshotRequest
InstallSnapshotResponse InstallSnapshotResponse { term, success }
PreVote RequestVoteRequest (same shape, flagged as a pre-vote)
PreVoteResponse RequestVoteResponse

(source: src/distributed/rpc.rs, RpcMessageType, RpcMessage)

bincode encodes enums by variant index, so the declaration order above is part of the wire format. Reordering the enum breaks mixed-version clusters. (source: src/distributed/rpc.rs, RpcMessageType)

Frame size limits

Limit Value Where it applies
MAX_RPC_FRAME_BYTES 8 MiB (+16 byte tag allowance) Request frames on a connection with no secret; every response frame read by the client
MAX_AUTHED_RPC_FRAME_BYTES 512 MiB (+16 byte tag allowance) Request frames on a connection that passed the handshake
Snapshot chunk 1 MiB send_snapshot_to_peer splits a snapshot into chunks this size
MAX_SNAPSHOT_TRANSFER_BYTES 1 GiB Total snapshot size a follower will assemble

The length prefix is checked before the buffer is allocated, so a peer cannot force a large allocation by sending a large length. The 512 MiB cap exists because a single Raft entry can be large: one bulk COPY statement becomes one entry. A unit test asserts that 512 MiB is below the value that the handshake magic SDBR reads as when parsed as a length, so a node with no secret rejects an authenticated peer at the length check instead of misparsing it. (source: src/distributed/rpc.rs, MAX_RPC_FRAME_BYTES, MAX_AUTHED_RPC_FRAME_BYTES, AUTH_MAGIC; src/distributed/raft.rs, MAX_SNAPSHOT_TRANSFER_BYTES)

Not verified: responses are always capped at 8 MiB, including on authenticated connections. The responses Raft sends are small (terms, indexes, booleans), so this does not limit entry size today. The client sets no timeout on reading the response, and the server sets no timeout on reading the request after the handshake, so a peer that stops mid-frame holds a task until TCP gives up. (source: src/distributed/rpc.rs, RaftRpcClient::send_message, handle_connection)

2. Authentication and encryption

[cluster] secret (environment SYNERGYDB_CLUSTER_SECRET) turns on an authenticated, encrypted transport. The secret must be at least MIN_CLUSTER_SECRET_LEN = 16 bytes; Server::init_cluster refuses a shorter one and treats an empty string as no secret. (source: src/distributed/rpc.rs, MIN_CLUSTER_SECRET_LEN; src/server/mod.rs, init_cluster; src/config.rs, ClusterConfig::secret)

Handshake and key derivation

client -> server   "SDBR\x02" || client_nonce[16]
server -> client   server_nonce[16]
key = HMAC-SHA256(secret, "synergydb-cluster-rpc-v2" || client_nonce || server_nonce)
client -> server   u32 len || AES-256-GCM(key, nonce = 1, aad = "req",  request)
server -> client   u32 len || AES-256-GCM(key, nonce = 2, aad = "resp", response)

Nonces come from rand::random. The server allows 10 seconds (AUTH_HANDSHAKE_TIMEOUT) for the client hello; the client reads the server nonce under its 5 second connect timeout. Nothing a peer sends is parsed, and no Raft state is touched, until its request frame decrypts and authenticates under the per-connection key. (source: src/distributed/rpc.rs, module doc, session_key, seal, open, handle_connection)

Why fixed GCM nonces are safe here: each connection derives a fresh key from two fresh random nonces and seals exactly one request (nonce 1) and one response (nonce 2) under it. A (key, nonce) pair is never reused. The different nonce and additional data per direction stop a response from being replayed as a request. A recorded request replayed on a new connection fails, because the new connection has a different key. (source: src/distributed/rpc.rs, Direction::nonce, Direction::aad; tests a_recorded_request_cannot_be_replayed, a_response_cannot_pass_for_a_request)

Crates used: aes_gcm for AES-256-GCM, hmac and sha2 for HMAC-SHA256, rand for nonces, bincode for message encoding. (source: src/distributed/rpc.rs, imports)

Behaviour matrix

Local node Peer Result
Secret Same secret Handshake, sealed frames, 512 MiB request cap
Secret Different secret Request fails to authenticate; connection dropped; state unchanged
Secret No secret Peer sends a bare length prefix; server rejects it as "peer did not start the cluster handshake"
No secret Secret The magic reads as a length above 8 MiB; frame rejected
No secret No secret Plaintext frames, 8 MiB request cap; only allowed on loopback

(source: src/distributed/rpc.rs, handle_connection; tests listed in section 7)

Loopback-only plaintext

Both RaftRpcServer::start and RaftCluster::start refuse to run without a secret when the bind address is not a loopback address. Loopback test clusters can run without one. (source: src/distributed/rpc.rs, RaftRpcServer::start, RaftCluster::start; test refuses_a_routable_bind_without_a_secret)

Not wired: the cluster port binds to [server] bind_address, the same address as every client wire. There is no separate bind address for cluster traffic. (source: src/server/mod.rs, init_cluster)

The secret protects Raft traffic only. Client wires use [tls], described in Connection handling. The two-phase-commit listeners in coordinator.rs use their own unauthenticated framing; see Sharding and 2PC. (source: src/distributed/coordinator.rs, CoordinatorRpcServer::start)

3. Cluster startup

Server::init_cluster starts Raft when [cluster] mode is not Standalone. (source: src/server/mod.rs, init_cluster)

  1. If cluster_port is unset, it logs a warning and returns. The node then runs as a standalone, writable node despite the configured mode.
  2. It binds bind_address:cluster_port. It parses each entry of peers as id@host:port; an entry that fails to parse or resolve is skipped with a warning.
  3. Storage for the Raft log goes in <data_dir>/raft/<node_id>.
  4. It checks the secret length, then calls RaftCluster::start. That enables PreVote, starts the node, spawns the RPC server, one replicator task per peer, the commit advancer, the quorum monitor and the election driver. Raft timing is in Raft internals.
  5. It spawns a status watcher. On each change the watcher publishes the role (section 5), writes the role to a .role file in the data directory and prints a [raft] node=... role=... term=... leader=... line.
  6. It installs the data plane: RaftReplicationHook on the storage engine, the apply loop, the snapshot restorer and the snapshot policy. Then it prints a "data plane wired" message.

(source: src/server/mod.rs, init_cluster; src/distributed/rpc.rs, RaftCluster::start)

Not verified: a peer that is skipped in step 2 is missing from the peer list, so the computed quorum is smaller than the cluster the operator configured. (source: src/server/mod.rs, init_cluster; src/distributed/raft.rs, quorum computation)

4. The write path in cluster mode

All wires write through StorageEngine::write_batch. When a replication hook is installed, the batch goes to ReplicationHook::before_write_batch first, which returns one of three outcomes. (source: src/storage/mod.rs, write_batch, ReplicationHook)

Hook outcome Meaning write_batch result
ApplyLocally No replication; write locally Local LSM write
Replicated Committed by Raft and already applied on this node by the apply loop Ok(()); no second local write
Reject(msg) This node may not write Err(Error::ReadOnly(msg))

write_batch_local bypasses the hook. It is used by the apply path, so a replicated entry is not sent back into Raft. (source: src/storage/mod.rs, write_batch, write_batch_local, apply_replicated_batch)

RaftReplicationHook::before_write_batch

  1. If this node is not the leader, return Reject with "cannot execute write: this node is a Raft follower; leader is X", or "… not the Raft leader (no leader currently elected)" when no leader is known.
  2. Encode the batch as ReplicatedWrite { entries, timestamp } (bincode).
  3. mark_local(payload): count the xxh3-64 hash of the payload in the process-wide LOCAL_PENDING map, so the apply loop can tell this node's own writes from replicated ones.
  4. RaftCluster::submit(payload): append to the leader's log and wait for commit, up to commit_timeout (30 s by default).
  5. wait_applied(index): wait until the local apply loop has applied that index, with a timeout of commit_timeout + 2 s.
  6. Return Replicated.

Errors become Reject messages: "write not committed by the cluster: …" when step 4 fails, and "write committed (index N) but not applied locally" when step 5 times out. The second case is ambiguous to the client: the write is durable in the Raft log but the client sees an error. (source: src/distributed/replication.rs, RaftReplicationHook::before_write_batch)

LOCAL_PENDING is capped at 2^20 entries; when the cap is hit the map is cleared. Entries leak only when a submitted write never commits. After a clear, an own write that later applies is reported to listeners as if it came from another node, which causes a redundant reload and nothing worse. (source: src/distributed/replication.rs, LOCAL_PENDING_MAX, mark_local, take_local)

Bridging sync storage to async Raft

write_batch is synchronous; Raft is async. The hook picks a strategy by the calling context. (source: src/distributed/replication.rs, before_write_batch)

Caller context Strategy
Multi-thread tokio runtime tokio::task::block_in_place plus Handle::block_on
Current-thread runtime (the PostgreSQL wire runs one per connection thread) Spawn the wait on the server runtime and block on a std::sync::mpsc::sync_channel
No runtime Handle::block_on on the server runtime handle

The current-thread case exists because block_in_place panics on a current-thread runtime. The status entry for leader routing records that before this fix every write on a clustered leader failed. (source: src/distributed/replication.rs; docs/status/2026-11-29-cluster-leader-routing.md)

Apply loop and replica listeners

The apply loop runs on every node. It waits for a commit-index change (or 100 ms), reads committed entries, and calls apply_log_entry for each. Empty payloads (the leader's no-op entry) are skipped. Non-empty payloads decode to a ReplicatedWrite and go to apply_replicated_batch. If take_local says the payload was not submitted by this node, the engine calls notify_replicated_apply. After an error the loop waits 50 ms and retries the same entry. (source: src/distributed/replication.rs, spawn_apply_loop, apply_log_entry)

ReplicatedApplyListener lets a wire that keeps state in memory follow the log:

pub trait ReplicatedApplyListener: Send + Sync {
    fn on_apply(&self, entries: &[(Vec<u8>, Option<Vec<u8>>)]);
    fn on_reset(&self); // InstallSnapshot replaced the keyspace
}

(source: src/storage/mod.rs, ReplicatedApplyListener, add_replicated_listener, notify_replicated_apply, notify_replicated_reset)

Wire Listener What it does on a replica
Redis RedisReplicaSync Reloads touched keys (values, streams, op log) and wakes blocked readers
Cassandra CatalogSync Reloads the schema catalog when keyspace or table records change
CouchDB CouchReplicaSync Reloads the database list and drops cached documents
InfluxDB InfluxReplicaSync Upserts replicated points; reloads the catalog on other changes

Wires that read storage directly on every request (PostgreSQL, MySQL, MongoDB) need no listener. (source: src/protocol/redis/commands/persist.rs, src/protocol/cassandra/mod.rs, src/protocol/couchdb/store.rs, src/protocol/influxdb/mod.rs; docs/status/2026-11-30-distributed-multiwire.md)

5. Node role and follower write refusal

node_role

src/distributed/node_role.rs holds one process-global RoleCell: an AtomicU8 role plus the current leader id. The Raft status watcher calls publish; wires call current, is_read_only and leader_id. (source: src/distributed/node_role.rs)

Value NodeRole as_str() Writable
0 Standalone standalone Yes
1 Leader leader Yes
2 NotLeader replica No

A process that never starts Raft stays Standalone. Candidates and followers both publish NotLeader. (source: src/distributed/node_role.rs; tests role_transitions, standalone_process_is_writable)

Per-wire behaviour on a follower

The storage hook rejects every write on a non-leader, so every wire refuses writes. Some wires check the role earlier to return a protocol-specific error. (source: src/storage/mod.rs, write_batch)

Wire Behaviour on a follower
PostgreSQL in_hot_standby and default_transaction_read_only ParameterStatus read on; SHOW transaction_read_only and pg_is_in_recovery() report a replica; writes fail with SQLSTATE 25006 (read_only_sql_transaction). Storing a SCRAM verifier on login is skipped on non-leaders.
Redis READONLY You can't write against a read only replica. Leader is X.
CouchDB HTTP 503 with {"error":"not_leader", ...} naming the leader
Other wires The storage error from the hook, mapped by each wire's generic error path

(source: src/protocol/postgres/mod.rs, standby_flag, store_scram_verifier; src/query/engine.rs, transaction_read_only; src/protocol/redis/commands.rs; src/protocol/couchdb/api.rs)

There is no write forwarding: a follower never proxies a write to the leader. A client must connect to the leader. The supported ways to find it are libpq target_session_attrs=read-write with a multi-host connection string, or a load balancer health check on /cluster/writable. (source: src/distributed/replication.rs, before_write_batch; test-scripts/cluster/haproxy.cfg)

HTTP role endpoints

Endpoint Status Body
GET /cluster/role Always 200 {"role", "writable", "leader"}
GET /cluster/writable 200 on a leader or standalone node, 503 on a replica Same body

Both endpoints need no authentication. (source: src/protocol/http/routes.rs, cluster_role, cluster_writable)

Read gate after a crash (PostgreSQL only)

A node that restarts with a non-empty Raft log refuses PostgreSQL queries until it has applied entries up to the commit index it learns from the leader. Queries in that window fail with SQLSTATE 25006 and "node is recovering and has not caught up; reads are temporarily unavailable". The details are in Raft internals. Not wired: no other wire checks the gate, so a recovering node can serve stale reads over MySQL, MongoDB, Redis and the rest. (source: src/distributed/raft.rs, ready_to_serve; src/server/mod.rs, PostgreSQL handler setup)

6. Replication modes

[cluster] mode takes one of three values. (source: src/config.rs, ClusterMode, ClusterConfig)

Mode What the code does
Standalone (default) Raft is not started; the node is writable
Replicated Starts Raft: one group, every node holds the full data set, single leader
Distributed Same code path as Replicated; there is no sharded data path
[cluster] field Default Used by
mode Standalone init_cluster
node_id "node-1" Raft node id, Raft directory name
peers empty id@host:port list
cluster_port none Raft listen port; required to start Raft
secret none Section 2
snapshot_threshold 0 (off) Snapshot policy, see Raft internals
replication_factor 3 Validated as non-zero; Not wired: no code reads it

Every field can be set from the environment as SYNERGYDB_CLUSTER_<FIELD>, for example SYNERGYDB_CLUSTER_PEERS. (source: src/config.rs, ClusterConfig, env overrides; test env_overrides_reach_every_section_and_type)

Replication is synchronous to a majority: the client is acknowledged only after the entry is committed by a quorum and applied on the leader. There is no asynchronous mode, no per-statement durability knob and no read-from-follower consistency option. (source: src/distributed/replication.rs, before_write_batch)

7. Tests

Test What it checks
peers_sharing_the_secret_exchange_rpcs Round trip with a shared secret
an_authenticated_peer_accepts_a_large_entry 512 MiB cap path
an_unauthenticated_peer_keeps_the_small_frame_cap 8 MiB cap without a secret
a_peer_with_the_wrong_secret_changes_nothing Wrong secret, no state change
a_peer_without_a_secret_is_refused Server with a secret, client without
a_node_without_a_secret_rejects_the_handshake Server without a secret, client with
a_recorded_request_cannot_be_replayed Replay on a new connection
a_response_cannot_pass_for_a_request Direction separation
refuses_a_routable_bind_without_a_secret Loopback-only plaintext
test_request_vote_serialization, test_append_entries_serialization bincode round trip
own_writes_are_recognised_once_per_submit mark_local and take_local counting
role_transitions, standalone_process_is_writable node_role

(source: src/distributed/rpc.rs, src/distributed/replication.rs, src/distributed/node_role.rs, #[cfg(test)] modules)

End-to-end checks are Python harnesses that start real server processes on loopback:

Script Scenarios
test-scripts/cluster/raft_net_test.py Election, role reporting, replication, failover, split brain, follower rejoin, snapshot catch-up
test-scripts/cluster/haproxy_failover_test.py Writes through HAProxy across a leader failure
test-scripts/cluster/multiwire_failover_test.py kill -9 of the leader while seven wires write

These scripts are run by hand; their recorded results are in test-scripts/cluster/RAFT_READINESS.md and the dated status entries. (source: test-scripts/cluster/)

tests/distributed_raft_test.rs does not test this code. It defines its own SimulatedRaftNode, never imports the synergydb crate, and its partition helpers only log. (source: tests/distributed_raft_test.rs)

Not verified: no automated test covers the sync/async bridge in before_write_batch, the per-wire refusal messages, or the /cluster/* endpoints. The Python harnesses cover them only when someone runs them. (source: search of src/ and tests/ for test modules)