Optimizing Rust Axum Services With PgBouncer Connection Pooling

Backend Development
Date:November 25, 2026
Topic:
Optimizing Rust Axum Services With PgBouncer Connection Pooling
⏱ 3 min read

Your Axum service hums along locally. Push it to production and the database connections spike. Postgres hits max_connections. Requests queue. Latency curves upward. The culprit isn't your query logic—it’s the overhead of a new TCP handshake and process fork for every incoming request.

Why Axum Needs a Pooling Layer

Axum runs on Tokio. It handles thousands of concurrent tasks on a few OS threads. Each task that talks to Postgres traditionally grabs a dedicated connection via sqlx::PgPool. Under load, 10,000 concurrent tasks demand 10,000 connections. Postgres defaults to 100. You can raise the limit, but each connection consumes ~10 MB of RAM and a backend process. The math stops working fast.

💡
TipPgBouncer sits between your app and Postgres. It multiplexes thousands of client connections over a tiny pool of actual server connections. Your Axum workers stay lightweight; Postgres stays breathable.

Architecture: Transaction vs Session Pooling

PgBouncer offers three modes. For Axum, transaction pooling is the sweet spot.

ModeWhen Connection Returns to PoolBest For
SessionClient disconnectsLegacy apps, prepared statements across requests
TransactionTransaction ends (COMMIT/ROLLBACK)Modern stateless services, Axum, serverless
StatementSingle statement endsRare; breaks transactions

Transaction pooling releases the server connection after every commit. Axum handlers typically open a transaction, run work, commit, and return. This maps perfectly.

Wiring It Up

Run PgBouncer as a sidecar or separate service. Point its databases section at your real Postgres host. Set pool_mode = transaction and max_client_conn = 10000. Keep default_pool_size at 20–50 per CPU core on the database host.

toml
# pgbouncer.ini
[databases]
myapp = host=postgres port=5432 dbname=myapp

[pgbouncer]
pool_mode = transaction
max_client_conn = 10000
default_pool_size = 50
min_pool_size = 10
reserve_pool_size = 5
reserve_pool_timeout = 5
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
log_connections = 1
log_disconnections = 1
stats_period = 60

In Axum, configure sqlx::PgPool to hit PgBouncer’s port (default 6432), not Postgres directly.

rust
use sqlx::postgres::PgPoolOptions;
use std::time::Duration;

let pool = PgPoolOptions::new()
    .max_connections(100) // client-side pool size
    .acquire_timeout(Duration::from_secs(5))
    .idle_timeout(Duration::from_secs(600))
    .max_lifetime(Duration::from_secs(1800))
    .connect("postgres://user:pass@pgbouncer:6432/myapp")
    .await?;
⚠️
WarningDisable prepared statement caching in sqlx when using transaction pooling. PgBouncer discards server-side state after each transaction. Add .disable_statement_logging() or set statement_cache_capacity(0) to avoid "prepared statement does not exist" errors.

Tuning the Knobs

Three numbers drive performance:

ParameterGuidelineWhy
default_pool_sizeCPU cores × 2–4Matches Postgres parallelism; avoids context-switch thrash
max_client_connExpected peak concurrent Axum tasksHeadroom for traffic spikes
sqlx max_connectionsdefault_pool_size × PgBouncer instancesClient-side pool shouldn’t exceed server-side capacity

Monitor pgbouncer.stats via SHOW POOLS and SHOW STATS. Watch cl_active, sv_active, and wait_time. If wait_time climbs, increase default_pool_size or add a PgBouncer replica behind a load balancer.

Common Pitfalls

Prepared statements. sqlx caches them by default. Transaction pooling invalidates them. Turn caching off or use simple_query for one-offs.

Session-level state. SET LOCAL, temp tables, advisory locks, and LISTEN/NOTIFY break across transaction boundaries. Move logic to application layer or use session pooling for those specific routes.

TLS termination. Terminate TLS at PgBouncer (client_tls_sslmode = require) to avoid double encryption overhead.

"

Connection pooling isn't optimization—it's survival. Without it, every successful launch becomes an outage.

— Backend engineer who learned the hard way

Verify Before You Ship

Run a load test (k6, wrk, or oha) against a staging cluster with production-like data volumes. Ramp concurrency to 5× expected peak. Assert p99 latency < 200 ms and zero 503 Service Unavailable from connection exhaustion. Capture SHOW STATS before and after.

ℹ️
NoteAdd a health-check endpoint that runs `SELECT 1` through the pool. If it fails, your orchestrator can drain traffic before clients see errors.

✦

PgBouncer turns a fragile connection model into a resilient pipeline. Your Axum handlers stay fast, your Postgres stays stable, and your on-call rotation stays asleep. Configure once, monitor forever, scale without fear.

Share𝕏 Twitterin LinkedInin Whatsapp