Managing Database Connections

1. Understanding Connection Lifecycle

Connection Lifecycle

  1. TCP handshake + TLS negotiation
  2. Authentication (SASL, scram, cert)
  3. Session setup (search_path, timezone, role)
  4. Active queries (transactions)
  5. Idle / cached in pool
  6. Close on timeout, error, or shutdown
CostDetail
Establishment10–100 ms (TLS, auth, fork backend)
Memory per backend~10 MB (Postgres)
CPU at scaleContext switches grow with connections

2. Configuring Connection Pooling

ModeDetail
Session pooling1 connection per client until disconnect
Transaction poolingConnection assigned per tx (most common)
Statement poolingPer-statement (no txs/prepared stmts)
MultiplexingN clients share K connections

3. Setting Pool Size Parameters

ParamGuidance
Max pool size~ (2 × cores) + spindles for sync DB workloads
Min idleMatch steady-state load
Acquire timeout1–5 seconds; fail fast on saturation
Idle timeout5–10 minutes to release unused
Max lifetime30 min to dodge stale TCP

4. Implementing Connection Timeouts

TimeoutPurpose
connect_timeoutTCP/TLS dial limit
statement_timeoutKill long queries
idle_in_transaction_session_timeoutKill idle txs (Postgres)
tcp_keepalives_*Detect dead peers
lock_timeoutAvoid hanging on lock acquisition

5. Handling Connection Leaks

CauseMitigation
Forgot close in error pathtry-with-resources / context managers
Long txs holding connsidle_in_transaction_session_timeout
Pool leak detectionHikariCP leakDetectionThreshold
ObservabilityTrack pool checkout time histogram

6. Using Connection Validation

ApproachDetail
Test querySELECT 1 before lease
Isolation APIJDBC isValid(timeout)
Background validationPeriodic vs per-checkout
Retry on failureReplace stale conn transparently

7. Managing Connection Credentials

MechanismDetail
Secret managerAWS Secrets Manager, Vault, GCP Secret Manager
IAM authRDS IAM tokens (15 min)
RotationAutomated, dual-key window for zero-downtime
TLS / mTLSCert-based authentication
Avoid env vars in codeInject at runtime

8. Implementing Connection Retry Logic

StrategyDetail
Retry transient errorsNetwork blip, primary failover
Don't retry on permanentAuth failure, schema mismatch
Exponential backoff + jitter50ms, 100ms, 200ms... with jitter
Max attempts3–5; then fail upstream
Circuit breakerStop hammering during outage

9. Monitoring Connection Pool Metrics

MetricWatch For
Active / idle / waitingWaiting > 0 → undersized pool
Acquire time p99Spikes → contention
Total connectionsvs server max_connections
Errors (timeouts)Alert on rate

10. Optimizing Connection Pool Performance

TipDetail
Right-sizeSmaller pools often outperform large ones
Use external poolerPgBouncer in front of Postgres
Prepared statement cacheReuse plans across calls
Avoid per-request connectionsCritical for serverless DB access