Connection Handling

This page covers what happens between a socket arriving on a wire port and a session task taking it over. It covers the accept loops, how each wire runs a session (tokio task, OS thread or worker), TLS at accept, timeouts, buffer and frame limits, backpressure, the client-side pool module, and what shutdown does to open connections. Process start-up and the order in which wires start are in Server Runtime. The wire-level protocol details are in the per-protocol pages under vol3/protocols and the per-wire pages under wires.

Overview

Every wire implements ProtocolHandler::start(addr, shutdown: mpsc::Receiver<()>). Server::start spawns one such task per enabled wire. The task binds a tokio::net::TcpListener and then loops on tokio::select! between listener.accept() and shutdown.recv() (source: src/protocol/mod.rs, ProtocolHandler; src/server/mod.rs, Server::start).

flowchart TD A["TcpListener::accept"] -->|"Ok(stream, peer)"| B["set_nodelay(true)"] A -->|"Err(e)"| E["protocol::accept_error: log, sleep 5 ms or 100 ms"] E --> A B --> C{"Execution model"} C -->|"default"| D["tokio::spawn(session)"] C -->|"PG / MongoDB / Oracle thread-per-conn"| F["OS thread, 8 MiB stack, current_thread runtime"] C -->|"Memcached"| G["round-robin to worker thread"] D --> H["ConnectionTracker::new(label)"] F --> H G --> H H --> I["Session loop until EOF, error or timeout"] S["shutdown.recv()"] --> X["break accept loop; sessions keep running"]

Source: src/protocol/mod.rs, accept_error; src/protocol/postgres/mod.rs, PostgresHandler::start; src/protocol/memcached/mod.rs, start_workers.

There is no server-wide connection limit, no global semaphore and no per-IP connection cap on any wire. Listeners are created with TcpListener::bind and no backlog, SO_KEEPALIVE or SO_REUSEPORT tuning (source: src/protocol/*/mod.rs, start). This matches the statement in the evaluator FAQ that there is no server-wide connection limit. The ResourceManager in src/observability/resources.rs has max_connections_per_protocol (100) and max_total_connections (500) fields, but nothing calls check_connection_allowed. Not wired: connection quotas (source: src/observability/resources.rs, ResourceManager::check_connection_allowed).

Accept loops per wire

Wire Accept mechanism Session model Error path ConnectionTracker label
PostgreSQL TcpListener + select! OS thread per connection by default, else tokio::spawn accept_error postgres
MySQL TcpListener + select! tokio::spawn accept_error mysql
MongoDB TcpListener + select! tokio::spawn, or OS thread with SYNERGYDB_MONGO_THREAD_PER_CONN accept_error mongodb
Redis TcpListener + select! tokio::spawn accept_error redis
Bolt (Neo4j) TcpListener + select! tokio::spawn accept_error none
HTTP / REST / GraphQL plaintext: axum::serve(...).with_graceful_shutdown; TLS: own loop with hyper http1 and upgrades hyper per connection TLS loop: accept_error http per request (middleware)
gRPC plaintext: tonic serve_with_shutdown; TLS: tls::grpc_incoming tonic TLS: accept_error grpc once at start, plus per request
Arrow Flight same as gRPC tonic TLS: accept_error none
Cassandra TcpListener + select! tokio::spawn accept_error cassandra
Elasticsearch TcpListener + select! tokio::spawn accept_error none
CouchDB TcpListener + select! tokio::spawn accept_error couchdb
Oracle TcpListener + select! tokio::spawn, or OS thread with SYNERGYDB_ORACLE_THREAD_PER_CONN accept_error oracle
SQL Server (TDS) TcpListener + select! tokio::spawn accept_error mssql
DynamoDB TcpListener + select! tokio::spawn accept_error dynamodb
ClickHouse native TcpListener + select! tokio::spawn accept_error clickhouse
ClickHouse HTTP TcpListener + select! tokio::spawn accept_error none
Snowflake TcpListener + select! tokio::spawn accept_error snowflake
InfluxDB TcpListener + select! tokio::spawn accept_error influxdb
Kafka TcpListener + select! tokio::spawn accept_error none
Schema Registry TcpListener + select! tokio::spawn accept_error none
Memcached TcpListener + select! worker threads, round-robin accept_error memcached
SQLite wire / Hrana TcpListener + select! (two listeners) tokio::spawn accept_error sqlite (protocol.rs only)
Prometheus TcpListener + select! tokio::spawn accept_error prometheus
Gremlin TcpListener + select! tokio::spawn accept_error none
S3 TcpListener + select! tokio::spawn, hyper per connection accept_result? none

Source: each wire's start function under src/protocol/; src/protocol/http/mod.rs, HttpHandler::start; src/protocol/grpc/mod.rs, GrpcHandler::start; src/protocol/arrow/mod.rs, start; src/protocol/s3/mod.rs, start; src/observability/metrics.rs, ConnectionTracker.

S3 exception

The S3 loop propagates an accept error with ?. One accept failure, such as EMFILE when the process runs out of descriptors, ends the S3 listener for the rest of the process lifetime. No other wire is affected (source: src/protocol/s3/mod.rs, start). Not verified: no test covers this path. The status entry 2026-11-30-open-files-and-accept-backoff.md says all 25 accept loops go through protocol::accept_error; S3 does not.

Alternate Arrow Flight path

FlightServer::serve in src/protocol/arrow/service.rs runs its own accept().await? loop with no shutdown branch. arrow/mod.rs uses tonic instead, so this function is not on the server's start path. Not wired: FlightServer::serve (source: src/protocol/arrow/service.rs, FlightServer::serve).

Accept error backoff and descriptor limit

accept_error(wire, &err) classifies the error and sleeps before the loop accepts again:

Condition Sleep
EMFILE, ENFILE, ENOBUFS, ENOMEM (Windows 10024, 10055) 100 ms
any other accept error 5 ms

It logs at most once every 10 seconds per wire. The log line carries a count of the errors suppressed since the last line (source: src/protocol/mod.rs, accept_error, accept_resource_exhausted).

At start-up raise_open_files_limit raises the soft RLIMIT_NOFILE to the hard limit. On macOS, where the hard limit can be RLIM_INFINITY, it falls back to 10,240 (source: src/protocol/mod.rs, raise_open_files_limit). Where it is called from is described in Server Runtime.

Tests: descriptor_exhaustion_is_recognised, open_files_soft_limit_is_raised_to_the_hard_limit, accept_error_backs_off_on_exhaustion (source: src/protocol/mod.rs, tests).

Execution models

Tokio tasks

Most wires call tokio::spawn with the session future on the main multi-thread runtime (64 workers, 8 MiB stacks; see Server Runtime). PostgreSQL wraps the spawned future in auth::audit::in_connection so audit records carry the connection context (source: src/protocol/postgres/mod.rs, PostgresHandler::start; src/auth/audit.rs, in_connection). Nearly all wires call set_nodelay(true) on the accepted stream (source: src/protocol/*/mod.rs, start).

Thread per connection

Three wires can run each connection on its own OS thread. The thread has an 8 MiB stack and builds a current_thread tokio runtime; the session runs as a task inside it.

Wire Environment variable Default Thread name
PostgreSQL SYNERGYDB_PG_THREAD_PER_CONN on; 0 or false turns it off pg-<port>
MongoDB SYNERGYDB_MONGO_THREAD_PER_CONN off mongo-<port>
Oracle SYNERGYDB_ORACLE_THREAD_PER_CONN off ora-<port>

Source: src/protocol/postgres/mod.rs, PostgresHandler::start; src/protocol/mongodb/mod.rs, start; src/protocol/oracle/mod.rs, start. Not verified: no test exercises the thread-per-connection branch itself. These variables are also listed in PostgreSQL and MongoDB.

The thread count is bounded only by the number of open connections. With PostgreSQL defaults, each idle client holds one OS thread and its 8 MiB stack reservation.

Memcached workers

start_workers creates SYNERGYDB_MEMCACHED_THREADS worker threads. The default is available_parallelism, capped at STAT_BLOCKS - 1 (64). Each worker is a thread named memcached-<i> running a current_thread runtime. The accept loop hands sockets to workers round-robin over unbounded mpsc channels; if a worker's channel is closed, the socket falls back to tokio::spawn on the main runtime (source: src/protocol/memcached/mod.rs, start_workers). Not verified: no test covers worker dispatch.

HTTP, gRPC and Arrow

The plaintext HTTP listener is served by axum (axum::serve with with_graceful_shutdown). The TLS listener runs its own accept loop and serves each connection with hyper http1::Builder with upgrades enabled, inside heap::track("http connection"). S3 uses hyper the same way under heap::track("s3 connection") (source: src/protocol/http/mod.rs, HttpHandler::start; src/protocol/s3/mod.rs, start).

gRPC and Arrow Flight use tonic. Plaintext uses serve_with_shutdown. TLS uses tls::grpc_incoming, which runs the accept loop, performs each TLS handshake on its own task and sends finished streams over an mpsc channel of capacity 64. It exits only on the next accept after the receiver is dropped (source: src/protocol/tls.rs, grpc_incoming).

TLS at accept

TLS uses rustls through TlsListener (source: src/protocol/tls.rs, TlsListener).

Mechanism Used by Behaviour
accept_auto HTTP-family and other wires with optional TLS Peeks the first byte with a 30 s timeout; 0x16 (TLS handshake record) starts TLS, anything else is served as plaintext
PostgreSQL SSLRequest (code 80877103) PostgreSQL Answers S and runs the handshake, or N when TLS is not configured
MSSQL first-byte peek SQL Server 30 s peek for the first byte when TLS is configured

The TLS handshake itself has no timeout once it has started (source: src/protocol/tls.rs, accept_auto). Not verified: no test covers a stalled handshake.

With require_tls, PostgreSQL refuses a non-loopback plaintext session with FATAL 28000. Cancel requests (code 80877102) are exempt. plaintext_allowed exempts loopback peers, including IPv4-mapped IPv6 loopback (source: src/protocol/tls.rs, plaintext_allowed; src/protocol/postgres/mod.rs, handle_connection). The [tls] keys are in the configuration reference and the security model in Security.

Timeouts

TimeoutConfig

Preset connect read write idle
default() 30 s 60 s 60 s 300 s
aggressive() 5 s 10 s 10 s 30 s
relaxed() 60 s 120 s 120 s 600 s
no_timeout() none none none none

Source: src/protocol/timeout.rs, TimeoutConfig. Tests: test_default_config, test_aggressive_config, test_relaxed_config, test_timeout_error_display, test_timeout_error_to_io_error.

Every wire handler holds TimeoutConfig::default(). There is no configuration key or environment variable for it. with_timeout_config is called only by the Oracle test stalled_client_is_disconnected (source: src/protocol/oracle/mod.rs, tests).

TimeoutStream, TimeoutAcceptor and the helpers connect_with_timeout, read_with_timeout and write_with_timeout have no callers. TimeoutStream checks idle time only when it is polled and arms no timer of its own. Not wired: these types (source: src/protocol/timeout.rs, TimeoutStream, TimeoutAcceptor).

Effective timeouts per wire

Each wire applies the default values with tokio::time::timeout at its own read and write sites:

Wire Before login After login Writes
PostgreSQL read_timeout (60 s) on the startup packet and on the read after an SSL decline none: the message loop has no timeout, so an idle connection stays open indefinitely none
MySQL 60 s per header and body read idle check (300 s) at loop top, plus 60 s per header and body read none
MongoDB 60 s per read idle check (300 s), plus 60 s per header and body read write_timeout (60 s) on replies
Redis 60 s per read 60 s per read, including subscriber mode; the idle check is skipped for subscribers write_timeout
Bolt none before the first chunk read_timeout per chunk once a message has started none
Oracle connect_timeout (30 s) per wait idle_timeout (300 s) between requests; read_timeout mid-packet write_timeout
SQL Server 30 s first-byte peek when TLS is configured none found none

Source: src/protocol/postgres/mod.rs, handle_connection; src/protocol/mysql/mod.rs, handle_connection; src/protocol/mongodb/mod.rs, handle_connection; src/protocol/redis/mod.rs, handle_connection; src/protocol/bolt/mod.rs, read_message; src/protocol/oracle/mod.rs, handle_connection; src/protocol/mssql/mod.rs, start.

Consequences:

  • On MySQL, MongoDB and Redis a client that sends nothing for 60 s is disconnected by the per-read timeout, so the 300 s idle check cannot fire first. Not verified: no test.
  • A Redis client in SUBSCRIBE mode that sends no command for 60 s is disconnected even while it waits for published messages. Not verified: no test.
  • PostgreSQL connections never time out after start-up. The message loop races the next header read against an unbounded notification channel used for LISTEN/NOTIFY. Not verified: no test.
  • Oracle: test stalled_client_is_disconnected sets short timeouts and asserts that the server closes a stalled client.

Buffer limits

BufferLimits

Field default()
max message size 256 MiB
max query length 16 MiB
max parameters 65,535
max columns 1,600
max rows per batch 100,000
max string length 1 MiB
max blob size 64 MiB
max header size 8 KiB

Source: src/protocol/buffer_limits.rs, BufferLimits. The presets large(), restricted() and minimal() exist, but no server code calls with_buffer_limits, and there is no configuration key. Every wire uses default(). Tests: test_default_limits, test_check_message_size, test_check_query_length and the other tests in that module.

Where the limits are checked and the error each wire returns:

Wire Checks Error
PostgreSQL message size (closes after ErrorResponse), query length (error, session continues) SQLSTATE 54000, 54001, 54011, 54023
MySQL packet size, query length error codes 1153, 1162, 1390
MongoDB message size codes 10334, 2
Redis inline line over max query length, multibulk count over max parameters, accumulated request over max message size, bulk string over max string length (1 MiB) Redis error strings

Source: src/protocol/buffer_limits.rs, BufferLimitError; each wire's handle_connection. The Redis 1 MiB bulk limit is also stated in Redis.

Pre-authentication body cap

PREAUTH_BODY_LIMIT is 1 MiB. On CouchDB, ClickHouse HTTP, DynamoDB, Elasticsearch, InfluxDB and Snowflake, a request body larger than 1 MiB, or a chunked body, is read only when the request headers authenticate. Otherwise the server writes PREAUTH_REFUSAL, a raw HTTP/1.1 401 response with Connection: close (source: src/protocol/buffer_limits.rs, PREAUTH_BODY_LIMIT, PREAUTH_REFUSAL). Not verified: no per-wire test of the refusal was found.

Per-wire frame caps

Wire Constant Cap
DynamoDB MAX_HTTP_BODY 16 MiB
CouchDB, InfluxDB, Snowflake, Elasticsearch MAX_HTTP_BODY 256 MiB
Gremlin MAX_HTTP_BODY / MAX_GREMLIN_FRAME 64 MiB / 16 MiB
Schema Registry MAX_HTTP_BODY 16 MiB
SQLite MAX_SQLITE_BODY 64 MiB
Oracle MAX_TTC_REQUEST_SIZE / TNS MAX_PACKET_SIZE 64 MiB / 2 MiB
Memcached MAX_MEMCACHED_BODY / MAX_LINE 64 MiB / 1 MiB
Cassandra MAX_CQL_FRAME_BODY 256 MiB
Prometheus remote write MAX_DECOMPRESSED_BODY 64 MiB
ClickHouse HTTP MAX_BODY 256 MiB
Bolt MAX_BOLT_MESSAGE_SIZE 16 MiB
PostgreSQL NOTIFY MAX_PAYLOAD_LENGTH 8,000 bytes
Kafka request length prefix a length of 0 or less, or over 104,857,600, closes the connection; checked before authentication too

Source: the named constants in each wire module under src/protocol/. Test for Bolt: test_read_message_rejects_oversized_message (source: src/protocol/bolt/mod.rs, tests).

gRPC

GrpcConfig defaults: max_message_size 64 MB, max_concurrent_streams 200, keepalive interval 60 s and keepalive timeout 20 s, connection_timeout 60 s, request_timeout 300 s. The keepalive settings and max_concurrent_streams are applied to the tonic Server builder. max_message_size, connection_timeout and request_timeout are not passed to tonic, so tonic's own defaults apply (source: src/protocol/grpc/mod.rs, GrpcConfig, GrpcHandler::start). Not wired: those three fields.

Backpressure

  • Connections. None. Accept continues as long as the OS returns sockets; the only throttle is the accept_error sleep (source: src/protocol/mod.rs, accept_error).
  • Authentication. global_auth_rate_limiter allows 100 attempts per 60 s per IP, locks an IP out for 60 s, and tracks at most 10,000 IPs. HTTP routes, MySQL authentication and PostgreSQL authentication use it (source: src/protocol/rate_limiter.rs, global_auth_rate_limiter; callers in src/protocol/http/routes.rs, src/protocol/mysql/auth.rs, src/protocol/postgres/auth.rs). Other wires do not. The MySQL figures also appear in MySQL.
  • Output buffering. PostgreSQL wraps the stream in a 64 KiB BufWriter and a 64 KiB BufReader and flushes at protocol sync points (source: src/protocol/postgres/mod.rs, handle_connection). A slow reader therefore blocks the session task at the next flush; there is no write timeout.
  • Unbounded channels. The PostgreSQL notification channel and the Memcached worker hand-off channels are unbounded mpsc channels (source: src/protocol/postgres/mod.rs, handle_connection; src/protocol/memcached/mod.rs, start_workers). The gRPC TLS hand-off channel is bounded at 64 (source: src/protocol/tls.rs, grpc_incoming).

Connection pool module (src/protocol/pool.rs)

Not wired: src/protocol/pool.rs is a generic client-side pool. No server code creates a ConnectionPool (source: src/protocol/pool.rs, ConnectionPool). The encryption proxy uses a separate pool in src/proxy/pool.rs, behind the encryption-proxy code path.

PoolConfig

Field Default
min_connections 2
max_connections 10
connection_timeout 30 s
idle_timeout 600 s
max_lifetime 3600 s
health_check_interval 30 s
validate_on_borrow true
validate_on_return false
connection_retries 3
retry_delay 100 ms

Source: src/protocol/pool.rs, PoolConfig::default.

Behaviour

  • A ConnectionFactory supplies create, validate, reset and close (source: src/protocol/pool.rs, ConnectionFactory).
  • get() acquires a semaphore permit within connection_timeout, takes an idle connection (validating it if validate_on_borrow, replacing it if invalid), or creates a new one with up to connection_retries attempts spaced by retry_delay (source: src/protocol/pool.rs, ConnectionPool::get).
  • Dropping a PooledConnection spawns return_connection, which discards connections past max_lifetime, validates if validate_on_return, and calls reset before returning the connection to the idle queue (source: src/protocol/pool.rs, return_connection).
  • A maintenance task drains and validates all idle connections every health_check_interval, and every 10 s closes connections idle past idle_timeout while keeping min_connections (source: src/protocol/pool.rs, start_maintenance).
  • close() marks the pool Closing, aborts maintenance, closes idle connections, waits up to 30 s for active connections, then marks it Closed (source: src/protocol/pool.rs, ConnectionPool::close).
  • Errors: PoolClosed, Timeout, ConnectionFailed, ValidationFailed, MaxCapacity, Internal. MaxCapacity is never returned (source: src/protocol/pool.rs, PoolError).
  • Each pool leaks one Semaphore with Box::leak to get a 'static reference (semaphore_ref). The struct also holds a second semaphore field that is not used (source: src/protocol/pool.rs, ConnectionPool::new).

Tests: test_basic_pool_operations, test_pool_respects_max_connections, test_pool_statistics, test_try_get, test_connection_deref (source: src/protocol/pool.rs, tests).

Shutdown and draining

Server::shutdown sends () on each wire's shutdown channel (capacity 1). Each accept loop's select! takes the shutdown.recv() branch and breaks, so no new connections are accepted (source: src/server/mod.rs, Server::shutdown; each wire's start).

What happens to open connections:

Model On shutdown
tokio::spawn sessions Not tracked or signalled. They keep running until the runtime is dropped when async_main returns.
axum (plaintext HTTP) and tonic (plaintext gRPC, Arrow) Graceful shutdown waits for in-flight connections inside the handler task, but Server::shutdown does not await handler tasks, so the wait is cut short when the process exits.
Thread-per-connection (PostgreSQL, MongoDB, Oracle) Threads are detached and end with the process.
Memcached workers End with the process.

Source: src/server/mod.rs, Server::shutdown; src/main.rs, async_main. There is no drain period, no per-connection close message (for example a PostgreSQL 57P01 admin shutdown) and no wait for in-flight transactions. Not verified: no test covers behaviour of open sessions during shutdown. Signal handling and the rest of the shutdown order are in Server Runtime.

Tests referenced

Test Module
descriptor_exhaustion_is_recognised, open_files_soft_limit_is_raised_to_the_hard_limit, accept_error_backs_off_on_exhaustion src/protocol/mod.rs
stalled_client_is_disconnected src/protocol/oracle/mod.rs
test_read_message_rejects_oversized_message src/protocol/bolt/mod.rs
test_default_config, test_aggressive_config, test_relaxed_config, test_timeout_error_display, test_timeout_error_to_io_error src/protocol/timeout.rs
test_default_limits, test_check_message_size, test_check_query_length src/protocol/buffer_limits.rs
test_basic_pool_operations, test_pool_respects_max_connections, test_pool_statistics, test_try_get, test_connection_deref src/protocol/pool.rs