Server Runtime: Process Startup and Shutdown

This page follows the synergydb process from main to exit: runtime construction, configuration loading, the order in which subsystems start, how each wire's listener is created, and what shutdown does. Per-connection behaviour is in Connection handling. Command-line flags are listed in full in the CLI reference. The operator view is in Operations.

1. main: before the runtime exists

main in src/main.rs runs these steps synchronously, in order. (source: src/main.rs, main)

Step What happens
1 protocol::tls::install_default_crypto_provider() installs rustls' ring provider as the process default. rustls needs an explicit choice when more than one provider is compiled in.
2 If SYNERGYDB_MEMORY_LOG_SECS is a positive integer, heap::enable() turns on live-heap byte counting in the global allocator wrapper.
3 A tracing_subscriber::fmt subscriber is installed with EnvFilter from RUST_LOG, default warn, writing to stderr. try_init is used so an embedding process's subscriber is kept.
4 If the first argument is passwd, backup, restore, backup-verify, encryption or audit, the matching offline command runs and its exit code is returned. No server starts.
5 protocol::raise_open_files_limit() raises the RLIMIT_NOFILE soft limit to the hard limit (Unix only). On macOS, where the hard limit can read as unlimited, it retries with 10,240. A result below 4,096 logs a warning.
6 A multi-thread tokio runtime is built: 64 worker threads, 8 MiB stack per worker, enable_all, and a thread-start hook that registers each worker with the heap counter. Failure exits with code 1.
7 runtime.block_on(async_main()).

The 8 MiB worker stack exists because the query engine recurses synchronously (foreign-key cascades and triggers re-enter the full DML path); the source comment says the default stack overflowed before the engine's depth guards could fire. (source: src/main.rs, main)

The global allocator is mimalloc wrapped in heap::Counting; the system-allocator Cargo feature switches to the system allocator. (source: src/lib.rs, #[global_allocator]; Cargo.toml)

2. async_main: configuration and safety checks

  1. Parse arguments. -h, -v and --generate-config print or write and return. An unknown argument prints "Unknown argument" and sets the help flag, so the process prints help and exits 0.
  2. Print the banner.
  3. If SYNERGYDB_SUPERUSER_PASSWORD is unset or empty and SYNERGYDB_ADMIN_PASSWORD is set, copy the latter into the former (compatibility with older Helm charts).
  4. With --dev: default SYNERGYDB_SUPERUSER to postgres, SYNERGYDB_SUPERUSER_PASSWORD to postgres and SYNERGYDB_DATABASE to synergydb when unset; always set SYNERGYDB_NON_INTERACTIVE=1.
  5. load_config: the file from -c, else SYNERGYDB_CONFIG, else ./synergydb.toml. A missing default file means built-in defaults; a missing or unparsable explicit file is an error. Then SYNERGYDB_<SECTION>_<KEY> overrides (problems are printed as warnings), then Config::validate. Any error returns exit code 1.
  6. Bind address precedence: --bind over --localhost over --bind-all over --dev (which forces 127.0.0.1) over the file. Then SYNERGYDB_BIND_ADDRESS, if set, overrides all of them.
  7. SYNERGYDB_KAFKA_ADVERTISED_HOST, if set and non-empty, sets server.kafka_advertised_host.
  8. wire_auth::set_protected_mode(server.protected_mode.unwrap_or(true)).
  9. If the bind address is not loopback (localhost or a loopback IP):
    • If SYNERGYDB_DEV_INSECURE_AUTH or SYNERGYDB_TEST_AUTH_CHEAP is 1 or true, protected mode is on, and SYNERGYDB_ALLOW_INSECURE_BIND is not set, print a FATAL message and process::exit(1).
    • If SYNERGYDB_SUPERUSER_PASSWORD is one of CHANGE_ME, CHANGE_ME_IN_PRODUCTION, changeme, CHANGEME, print a FATAL message and process::exit(1).
  10. Print the data directory, WAL directory and bind address.
  11. Server::new(config).start(). An error prints "Failed to start server: …" and returns exit code 1.
  12. Print "SynergyDB is ready to accept connections!", wait for a shutdown signal (section 6), run Server::shutdown, print "Goodbye!" and return exit code 0.

(source: src/main.rs, Args::parse, async_main, load_config)

Not verified: --dev combined with --bind-all passes step 9, because the dev password postgres is not in the placeholder list. No test covers async_main. (source: src/main.rs, async_main)

3. Server::start: subsystem order

Server holds the configuration, the storage engine, one shutdown sender per started wire, a list of storage close hooks and the optional RaftCluster. start runs in this order. (source: src/server/mod.rs, Server, Server::start)

Order Step Failure behaviour
0 observability::metrics::init_metrics() Infallible; see Observability internals
1 init_storage: StorageEngine::open(storage.to_storage_config()), then vector::sources::resume (restart the cross-wire vector indexer) Error aborts startup
2 run_bootstrap: bootstrap_if_needed. After a first bootstrap, storage.flush() and storage.sync() (failures there only warn) Bootstrap error aborts startup
3 init_cluster (no-op in Standalone); see Cluster RPC and routing Error aborts startup
4 protocol::tls::resolve_tls_config(&config.tls, data_dir) TLS enabled with no certificate source aborts startup
5 start_audit_logger when [audit] enabled Missing path, bad key or require_key with no key aborts startup
6 Start each enabled wire in a fixed order (section 4) A port that cannot be bound aborts startup
7 startup_memory::summary, spawn_monitor, spawn_periodic (section 5) Infallible

(source: src/server/mod.rs, Server::start, init_storage, run_bootstrap)

If a later step fails, wires started by earlier steps are already listening. async_main then returns exit code 1 and the runtime is dropped, which ends the process without running Server::shutdown, so the storage engine is not closed cleanly and the next start replays the WAL. (source: src/main.rs, async_main; src/server/mod.rs, Server::start)

Audit logger

start_audit_logger reads the HMAC key from SYNERGYDB_AUDIT_KEY, else from [audit] key_file. Without a key it refuses to start if require_key is set and otherwise warns that the chain is unkeyed. It opens a FileAuditWriter with rotate_mb (minimum 1), retention_days and checkpoint_secs, installs the logger as the process-global sink with log_statement and log_parameters, and writes a DatabaseStartup record carrying the version, pid, whether the chain is keyed, the key id, retention and the previous chain head. Keyed chains use HMAC-SHA-256; unkeyed chains use SHA-256. The PostgreSQL handler is also given the logger directly. (source: src/server/mod.rs, start_audit_logger; src/auth/audit_chain.rs)

4. Per-wire listener setup

Order and defaults

Each wire starts only if its port is Some in [server]. Ports default as below; all bind to server.bind_address, which defaults to 127.0.0.1. (source: src/config.rs, ServerConfig::default; src/server/mod.rs, Server::start)

Order Wire (handler.name() printed at start) Default port TLS wiring in start
1 PostgreSQL 5432 with_tls; also audit logger and, in a cluster, the read gate
2 MySQL 3306 with_tls
3 MongoDB 27017 with_tls
4 Bolt 7687 with_tls
5 HTTP REST 8080 with_tls(Option); metrics_token
6 gRPC 9090 with_tls(Option)
7 Redis 6379 with_tls
8 Cassandra 9042 with_tls
9 Elasticsearch 9200 with_tls
10 CouchDB 5984 with_tls
11 Oracle 1521 with_tls(Option)
12 SQL Server 1433 with_tls(Option)
13 DynamoDB 8000 with_tls
14 ClickHouse native 9000 with_tls
15 ClickHouse HTTP 8124 with_tls
16 Snowflake 8443 with_tls
17 InfluxDB 8086 with_tls
18 Kafka 9092 with_tls(Option); require_sasl defaults to on unless SYNERGYDB_DEV_INSECURE_AUTH; advertised host
19 Schema Registry 8081 with_tls
20 Memcached 11211 with_tls; registers a storage close hook
21 SQLite (Hrana) off with_tls
22 S3 9100 with_tls
23 Prometheus remote storage 9091 with_tls
24 Gremlin 8182 with_tls(Option)
25 Arrow Flight 8815 with_tls(Option)

Every wire shares the one Arc<StorageEngine>. A handler's constructor is where it loads any in-memory state from storage (Redis keyspace, Cassandra catalog and so on), which is why start_handler takes a memory checkpoint per wire. (source: src/server/mod.rs, Server::start, start_handler)

start_handler

addr = bind_address:port
std::net::TcpListener::bind(addr)   // probe; error -> "<wire> protocol cannot listen on <addr>: <err>"
(tx, rx) = mpsc::channel(1); shutdown_txs.push(tx)
println!("Starting <wire> protocol on <addr>")
startup_memory::checkpoint(<wire>)
tokio::spawn(handler.start(addr, rx))  // errors printed to stderr, not returned

The probe bind exists because each handler binds inside its own task, where a failure is only logged; without the probe, a port clash left the server reporting ready while that wire served nothing. The probe listener is dropped before the handler binds, so a process that grabs the port in between still causes a logged-only failure. (source: src/server/mod.rs, start_handler; tests start_handler_fails_when_port_is_taken, start_handler_succeeds_on_a_free_port)

ProtocolHandler is the trait every wire implements: name(), default_port() and async fn start(addr, shutdown: mpsc::Receiver<()>). (source: src/protocol/mod.rs, ProtocolHandler)

ServerBuilder offers with_config, per-port setters for the first six wires and with_bind_address; it is a convenience for embedding and tests. (source: src/server/mod.rs, ServerBuilder)

5. Startup memory reporting

startup_memory reads VmRSS and VmHWM from /proc/self/status, so it does nothing on systems without procfs. (source: src/server/mod.rs, module startup_memory)

Function When Output
checkpoint(phase) After storage open, after vector resume, before each wire's task Growth since the last checkpoint: warn at 1 GiB or more, info at 256 MiB or more, else debug
summary() After all listeners info with RSS and peak
spawn_monitor Every 10 s for 180 s after startup RSS, peak and a breakdown: block cache, secondary indexes, SQL vector indexes, vector collections, per-thread heap (when counting), top 3 statements by memory
spawn_periodic Every SYNERGYDB_MEMORY_LOG_SECS seconds, on a dedicated thread, only when that variable is a positive integer RSS, anonymous RSS, peak, live heap, thread count, memtable size and the same breakdown

(source: src/server/mod.rs, startup_memory::checkpoint, summary, spawn_monitor, spawn_periodic, breakdown)

6. Signals and shutdown

Server::wait_for_shutdown returns on the first of:

Platform Signals
Unix SIGINT (Ctrl+C), SIGTERM. If the SIGTERM handler cannot be installed, only SIGINT, with a warning
Windows Ctrl+C, Ctrl+Break, console close, system shutdown

(source: src/server/mod.rs, shutdown_signal)

Server::shutdown then runs:

  1. If a global audit logger exists, log DatabaseShutdown and flush it on the blocking pool with a 10 s limit.
  2. Send () on every wire's shutdown channel, then drop the senders.
  3. Run each storage close hook on the blocking pool (Memcached registers one to flush its write-behind state).
  4. storage.sync() then storage.shutdown() on the blocking pool, which syncs the WAL, flushes memtables and saves the manifest. Prints "Storage engine closed cleanly" or the error.

(source: src/server/mod.rs, Server::shutdown)

Not verified: shutdown does not wait for wires to finish. Step 2 only sends the signal; each handler's accept loop exits when it sees it, but in-flight connection tasks and per-connection threads are not joined or drained before storage is closed. A statement running at that moment can race the storage shutdown. (source: src/server/mod.rs, Server::shutdown, start_handler)

Not wired: shutdown does not stop the Raft cluster. The RPC server, replicator, election and apply tasks keep running until the process exits, and a leader does not hand off leadership. Peers detect the loss by election timeout. (source: src/server/mod.rs, Server::shutdown, raft_cluster field)

7. Tests

Test Covers
start_handler_fails_when_port_is_taken Probe bind turns a port clash into a startup error
start_handler_succeeds_on_a_free_port Normal start
descriptor_exhaustion_is_recognised accept_error classification of EMFILE and similar
open_files_soft_limit_is_raised_to_the_hard_limit raise_open_files_limit
accept_error_backs_off_on_exhaustion Accept-loop backoff
env_overrides_reach_every_section_and_type and other config::tests Environment overrides and validation

(source: src/server/mod.rs, src/protocol/mod.rs, src/config.rs, test modules)

Not verified: nothing tests main, async_main, the bind-address precedence, the insecure-bind refusal, Server::start as a whole or Server::shutdown. End-to-end scripts under test-scripts/ start the binary but are run by hand. (source: search of src/ and tests/)