On this page
What a SOCKS5 database connection looks like
A SOCKS5 proxy sits below the database protocol. Your driver opens a TCP connection to the proxy and authenticates, usually with a username and password as defined in RFC 1929. It then sends a CONNECT request naming the database host and port. The proxy opens its own TCP connection to the database, replies with success, and copies bytes in both directions until one side closes.
The database sees a connection from the proxy's address. That is the whole point when the database has an IP allowlist, such as an RDS security group, a Cloud SQL authorized network, or pg_hba.conf on your own server. You allowlist the proxy's fixed IPs instead of a serverless platform's shifting pool.
Two consequences follow. One pooled database connection is really two TCP connections joined by a relay, each with its own timeouts. And the CONNECT request carries either a hostname or an IP, which decides where DNS happens.
| Driver | SOCKS5 hook | Where DNS happens |
|---|---|---|
| Go pgx v5 | DialFunc with a SOCKS5 dialer | Locally, unless you override LookupFunc |
| Go go-sql-driver/mysql | RegisterDialContext | On the proxy (the hostname is passed through) |
| pgjdbc (Java) | JVM socksProxyHost property | On the proxy, unless the host matches socksNonProxyHosts |
| MySQL Connector/J | socksProxyHost connection property | Locally, unless socksProxyRemoteDns=true |
| libpq, psql, psycopg | None | Needs a local port forwarder |
| node-postgres, mysql2, PyMySQL | None built in | Needs a local port forwarder |
libpq documents no proxy parameter in its connection settings, and every libpq-based client inherits that gap. Those drivers need a local forwarder on 127.0.0.1 that speaks SOCKS5 upstream.
Why socks5h matters for managed database hostnames
By convention, socks5:// means the client resolves the hostname and sends an IP, and socks5h:// means the client sends the name and the proxy resolves it. curl's manual defines the two schemes this way. On the wire, the CONNECT request's ATYP byte is 0x01 or 0x04 for an address and 0x03 for a domain name (RFC 1928). The post on socks5 vs socks5h covers the general case. For managed databases it matters for three concrete reasons.
- The answer depends on who asks. AWS documents that a publicly accessible RDS endpoint resolves to the private IP from inside the VPC and the public IP from outside it. A client on a corporate network with split-horizon DNS can get an answer the proxy cannot route to.
- The address moves. AWS recommends connecting by DNS name because the underlying IP changes during failover. A client that resolves once and caches the IP keeps sending the proxy to the old primary.
- Dual-stack names return AAAA records. If your client resolves locally and prefers IPv6, it can ask an IPv4-only proxy to reach an IPv6 address, which fails. See IPv6 egress and IPv4-only allowlists.
When the proxy resolves the name, it gets the public answer from the network your traffic actually leaves from, fresh on every new connection.
In Go, the scheme is not what decides
Go's golang.org/x/net/proxy SOCKS5 dialer does not look at the URL scheme at all. It sends whatever address string it is given. If the host part parses as an IP, it sends ATYP 0x01 or 0x04, otherwise it sends the name as ATYP 0x03 (see the client source). So the question becomes what your driver passes to the dialer.
go-sql-driver/mysql passes the DSN's host:port straight to the dial function, so the name reaches the proxy. pgx does not. In pgx v5, pgconn calls LookupFunc on each host first, then calls DialFunc once per resolved IP. Through a proxy, that means your function does the DNS lookup and the proxy only sees IPs.
We checked this with a stub SOCKS5 server that logs each CONNECT request, pgx v5.12.0, and go-sql-driver/mysql 1.9.3. The addresses below are replaced with documentation ranges.
pgx, default LookupFunc:
ATYP 0x01 192.0.2.10:5432
ATYP 0x01 192.0.2.11:5432
ATYP 0x04 [2001:db8::10]:5432
ATYP 0x04 [2001:db8::11]:5432
pgx, LookupFunc returns the name unchanged:
ATYP 0x03 db.example.com:5432
go-sql-driver/mysql, RegisterDialContext:
ATYP 0x03 db.example.com:3306The fix in pgx is one function that returns the host unchanged, shown in the pool configuration below. pgx still uses the original hostname for TLS, so certificate checks are unaffected.
Java drivers
pgjdbc leaves the name unresolved when the JVM socksProxyHost property is set, unless the host matches socksNonProxyHosts or the built-in localhost defaults. You can see this in its `HostSpec.shouldResolve`. MySQL Connector/J has its own `socksProxyHost` property, and it resolves locally by default. Set socksProxyRemoteDns=true, available since 8.0.29, to send the name instead.
# Connector/J: SOCKS settings live in the JDBC URL, per connection.
jdbc:mysql://mysql.example.com:3306/app?sslMode=VERIFY_IDENTITY&socksProxyHost=proxy.example.com&socksProxyPort=1080&socksProxyRemoteDns=true
# pgjdbc: follows the JVM-wide SOCKS properties, which affect every socket.
java -DsocksProxyHost=proxy.example.com -DsocksProxyPort=1080 -jar app.jarThe JVM properties route every socket in the process through the proxy, per the Java networking properties. Credentials come from a java.net.Authenticator or the java.net.socks.username and java.net.socks.password properties.
TLS to the database still runs end to end
SOCKS5 has no idea what the bytes mean. The driver negotiates TLS with the database inside the relayed stream, exactly as it would on a direct connection. The proxy sees the TLS handshake in transit and can read the SNI name, but not queries, results, or the database password. See TLS passthrough and zero-knowledge proxies for what a relay can and cannot observe.
The useful property of an in-driver SOCKS dialer is that the driver still knows the real hostname. Certificate verification and SNI use that name, so sslmode=verify-full in Postgres and tls=true in go-sql-driver/mysql work with no extra settings. pgx sets the TLS server name from the host in the connection string for verify-full.
SNI matters more than it looks. Some managed Postgres services route on it. Neon, for example, uses the SNI name to find your compute endpoint, because the Postgres protocol does not carry the hostname. A local port forwarder breaks that if the driver connects to 127.0.0.1 with nothing else set. With libpq, keep the real name in host and the forwarder in hostaddr. libpq then uses host for verify-full and, with the default sslsni=1, for SNI.
Two TLS layers, two jobs
Database TLS protects your data. It does not protect the proxy credentials. RFC 1929 sends the SOCKS username and password in cleartext and says so in its security section. If the hop to the proxy crosses a network you do not control, wrap SOCKS5 itself in TLS when the provider offers an endpoint for it. In Go, that is a tls.Dialer passed as the forward dialer. The HTTPS proxy endpoints post covers the same idea for HTTP CONNECT.
// go get golang.org/x/net/proxy
package db
import (
"crypto/tls"
"net/url"
"os"
"golang.org/x/net/proxy"
)
// socksDialer connects through the SOCKS5 proxy in FIXEDMARK_SOCKS_URL.
// If the port is 1443 (SOCKS5 inside TLS), it wraps the hop to the proxy
// in TLS, so the proxy password never crosses the network in clear.
func socksDialer() (proxy.ContextDialer, error) {
u, err := url.Parse(os.Getenv("FIXEDMARK_SOCKS_URL"))
if err != nil {
return nil, err
}
pw, _ := u.User.Password()
var forward proxy.Dialer = proxy.Direct
if u.Port() == "1443" {
forward = &tls.Dialer{Config: &tls.Config{ServerName: u.Hostname()}}
}
d, err := proxy.SOCKS5("tcp", u.Host,
&proxy.Auth{User: u.User.Username(), Password: pw}, forward)
if err != nil {
return nil, err
}
return d.(proxy.ContextDialer), nil
}Every hop has an idle timeout
A pool keeps connections open so that each query skips the TCP, SOCKS, TLS, and authentication handshakes. The cost is that an idle connection can be closed by anything on the path while the pool still believes it is good. Through a proxy there are more things on the path.
| Hop | Example | Default |
|---|---|---|
| Your platform's NAT | AWS NAT gateway | 350 seconds idle, then RST |
| The SOCKS proxy | Relay idle timer | Provider specific, often minutes |
| The database server | MySQL wait_timeout | 28,800 seconds |
| The database server | Postgres idle_session_timeout | 0 (off) |
The defaults come from the NAT gateway troubleshooting guide, the MySQL `wait_timeout` reference, and the Postgres client settings. The Postgres docs also warn against enforcing idle_session_timeout on connections that come through poolers or middleware, which react badly to closures they did not expect.
The rule is simple. Your pool's maximum idle time must be shorter than the shortest timeout on the path, with margin for how often the pool checks. The proxy is usually the shortest. When a proxy closes a relay, the database side of the connection closes too, and the next query on that pooled connection fails.
TCP keepalive is not the same as activity
TCP keepalive probes are generated by the kernel and carry no application data. They keep NAT state on your hop alive, which is why AWS suggests a keepalive under 350 seconds for NAT gateways. They also detect a peer that vanished. A relay proxy, though, sees only the bytes it copies. If its idle timer counts relayed data, kernel probes on your side never reach it, and it closes the relay on schedule.
Go already sends keepalives on the socket to the proxy. proxy.Direct dials with a zero-value net.Dialer, which defaults to probes every 15 seconds. What keeps a relay open is application traffic, such as a query or a pool ping. Closing idle connections early is usually cheaper than pinging them forever, since a pinged connection holds a proxy session and a database backend for nothing.
Pool settings that survive a proxy
These examples assume the proxy's idle timeout is 5 minutes. Adjust the numbers to your provider. Both reuse the socksDialer above.
func connectPostgres(ctx context.Context) (*pgxpool.Pool, error) {
dialer, err := socksDialer()
if err != nil {
return nil, err
}
// DATABASE_URL=postgres://app:secret@db.example.com:5432/app?sslmode=verify-full
cfg, err := pgxpool.ParseConfig(os.Getenv("DATABASE_URL"))
if err != nil {
return nil, err
}
cfg.ConnConfig.DialFunc = dialer.DialContext
// pgx resolves the host itself before it dials. Return the name
// unchanged so the dialer sends it to the proxy, which resolves it.
cfg.ConnConfig.LookupFunc = func(_ context.Context, host string) ([]string, error) {
return []string{host}, nil
}
cfg.MaxConns = 4
cfg.MaxConnIdleTime = 2 * time.Minute // below every idle timeout on the path
cfg.HealthCheckPeriod = 30 * time.Second // how often idle conns are swept
cfg.MaxConnLifetime = 30 * time.Minute
cfg.PingTimeout = 5 * time.Second // a silently dropped conn fails fast
return pgxpool.NewWithConfig(ctx, cfg)
}func openMySQL() (*sql.DB, error) {
dialer, err := socksDialer()
if err != nil {
return nil, err
}
mysql.RegisterDialContext("fixedmark",
func(ctx context.Context, addr string) (net.Conn, error) {
return dialer.DialContext(ctx, "tcp", addr)
})
// The network name in the DSN selects the dialer:
// MYSQL_DSN=app:secret@fixedmark(mysql.example.com:3306)/app?tls=true
db, err := sql.Open("mysql", os.Getenv("MYSQL_DSN"))
if err != nil {
return nil, err
}
db.SetMaxOpenConns(4)
db.SetMaxIdleConns(4)
db.SetConnMaxIdleTime(2 * time.Minute)
db.SetConnMaxLifetime(4 * time.Minute)
return db, nil
}pgxpool
The pgxpool defaults are a 30 minute MaxConnIdleTime, a 1 hour MaxConnLifetime, and a 1 minute HealthCheckPeriod. The 30 minute idle time is far longer than most proxy timeouts. The background check closes idle connections only when it runs, so a connection can live up to MaxConnIdleTime plus one HealthCheckPeriod. Two minutes plus 30 seconds stays well under five.
pgxpool also pings a connection on acquire if it has been idle for at least 1 second, unless you set ShouldPing. A failed ping destroys the connection and the pool tries another. That covers a connection the proxy closed cleanly. It does not cover one dropped silently, such as when a proxy node dies, because the ping waits for a reply that never comes. PingTimeout bounds that wait. Its default is no timeout.
database/sql and go-sql-driver/mysql
The go-sql-driver README already recommends SetConnMaxLifetime under 5 minutes, because some middleware closes idle connections at 5 minutes. It also recommends setting SetMaxIdleConns equal to SetMaxOpenConns. The database/sql default of 2 idle connections makes a busy pool open and close connections constantly, and each of those is a fresh proxy handshake.
Through a SOCKS dialer, SetConnMaxIdleTime matters more than usual. The driver's checkConnLiveness check, on by default, peeks at the socket before reusing a pooled connection. It only works when the connection exposes its file descriptor. The SOCKS dialer returns a wrapper that does not, so the driver skips the check without an error. We confirmed the wrapper type with x/net v0.62.0. So nothing catches a dead connection before your query does. Keep idle time short, and retry a failed query on a fresh connection when that is safe.
HikariCP
HikariCP defaults to a 10 minute idleTimeout, a 30 minute maxLifetime, and a 2 minute keepaliveTime. Its keepalive is an application-level check, so it does move bytes through the relay and keeps a 5 minute proxy timer from firing. Note that idleTimeout only applies when minimumIdle is below maximumPoolSize, and by default they are equal.
Serverless pools are per instance
On AWS Lambda, each concurrent request gets its own execution environment. A pool created at module scope survives between invocations on the same environment, but it is never shared across environments. Total connections equal environments times pool size. A MaxConns of 10 on a function running 50 at once is 500 proxy sessions and 500 database backends.
- Keep the pool at module scope so warm invocations reuse it, and size it to the concurrency one environment really has. For Lambda that is often 1 or 2.
- Expect frozen environments. A paused function does not run pool timers, so a connection can sit past the proxy timeout and be handed out on the next invocation. Short idle times and ping on acquire handle this.
- A server-side pooler such as PgBouncer cuts the number of database backends, but it receives connections from the proxy IPs too, so its host needs the same allowlist. The post on serverless to RDS with an IP allowlist covers that setup.
Failover and reconnects
If a proxy node fails, every pooled connection through it breaks at once. That is expected, and the pool's job is to replace them. If your proxy gives you a pair of IPs, allowlist both, because new connections may leave from either. The post on static IP pairs and failover explains why.
- Retry reads and idempotent writes once on a connection error, on a new connection.
- Do not blindly retry a write whose commit status is unknown. Use an idempotency key or check the row first.
- Set connect timeouts on the driver, such as
connect_timeoutin a Postgres URL ortimeoutin a MySQL DSN, so a dead path fails in seconds. - Learn what a rejection looks like. A security group that does not list the proxy IP drops packets, so the connect times out.
pg_hba.confanswers with an error. A proxy-side destination rule fails the SOCKS5 CONNECT with a reply code. The proxy error codes guide helps read them.
Doing this with Fixedmark
Fixedmark, in early access, gives an app a pair of static outbound IPs and a SOCKS5 endpoint. Put the URL from the dashboard in FIXEDMARK_SOCKS_URL with the socks5h:// scheme, and allowlist both IPs in the database firewall. The databases guide and the Go guide have the driver code this post builds on.
- Port 1443 serves SOCKS5 inside TLS and keeps your token encrypted. Port 1080 is plain SOCKS5, which sends the token in cleartext. See SOCKS5 in the concepts guide.
- Idle connections close after 5 minutes by default, and database tunnels are planned to allow a longer timeout (limits). The idle timer counts only bytes the proxy relays, and kernel keepalive probes carry none, so set the pool's idle time below 5 minutes rather than relying on TCP keepalive.
- Requests are not capped, but each new SOCKS session counts as one request, and each app is planned to have a rate limit on requests per second and on concurrent connections (limits). A pool that reuses connections stays far below those limits. One that reconnects per query does not.
- For libpq, psql, node-postgres, and other drivers without a SOCKS option,
fm tunnelforwards a local port through your IPs. The CLI reference covers the tunnel, and the databases guide shows thehostandhostaddrsetup that keeps TLS checks on the real name.
Sources
Checked November 2026. Confirm current details on the vendor's site before you decide. Prices and limits change.
- RFC 1928: SOCKS Protocol Version 5
- RFC 1929: Username/Password Authentication for SOCKS V5
- pgx: pgxpool package documentation
- go-sql-driver/mysql: README
- golang.org/x/net: SOCKS client source
- AWS: Working with a DB instance in a VPC
- AWS: Troubleshoot NAT gateways
- MySQL Connector/J: Networking properties
- PostgreSQL: libpq connection parameters
- Neon: Connection errors and SNI

