Architecture atlas
This page is the book's map of SynergyDB at main @ 8a689c5c (2026-11-30). It has seven diagrams. Each one draws only edges that were checked in the code, and each has a short explanation and a source line under it. The chapters linked from each section give the detail; this page gives the shape.
It replaces the June 2026 "System Design & Architecture Diagrams (Atlas)". That atlas was used for its list of topics only. Its diagrams and numbers are not reused.
Conventions used in the diagrams:
- A solid arrow is a call or a message that the code makes on the path shown.
- A dotted arrow is a path that exists only in some configurations (for example cluster mode), and the label says which.
- Function and type names are the ones in the source, so you can search for them.
Contents
- System overview
- Write path
- MVCC transaction lifecycle
- Query pipeline
- Raft cluster
- Wire-to-engine translation
- Proof harness flow
1. System overview
SynergyDB is one process. Server::start opens one StorageEngine, runs bootstrap, starts Raft if [cluster] asks for it, and then starts one listener for every wire whose port key is set in the config: 25 port keys over 24 wire directories (ClickHouse has a native and an HTTP port). start_handler pre-binds each port so a port clash fails startup (source: src/server/mod.rs, Server::start, Server::init_storage, start_handler). Tested by start_handler_fails_when_port_is_taken and start_handler_succeeds_on_a_free_port (src/server/mod.rs).
Every wire is handed the same Arc<StorageEngine>. From there the wires take one of three routes, and many wires use more than one:
| Route | What the wire does | Examples checked in code |
|---|---|---|
| SQL text | Hands statement text to QueryEngine::execute
|
PostgreSQL, MySQL, SQLite, Snowflake, Oracle, gRPC, Arrow Flight, HTTP (see Statement lifecycle) |
| Own state, persisted as SQL | Keeps a working copy in memory and writes it back through a QueryEngine
|
Bolt (_bolt_nodes), DynamoDB, Elasticsearch, S3 |
| Direct storage keys | Encodes its own records and calls StorageEngine (write_batch, write_batch_unsynced, scan_visit, get) |
MongoDB (mongodb:<db>:<coll>:<id>), Redis (__redis__:<key>), Kafka, InfluxDB |
(source: src/protocol/bolt/mod.rs, persist_node; src/protocol/dynamodb/mod.rs; src/protocol/elasticsearch/mod.rs; src/protocol/s3/mod.rs; src/protocol/mongodb/commands.rs, collection_prefix_with_db; src/protocol/redis/commands.rs, REDIS_KEY_PREFIX; src/protocol/kafka/log.rs)
QueryEngine::new wraps the storage in a NamespacedStorage that prefixes each key with the session's database, and takes the transaction manager from TransactionManager::shared_for(&storage), a process registry keyed by the storage engine. Every SQL session on one engine therefore shares one commit clock, one lock table and one SSI tracker (source: src/query/engine.rs, QueryEngine::new; src/transaction/mvcc.rs, TransactionManager::shared_for). The MongoDB wire takes the same shared manager (source: src/protocol/mongodb/mod.rs). The Redis, Kafka and InfluxDB wires do not use TransactionManager at all (source: search of src/protocol/redis/, src/protocol/kafka/, src/protocol/influxdb/ for TransactionManager). So "one MVCC layer" in the README holds for the SQL engine and the MongoDB wire, not for every wire. See MVCC.
The cluster layer is off by default. When [cluster] mode is not Standalone and cluster_port is set, init_cluster installs a RaftReplicationHook on the storage engine. From then on every write_batch, write_batch_unsynced and put_unsynced asks the hook first (source: src/server/mod.rs, init_cluster; src/storage/mod.rs, write_batch, write_batch_unsynced, put_unsynced). Section 5 covers that path.
The vector service is opened from the storage engine (storage.vectors()), and init_storage resumes cross-wire vector collections right after the engine opens (source: src/server/mod.rs, init_storage; src/vector/sources.rs, resume).
Source: src/server/mod.rs, src/query/engine.rs, src/transaction/mvcc.rs, src/storage/mod.rs, the wire directories named above. Detail: Storage engine overview, Server runtime, Repository map.
2. Write path
This is a two-statement transaction over the PostgreSQL wire: BEGIN; INSERT ...; COMMIT.
What the diagram shows, step by step:
- Writes in an explicit transaction go to the transaction's
write_bufferafter the engine takes the row lock. Storage is not touched until COMMIT (source:src/transaction/mvcc.rs,Transaction::record_write;src/query/engine.rs,acquire_row_lock). -
commit_transactionvalidates first (commit_validate_only), then writes the whole buffer as one batch at the commit timestamp while the row locks are still held, then releases the locks. A comment explains the order: validating before the write means a failed validation never touches storage, and holding the locks across the write closes the lost-update window (source:src/query/engine.rs,commit_transaction,write_commit_batch). -
write_commit_batchcallsNamespacedStorage::write_batch_then, which appends without fsync (write_batch_unsynced), tells the transaction manager the timestamp has landed (applied_at, which releases statement snapshots waiting on it), and then callsgroup_syncfor the fsync (source:src/query/engine.rs,write_commit_batch;src/storage/namespaced.rs,write_batch_with;src/transaction/mvcc.rs,applied_at). - Inside the engine, values are bincode-encoded outside the lock. Under the WAL mutex each entry gets a sequence number and a WAL frame, and one commit marker with the entry count closes the batch. A failed append rolls the WAL back to its length before the batch (
rollback_to) with the memtable untouched (source:src/storage/mod.rs,write_batch_local_opts). - The WAL lock is released before the memtable inserts.
insert_versionedkeeps an older version when a live snapshot still needs it (source:src/storage/mod.rs,write_batch_local_opts,snapshot_watermark;src/storage/memtable.rs,MemTable::insert_versioned). - The background flush loop wakes every 100 ms, writes the oldest immutable memtable to an L0 SSTable, records it in the manifest, prunes WAL segments that are flushed and not held for a backup, and asks the compaction manager for work. Compaction compacts L0 when it has too many files and other levels when they exceed their byte budget, merging into the next level (source:
src/storage/mod.rs,background_flush_loop,flush_memtable_to_sst,cleanup_old_wal_files;src/storage/compaction.rs,maybe_schedule_compaction,needs_compaction,pick_compaction).
wal_sync_mode changes only the fsync step. Under no_sync, group_sync returns after handing the buffer to the OS; under periodic a commit round fsyncs only after 100 entries or 10 ms (source: src/storage/mod.rs, group_sync; src/storage/wal.rs, prepare_group_sync). See WAL sync modes.
Two writes skip this path. A large bulk COPY commit can go to ingest_bulk, which writes an L0 SSTable directly, and autocommit statements take a commit timestamp from begin_applying instead of creating a Transaction (source: src/query/engine.rs, write_commit_batch; src/storage/mod.rs, ingest_bulk_prefixed; src/transaction/mvcc.rs, begin_applying).
Tested by committed_multiwrite_batch_recovers_atomically (crash_atomicity_tests) and concurrent_durable_commits_all_complete_and_survive_reopen (group_commit_tests) in src/storage/mod.rs, and by the kill -9 restart phases of the differential suites (section 7).
Source: src/query/engine.rs, commit_transaction; src/storage/namespaced.rs; src/storage/mod.rs; src/storage/wal.rs; src/storage/compaction.rs. Detail: Storage engine overview, Write-ahead log, Memtable, SSTable format.
3. MVCC transaction lifecycle
This is a SQL transaction on the PostgreSQL dialect, as the session sees it. SQLSTATEs are the ones the PostgreSQL wire sends.
The states map onto the code like this:
| State in the diagram | Code |
|---|---|
| Active |
TransactionState::Active; begin_with_priority assigns the id, start_ts and, for Snapshot Isolation and Serializable, a ReadView
|
| FailedBlock | The session flag txn_failed. abort_failed_transaction_now has already aborted the MVCC transaction; the session refuses statements until ROLLBACK, and turns COMMIT into ROLLBACK |
| Validating |
commit_validate_only, steps 1 to 4 |
| Committed |
TransactionState::Committed, set in commit_validate_only once commit_ts is allocated |
| Aborted | TransactionState::Aborted |
(source: src/transaction/mvcc.rs, TransactionState, begin_with_priority, commit_validate_only, abort; src/query/engine.rs, execute_top, abort_failed_transaction_now, commit_transaction, rollback_transaction)
TransactionState also has a Preparing variant. Nothing assigns it (source: search of src/transaction/ for Preparing).
Reads: Read Committed takes one statement snapshot per read-only statement; Snapshot Isolation and Serializable read at start_ts - 1 for the whole transaction. Both overlay the transaction's own buffered writes (source: src/transaction/mvcc.rs, statement_snapshot, Transaction::snapshot_read_ts; src/query/engine.rs, execute_plan).
Where each error comes from:
| Point | Error variant | PostgreSQL SQLSTATE | Origin |
|---|---|---|---|
| Lock wait finds a cycle | Deadlock |
40P01 | src/transaction/lock.rs |
| Lock wait passes its deadline | LockTimeout |
55P03 | src/transaction/lock.rs |
| REPEATABLE READ or SERIALIZABLE update of a row changed after the snapshot | TransactionConflict |
40001 |
src/query/engine.rs, check_serializable_row
|
| Statement inside a failed block | TransactionAborted |
25P02 |
src/query/engine.rs, execute_top
|
| COMMIT on a transaction that is not Active, or past its timeout (600 s by default) | TransactionAborted |
25P02 |
src/transaction/mvcc.rs, commit_validate_only
|
| SSI dangerous structure | TransactionConflict |
40001 |
src/transaction/ssi.rs, SsiTracker::check_cycles
|
A written key was committed by another transaction at or after start_ts (SI and Serializable), or a read key was (Serializable) |
TransactionConflict |
40001 |
src/transaction/mvcc.rs, check_write_conflicts, check_read_write_conflicts
|
| Write on a Raft follower | ReadOnly |
25006 |
src/storage/mod.rs, write_batch
|
(source: the files named; src/protocol/postgres/mod.rs, PostgresHandler::error_to_sqlstate). MySQL, SQL Server and the other wires map the same variants to their own codes; see Error model and wire error codes.
Dialect differences the diagram does not draw:
- A statement error does not enter FailedBlock when a savepoint exists or the dialect is SQL Server (source:
src/query/engine.rs,execute_top). - MySQL sessions skip the PostgreSQL failed-block rule; a deadlock error rolls the transaction back (source:
src/query/engine.rs,execute_top). - MySQL and SQL Server sessions at REPEATABLE READ or SERIALIZABLE set
current_read_writes, which skips commit-time validation, the SSI check andcheck_serializable_row. A conflicting writer waits on the row lock instead (source:src/query/engine.rs,mark_mysql_txn;src/transaction/mvcc.rs,commit_validate_only).
Not verified: commit_validate_only sets the state to Committed before the engine writes the batch. If that storage write then fails, commit_transaction releases the locks and returns the error, but the transaction manager has already recorded the commit. No test was found for a storage failure after validation (source: src/query/engine.rs, commit_transaction; src/transaction/mvcc.rs, commit_validate_only).
Tested by test_write_write_conflict, test_failed_commit_releases_locks_and_removes_from_active (src/transaction/mvcc.rs), test_ssi_write_skew_detected, repeatable_read_update_of_concurrently_changed_row_is_40001 and test_cross_model_txn_invisible_to_concurrent_session_until_commit (src/query/engine.rs).
Source: src/transaction/mvcc.rs, src/transaction/ssi.rs, src/transaction/lock.rs, src/query/engine.rs. Detail: MVCC, Isolation levels and SSI, Locking, Savepoints and transactional DDL.
4. Query pipeline
One simple-query message on the PostgreSQL wire, from bytes to bytes.
There is no separate syntax tree: the parsers produce LogicalPlan directly and the engine interprets it (source: src/query/sql/parser.rs, Parser::parse; src/plan/logical.rs, LogicalPlan). parse_query sends text to the SQL, Cypher or MQL analyzer by detect_language. GraphQL and SynergyQL go to the SQL analyzer and SPARQL is refused with "SPARQL queries not supported in QueryEngine" (source: src/query/engine.rs, parse_query, detect_language).
The optimizer is a fixed rule list
QueryEngine builds its optimizer with Optimizer::new(). That runs these rules, in this order, over the plan, repeating the whole list until a pass changes nothing or 10 passes have run (source: src/plan/optimizer.rs, Optimizer::new, Optimizer::optimize; src/query/engine.rs, QueryEngine::new):
| Order | Rule |
|---|---|
| 1 | PredicatePushdown |
| 2 | ProjectionPushdown |
| 3 | ConstantFolding |
| 4 | FilterMerge |
| 5 | LimitPushdown |
| 6 | JoinElimination |
| 7 | RedundantProjectElimination |
After the rules, cost_reorder_top runs one cost-based step. Under a top-level projection with no *, it reorders a tree of inner joins over distinct base tables greedily by row count, but only when every table has row counts from ANALYZE in the process-wide statistics. Without ANALYZE statistics it changes nothing (source: src/plan/optimizer.rs, cost_reorder_top, try_reorder_inner_tree, row_estimate). Tested by cost_reorder_puts_smaller_relation_on_build_side, cost_reorder_skips_wildcard_projection and cost_reorder_multiway_chain_orders_and_attaches_predicates (src/plan/optimizer.rs).
So the planner is not a cost-based search over plans. Index choice is made later, at execution, by the engine's access-path code, not by the optimizer (see Statement lifecycle).
Not wired: Optimizer::with_join_ordering, Optimizer::with_full_optimization, JoinOrderingRule, JoinOrderOptimizer and AdaptiveQueryOptimizer are defined in src/plan/optimizer.rs and re-exported from src/plan/mod.rs, but nothing in src/ outside those two files uses them (source: search of src/).
The comment above the optimizer call in execute_with_timeout_inner still calls the optimizer "OFF BY DEFAULT and EXPERIMENTAL". optimizer_enabled returns true unless SYNERGYDB_OPTIMIZER is 0, false or off (source: src/query/engine.rs, optimizer_enabled).
Source: src/protocol/postgres/mod.rs, handle_query_generic; src/query/engine.rs; src/plan/optimizer.rs. Detail: Statement lifecycle, Parser, SQL reference.
5. Raft cluster
5.1 Roles and elections
A node runs one Raft group; every node holds the whole keyspace. RaftCluster::start always turns PreVote on. When the election timer (3 to 6 s by default) expires, the node only marks an election as due. The election driver then asks every peer for a PreVote at term + 1; a peer refuses if it heard from a leader recently or the asker's log is behind. Only with a majority does begin_candidacy raise the term and vote for itself. persist_candidacy saves term and vote before any RequestVote goes out. become_leader re-checks the term, resets next_index and match_index and appends an empty entry so earlier-term entries can commit (source: src/distributed/rpc.rs, RaftCluster::start; src/distributed/raft.rs, run_election_timer, handle_pre_vote, begin_candidacy, persist_candidacy, become_leader).
The quorum monitor steps a leader down at the same term when fewer than a quorum of nodes have answered an AppendEntries or InstallSnapshot within ten times the maximum election timeout, 60 s with the defaults (source: src/distributed/rpc.rs, quorum monitor in RaftCluster::start; src/distributed/raft.rs, step_down_to_follower).
Tested by pre_vote_keeps_a_lagging_follower_from_deposing_the_leader (src/distributed/rpc.rs, three nodes over loopback TCP), candidacy_is_durable_before_vote_fanout, become_leader_checks_term_and_appends_noop and step_down_fails_pending_waiters (src/distributed/raft.rs).
5.2 A replicated write
write_batch is the single gate: on a node with a hook, the hook decides ApplyLocally, Replicated or Reject. The leader replicates the resolved key/value mutations and the MVCC timestamp, not SQL text. It waits for commit (up to commit_timeout, 30 s) and then for its own apply loop to apply that index before it acknowledges. Followers apply the same entries through the same apply loop (source: src/storage/mod.rs, write_batch; src/distributed/replication.rs, RaftReplicationHook::before_write_batch, ReplicatedWrite, spawn_apply_loop, apply_log_entry; src/distributed/rpc.rs, RaftCluster::submit; src/distributed/raft.rs, maybe_advance_commit_index, wait_applied).
A write that times out after commit returns an error to the client although the entry is in the Raft log ("write committed (index N) but not applied locally") (source: src/distributed/replication.rs, before_write_batch).
5.3 Failover
When the leader stops, followers stop receiving AppendEntries. After an election timeout one of them wins PreVote and RequestVote as in 5.1 and appends its no-op. There is no write forwarding: clients must find the new leader themselves, through libpq target_session_attrs=read-write with several hosts or a load balancer probing GET /cluster/writable, which answers 503 on a replica (source: src/distributed/replication.rs, before_write_batch; src/protocol/http/routes.rs, cluster_writable; test-scripts/cluster/haproxy.cfg). A restarted node refuses PostgreSQL reads with 25006 until its apply loop has caught up to the log it recovered; other wires do not check this gate (source: src/distributed/raft.rs, ready_to_serve; src/server/mod.rs, set_read_gate).
End-to-end failover is tested only by the Python harnesses test-scripts/cluster/raft_net_test.py, haproxy_failover_test.py and multiwire_failover_test.py, which are run by hand and not by cargo test. tests/distributed_raft_test.rs defines its own simulated node and does not exercise src/distributed/ (source: test-scripts/cluster/; tests/distributed_raft_test.rs).
5.4 What the cluster layer does not do
| Item | What the code does | Source |
|---|---|---|
mode = "Distributed" |
Same path as Replicated: init_cluster only tests for Standalone
|
src/server/mod.rs, init_cluster
|
| Sharding and two-phase commit |
shard.rs and coordinator.rs exist; nothing outside src/distributed/ uses them |
search of src/; Sharding and 2PC
|
replication_factor |
Checked to be non-zero; not read by Raft | src/config.rs |
| Membership change | None: peers are fixed at startup, no AddServer or RemoveServer, no joint consensus |
src/distributed/raft.rs, src/distributed/rpc.rs
|
| Follower reads with a bound | None: no read index or lease; followers read local state | src/distributed/raft.rs |
| Write forwarding | None: a follower rejects writes | src/distributed/replication.rs |
| Streaming snapshots | None: a snapshot is a full in-memory copy, capped at 1 GiB on receive |
src/distributed/replication.rs, serialize_keyspace_snapshot; src/distributed/raft.rs, MAX_SNAPSHOT_TRANSFER_BYTES
|
| Raft stop on shutdown |
Server::shutdown never calls RaftCluster::stop
|
src/server/mod.rs, Server::shutdown
|
Source: src/distributed/raft.rs, src/distributed/rpc.rs, src/distributed/replication.rs, src/server/mod.rs. Detail: Raft consensus internals, Cluster RPC, leader routing and replication modes, Operations: cluster mode.
6. Wire-to-engine translation
Three requests that end in the same StorageEngine by different routes.
MongoDB find. The MongoDB wire does not use QueryEngine or the MQL analyzer in src/query/mql/. handle_find reads documents straight from storage keys mongodb:<db>:<collection>:<id> with scan_visit (or point gets for _id lookups and index candidates), filters them with its own matches_filter, then sorts, skips, limits and projects them before building the cursor reply (source: src/protocol/mongodb/mod.rs, handle_op_msg; src/protocol/mongodb/commands.rs, dispatch, handle_find, load_matching_documents, scan_collection, collection_prefix_with_db). Its writes commit through the shared TransactionManager and one write_batch at the commit timestamp (source: src/protocol/mongodb/commands.rs, comments and code around write_batch; src/protocol/mongodb/mod.rs). Tested by autocommit_write_is_visible_through_mvcc_layer (src/protocol/mongodb/commands.rs).
Redis SET. Redis commands execute against an in-memory map, as in Redis, and storage is a write-through copy. execute takes a shared isolation gate (exclusive for EXEC and scripts); before_write takes per-key stripe locks; set updates the map; after_write calls persist_command, which writes the key's new record with write_batch_unsynced at timestamp 0 under __redis__:<key> (database 0) or __redisdb__:NN:<key>. sync_persisted then waits on the redis-fsync thread, which runs one group_sync for every waiting connection, and only then is the reply sent. Inside EXEC or a script the writes are held and written as one batch at the end (source: src/protocol/redis/mod.rs; src/protocol/redis/commands.rs, execute, before_write, set, after_write, REDIS_KEY_PREFIX; src/protocol/redis/commands/persist.rs, persist_command, snapshot_value, store_batch, commit_tx_writes, DurabilitySyncer, value_storage_key). The Redis wire does not use TransactionManager. Tested by test_set_persists_to_redis_store and test_data_survives_restart (tests/protocol_redis.rs).
Cypher MATCH. Cypher text sent through a SQL wire goes into QueryEngine::execute. detect_language recognises it, the Cypher planner builds a GraphMatch plan, and execute_plan_inner routes plans whose leaf is a graph operator to execute_graph_query, which reads __graph_nodes__ with an ordinary table scan through NamespacedStorage (source: src/query/engine.rs, detect_language, parse_query, plan_leaf_is_graph, execute_graph_query, execute_graph_node_match; src/query/cypher/planner.rs, node_to_plan). Tested by test_engine_cypher_create_then_match_roundtrip and test_engine_cypher_create_edge_then_match_traverses (src/query/engine.rs).
A MATCH sent over the Bolt wire takes a different route: execute_cypher sends it to execute_match, which reads the Bolt wire's own in-memory GraphStore. That store is loaded from, and written back to, the SQL tables _bolt_nodes and _bolt_relationships through a QueryEngine (source: src/protocol/bolt/mod.rs, execute_cypher, execute_match, GraphStore, persist_node). The two graph stores do not see each other's writes; see How it works.
What is shared, then, is the StorageEngine (WAL, memtables, SSTables, group commit, replication hook). Above it, the three requests use different key spaces, different evaluators and, for Redis, no MVCC transaction manager.
Source: the files named above. Detail: MongoDB protocol, Redis protocol, Neo4j Bolt protocol, Keys and namespaces.
7. Proof harness flow
make prove is how the wire scores in this book were produced.
How it runs:
-
make proverunsprove/prove.sh, which checks Docker and Python, builds SynergyDB with--features fullunlessSDB_BINpoints at a binary, sets up a virtual environment with the client drivers fromprove/requirements.txt, removes leftoverref-*containers and runsprove.py.make prove-quickpasses--skip-bench;make benchpasses--bench-only(source:Makefile;prove/prove.sh). - For each wire,
run_wirestarts and waits for the reference containers, starts a fresh SynergyDB withsdb.sh fresh <profile>, runs every step thatwires.pylists for the wire, optionally runs throughput on another fresh SynergyDB, and stops both (source:prove/prove.py,run_wire,run_step,run_bench;prove/refs.py). - The comparison happens inside each suite under
test-scripts/: the suite sends the same operations to both servers and counts matches.prove.pyonly reads the suite's printed score lines with the regexes inwires.py, overall and per phase (source:prove/wires.py,Step,Wire;prove/prove.py,parse). - The restart phase is the suite calling the
{sdb_restart}command, which issdb.sh restart:kill -9by default, then start and wait.PROVE_RESTART=gracefulsends SIGTERM instead (source:prove/prove.py,fill;prove/sdb.sh,restart). - After every wire,
results.jsonis rewritten andreport.renderwritesreport.mdandreport.html, so a partial report is always on disk. A run without--outgoes toprove/out/<UTC timestamp>/and moves theprove/out/latestsymlink (source:prove/prove.py,main;prove/report.py). - The gate is a separate command.
prove/gate.py results.json [baseline]fails when a wire's reference or SynergyDB did not start, a step has no score, a baseline step is missing, or a step passed fewer checks than itsmininprove/ci-baseline.json. Wires not in the run are ignored (source:prove/gate.py,main;prove/ci-baseline.json,_about).
Not wired: neither make prove nor prove.sh nor prove.py calls gate.py, and no CI workflow file is in the snapshot. gate.py appends its table to $GITHUB_STEP_SUMMARY when that variable is set, which suggests a GitHub Actions job, but this page cannot confirm one (source: search of the snapshot for gate.py).
The harness itself has no automated test. Its outputs for the 2026-11-30 run are under docs/proof/2026-11-30/, and the per-wire numbers are in the wire guides.
Source: Makefile, prove/prove.sh, prove/prove.py, prove/wires.py, prove/sdb.sh, prove/refs.py, prove/report.py, prove/gate.py, prove/ci-baseline.json. Detail: Overview: how a wire is proven, Benchmarks and reproduction.