Sharding, Two-Phase Commit and the Circuit Breaker

Not wired and untested as a system. Everything on this page is library code in src/distributed/ that no part of the server calls. The server never constructs a ShardManager, HashRing, DistributedCoordinator, Coordinator, Participant or CircuitBreaker, and nothing starts the two-phase-commit listeners. No integration test or test script drives any of it. Unit tests exercise individual structs in-process, which is all the coverage there is. The only multi-node data path that runs is the single Raft group described in Raft internals and Cluster RPC and routing, where every node holds the full data set. (source: search of src/ and tests/ for these type names outside src/distributed/)

This page describes the code so that a reader of src/distributed/ knows what it is and what it lacks. Nothing here describes behaviour a running server has.

1. Cluster state and shard selection in mod.rs

DistributedCoordinator wraps a tokio::sync::RwLock<ClusterState>. ClusterState holds the cluster mode, the local node id, a map of NodeInfo (id, address, NodeStatus, shard list, leader flag, last heartbeat), a shard_map: HashMap<u32, Vec<String>> and an optional leader id. Its methods add and remove nodes and look up a shard's nodes. All state is in memory; nothing persists it or fills it from Raft. (source: src/distributed/mod.rs, ClusterState, DistributedCoordinator)

DistributedCoordinator::compute_shard(key, num_shards) returns FNV-1a 32-bit of the key modulo num_shards. (source: src/distributed/mod.rs, compute_shard, hash_key)

Not verified: no tests in mod.rs.

2. Consistent hashing in shard.rs

HashRing

Property Value
Structure BTreeMap<u64, String> from ring position to node, plus a HashSet of physical nodes
Virtual nodes per physical node 150 (VIRTUAL_NODES), keyed as "{node}#{i}"
Hash FNV-1a 64-bit, for both virtual-node labels and keys
Lookup First ring position at or after the key hash, wrapping to the start
Replica set get_nodes(key, n) walks the ring from the key hash, skipping repeats, until n distinct nodes

Two virtual-node labels that hash to the same position overwrite each other in the map, and remove_node then removes the position for both. With 64-bit hashes this is unlikely but not handled. A source comment suggests replacing FNV with xxhash; the code uses FNV. (source: src/distributed/shard.rs, HashRing)

ShardManager

ShardManager holds a HashRing, a HashMap<u32, ShardInfo>, num_shards and replication_factor. (source: src/distributed/shard.rs, ShardManager)

Method What it does
get_shard(key) FNV-1a 32-bit of the key modulo num_shards
get_nodes_for_key(key) ring.get_nodes(key, replication_factor)
add_node, remove_node Update the ring, then call rebalance
rebalance Empty function body; the comment lists steps it does not perform
get_shard_info(id) Reads the shards map, which nothing ever fills, so it always returns None

get_shard and get_nodes_for_key use different hashes and different schemes (modulo versus ring), so the shard id a key maps to has no relation to the nodes that key maps to. ShardInfo declares range_start and range_end byte bounds and a ShardStatus, but no code assigns ranges. (source: src/distributed/shard.rs, get_shard, get_nodes_for_key, rebalance, ShardInfo)

Tested by test_hash_ring_basic (lookups are stable and return a member) and test_hash_ring_replication (get_nodes returns distinct nodes). Nothing tests ShardManager. (source: src/distributed/shard.rs, tests)

3. Two-phase commit in coordinator.rs

Roles and messages

A Coordinator drives transactions; a Participant votes and applies. Each has an RPC server (CoordinatorRpcServer, ParticipantRpcServer) and they talk through TwoPhaseCommitRpcClient. (source: src/distributed/coordinator.rs)

TwoPhaseCommitMessageType Request or response struct
PrepareRequest / PrepareResponse PrepareRequest { txn_id, coordinator_id, data, timestamp }; PrepareResponse { txn_id, participant_id, vote_commit, abort_reason }
CommitRequest / CommitResponse { txn_id, coordinator_id, timestamp }; { txn_id, participant_id, success, error }
AbortRequest / AbortResponse { txn_id, coordinator_id, reason, timestamp }; { txn_id, participant_id, success }
InquiryRequest / InquiryResponse { txn_id, participant_id }; { txn_id, status, timestamp }
Ack Declared

(source: src/distributed/coordinator.rs, TwoPhaseCommitMessageType and request structs)

Wire format

Each call opens a new TCP connection and sends a big-endian u32 length followed by a bincode TwoPhaseCommitRpcMessage { id, msg_type, payload }. The client applies a connect timeout and a request timeout. (source: src/distributed/coordinator.rs, TwoPhaseCommitRpcClient::send_message)

Both servers refuse to bind to anything but loopback, with the error "… it is unauthenticated and limited to loopback". There is no handshake, no encryption and no frame size cap on either side: the server and the client allocate whatever the length prefix says, up to 4 GiB. (source: src/distributed/coordinator.rs, CoordinatorRpcServer::start, ParticipantRpcServer::start, handle_connection, send_message)

Coordinator state machine

DistributedTxnState: Active, Preparing, Prepared, Committing, Committed, Aborting, Aborted. The status returned to an inquiry maps Active to Unknown, Committing to Committed and Aborting to Aborted. (source: src/distributed/coordinator.rs, DistributedTxnState, From<DistributedTxnState> for TransactionStatus)

Step Coordinator action
begin(participants) Allocate a TxnId from an atomic counter, log Begin, state Active
prepare(txn) Require Active; set Preparing; log PrepareStarted; send PrepareRequest to every participant in parallel with a 10 s timeout each. A participant with no client, an error or a timeout counts as an Abort vote. Each vote is logged as VoteReceived. Set Prepared if all voted commit, else Aborting.
commit(txn) Require Prepared; log Decision { commit: true }; set Committing; send CommitRequest to all with a 10 s timeout; record acks (AckReceived) or mark the ack Failed; set Committed; log Completed
abort_with_reason(txn, reason) Log Decision { commit: false }, send AbortRequest to all, log Completed { committed: false }
execute_transaction(...) begin_with_data, prepare, then commit or abort

(source: src/distributed/coordinator.rs, Coordinator::begin, prepare, commit, send_commit_to_all, abort_with_reason, execute_transaction)

Not verified: prepare and send_commit_to_all use a hard-coded 10 second timeout per participant on top of the client's own timeouts: register_participant passes prepare_timeout as the connect timeout and decision_timeout as the request timeout for every call, prepare included. commit marks the transaction Committed and logs Completed even when some participants failed to acknowledge, so recovery will not resend CommitRequest to them; the comment says the participant "will need to recover". (source: src/distributed/coordinator.rs, prepare, send_commit_to_all, register_participant)

Coordinator log and recovery

CoordinatorLog appends one JSON object per line (serde_json) to log_path and calls sync_all after every entry. CoordinatorLogEntry variants: Begin, PrepareStarted, VoteReceived, Decision, AckReceived, Completed. (source: src/distributed/coordinator.rs, CoordinatorLog::write, CoordinatorLogEntry)

recover replays the file, rebuilds each transaction's state, sets the next transaction id past the largest seen, and keeps only transactions not yet Committed or Aborted. A missing or unreadable log is treated as a fresh start. resume_transactions then aborts transactions left in Preparing and resends commit for those left in Prepared or Committing. (source: src/distributed/coordinator.rs, Coordinator::recover, resume_transactions)

Not verified: CoordinatorLog::truncate exists but nothing calls it, so the log grows without bound. A transaction recovered in Prepared has its commit resent without a logged Decision, which matches presumed-commit only if every vote was logged; that path has no test. (source: src/distributed/coordinator.rs, truncate, resume_transactions)

Background tasks

start_background_tasks runs a loop every cleanup_interval that drops finished transactions older than completed_txn_retention and aborts timed-out ones (handle_timeouts). It returns a channel sender used to stop the loop. (source: src/distributed/coordinator.rs, start_background_tasks, cleanup, handle_timeouts)

Configuration defaults

CoordinatorConfig field Default
node_id coordinator-1
rpc_addr 127.0.0.1:9000
log_path ./data/coordinator.log
txn_timeout 30 s
prepare_timeout 10 s
decision_timeout 10 s
cleanup_interval 60 s
completed_txn_retention 300 s

None of these is exposed in synergydb.toml. (source: src/distributed/coordinator.rs, CoordinatorConfig::default; src/config.rs)

Participant

Participant::handle_prepare always votes commit. It stores the transaction in an in-memory HashMap and returns vote_commit: true. Its comment lists validation, a prepare log record and resource locks as things "a real implementation" would do; none of them happens. handle_commit removes the entry and calls the optional commit callback; a callback error is logged and the response still reports success. A commit for an unknown transaction also reports success. handle_abort removes the entry and calls the abort callback. (source: src/distributed/coordinator.rs, Participant::handle_prepare, handle_commit, handle_abort)

recover_prepared_transactions asks the coordinator about each prepared transaction (inquire) and commits on Committed, aborts on Aborted or Unknown. Because the prepared set lives only in memory, it is empty after a restart, so this recovery has nothing to recover. (source: src/distributed/coordinator.rs, recover_prepared_transactions, Participant::prepared)

This is not a correct two-phase commit participant: it gives no guarantee that a participant that voted commit can still commit, and it loses its prepared state on a crash.

Tests

Unit tests in coordinator.rs, all in-process with no network:

Test Covers
test_vote_serialization, test_prepare_request_serialization, test_prepare_response_serialization, test_commit_request_serialization, test_abort_request_serialization, test_inquiry_serialization, test_log_entry_serialization serde round trips
test_distributed_txn_voting, test_distributed_txn_abort_vote, test_distributed_txn_timeout DistributedTxn vote counting and timeout
test_transaction_status_from_state State to status mapping
test_coordinator_begin_transaction, test_coordinator_manual_voting, test_coordinator_abort_vote, test_coordinator_get_status, test_coordinator_cleanup Coordinator state changes driven by direct method calls
test_participant_prepare_commit_abort Participant handlers called directly

No test sends a 2PC message over TCP, runs recovery from a log file, or runs a coordinator and participants together. (source: src/distributed/coordinator.rs, #[cfg(test)] module)

4. Circuit breaker in circuit_breaker.rs

A per-name breaker with three states held in an AtomicU8: Closed, Open, HalfOpen. CircuitBreakerRegistry keeps breakers by name. (source: src/distributed/circuit_breaker.rs, CircuitState, CircuitBreaker, CircuitBreakerRegistry)

CircuitBreakerConfig field Default
failure_threshold 5
open_duration 30 s
half_open_success_threshold 3
failure_window_secs 60
State allow_request record_success record_failure
Closed true Reset failure count to 0 Increment; open at threshold
Open false until open_duration has passed since opening, then move to HalfOpen and return true Ignored Ignored
HalfOpen true for every request Increment; close at half_open_success_threshold Open immediately

(source: src/distributed/circuit_breaker.rs, allow_request, record_success, record_failure)

Not verified: two defects in the code as written.

  • The failure window never expires. record_failure stores the current time in last_failure_at before calling reset_if_window_expired, which then measures the time since that just-written instant. So failures spread over any period accumulate until a success resets them.
  • HalfOpen admits every request, not a limited number, despite the comment.

(source: src/distributed/circuit_breaker.rs, record_failure, reset_if_window_expired, allow_request)

Tested by test_circuit_breaker_starts_closed, test_circuit_breaker_opens_after_failures, test_circuit_breaker_rejects_when_open and test_success_resets_failure_count. No test covers the half-open path or the window. (source: src/distributed/circuit_breaker.rs, tests)

5. What would be needed to use this code

For a reader planning work here, the gaps between this code and a sharded cluster are:

  • A routing layer that maps a key or statement to a shard and forwards it. None exists; every wire writes to local storage through the Raft hook.
  • Persistent shard ownership, replicated through Raft or another log. ClusterState and ShardManager are in memory only.
  • Rebalancing and data movement. rebalance is empty.
  • A participant that validates, locks and durably logs a prepare, and recovers from that log.
  • Authentication and frame limits on the 2PC transport, equivalent to the Raft transport.
  • A use of [cluster] replication_factor, which no code reads.

(source: src/distributed/; src/storage/mod.rs, write_batch; src/config.rs, ClusterConfig)