--- title: "PgBouncer Transaction Mode: Pool Sizing Math and the Prepared Statement Trap" published: true description: "Deep dive into PgBouncer transaction vs session mode tradeoffs, the prepared statement invalidation bug that hits production, pool sizing formulas, and a benchmark comparison of PgBouncer, Pgpool-II, and RDS Proxy." tags: postgresql, architecture, devops, cloud canonical_url: https://mvpfactory.co/blog/pgbouncer-transaction-mode-pool-sizing --- ## What you will learn By the end of this post you will understand why PostgreSQL connections are expensive at scale, how to choose between PgBouncer's session and transaction pooling modes, how to calculate a correct pool size from first principles, and — most importantly — how to avoid the prepared statement bug that silently corrupts production traffic. ## Prerequisites - A running PostgreSQL instance (any version) - PgBouncer installed as a sidecar or standalone proxy - A backend application using JDBC, SQLAlchemy, or any ORM with prepared statement caching --- ## Why connection pooling is not optional at scale PostgreSQL connections are **processes**, not threads. Each connection forks a backend process consuming roughly 5–10 MB of memory. At 500 concurrent connections you are already allocating 2.5–5 GB just in connection overhead — before a single query runs. A `max_connections = 200` instance under naive connection management from 20 app pods at 20 connections each exhausts capacity instantly. Add connection storms during deployments and you have a production incident. Connection pooling solves this by multiplexing many application connections onto a small number of actual server connections. --- ## Session mode vs transaction mode PgBouncer offers three pooling modes. Here is the minimal breakdown you need: | Mode | Server conn held until | Prepared statements | Throughput density | |---|---|---|---| | Session | Client disconnects | Works natively | Low | | Transaction | Transaction ends | **Breaks** | High | | Statement | Statement ends | N/A | Highest (rarely usable) | In **session mode**, a client owns a server connection for its entire lifetime — semantically identical to a direct connection. Safe, boring, and largely pointless for high-concurrency workloads. In **transaction mode**, the server connection returns to the pool the moment `COMMIT` or `ROLLBACK` fires. A pool of 20 server connections can serve thousands of short-lived application transactions. This is where PgBouncer earns its keep. --- ## The prepared statement problem Here is the gotcha that will save you hours. When your application executes `PREPARE my_stmt AS SELECT ...`, PostgreSQL stores that named statement in **server process memory** — not in the client, not in PgBouncer. In transaction mode, the next transaction from that application client may land on a different server connection that has never seen `my_stmt`. Result: `ERROR: prepared statement "my_stmt" does not exist`. This surfaces insidiously in ORMs. Hibernate, SQLAlchemy, and many JDBC drivers enable prepared statement caching by default. The docs do not always mention this, but the fix is per-driver:
yaml
Spring Boot / HikariCP — disable server-side prepared statements
spring:
datasource:
hikari:
connection-init-sql: "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ COMMITTED"
url: jdbc:postgresql://pgbouncer:6432/mydb?prepareThreshold=0
python
SQLAlchemy — force simple query execution
engine = create_engine(
"postgresql+psycopg2://user:pass@pgbouncer:6432/mydb",
connect_args={"options": "-c statement_timeout=30000"},
execution_options={"prepared_statement_cache_size": 0}
)
Setting `prepareThreshold=0` in JDBC or disabling the prepared statement cache in your ORM forces the driver into simple query protocol, bypassing server-side statement state entirely. --- ## Pool sizing math Let me show you a pattern I use in every project. Over-sized pools are as dangerous as under-sized ones — too many server connections and PostgreSQL spends more time on context switching and lock contention than executing queries. The formula:
plaintext
optimal_pool_size = (2 × CPU_cores) + effective_spindle_count
For a 4-core RDS instance with SSD (spindle count ≈ 1):
plaintext
pool_size = (2 × 4) + 1 = 9
This feels shockingly small. It is correct. Add a 10–20% overflow for burst headroom:
plaintext
max_connections (Postgres) = pool_size × num_app_instances × safety_factor
= 9 × 5 × 1.2 ≈ 55
Reserve the remaining connection budget for DBA tools, migrations, and read replicas. --- ## Gotchas **`SET` and temp tables break in transaction mode.** Any session-scoped state — `SET search_path`, temporary tables, advisory locks — does not survive across transactions when the server connection changes underneath you. Audit your application for these patterns before switching modes. **Pool wait time is not query time.** Latency spikes that look like slow queries are often pool exhaustion. Add a `pool_checkout_timeout` metric to your dashboards before your on-call rotation learns this the hard way. **Don't inherit the PostgreSQL default of 100.** The default `max_connections = 100` is not a recommendation — it's a starting point that predates modern connection pooling. Size from the bottom up using the formula above. --- ## Pooler comparison | Pooler | Protocol overhead | Transaction mode | HA / failover | Operational complexity | |---|---|---|---|---| | PgBouncer | Very low (~0.1 ms) | Native | Manual | Low | | Pgpool-II | Medium | Yes | Built-in | High | | RDS Proxy | Low–medium | Yes | Native AWS | Zero ops | PgBouncer wins on raw latency — it's a single-threaded C proxy that does almost nothing except multiplex connections. Pgpool-II adds load balancing and replication awareness at the cost of configuration complexity. RDS Proxy makes sense if you are already deep in AWS and want managed failover without operating a sidecar. --- ## What to do next Switch to transaction mode and kill prepared statements in your driver — `prepareThreshold=0` in JDBC or the equivalent in your ORM. It is the single change with the best return. Size from the bottom up: `(2 × cores) + 1` is your pool baseline. Multiply by instance count, add headroom, then set `max_connections` there. Instrument pool wait time on your dashboards now, before it becomes an incident. 