, ,

PgBouncer vs RDS Proxy vs ProxySQL: Connection Pooling Compared

Compare PgBouncer, RDS Proxy, and ProxySQL by engine support, pooling modes, session compatibility, operations, and pricing model.

Laurent Gil Avatar
Cast AI DBO demo showing 235 application connections mapped to 44 database connections.

PgBouncer, Amazon RDS Proxy, and ProxySQL reduce connection-management overhead, but differ in supported engines, deployment, and routing features. PgBouncer is a focused PostgreSQL pooler. RDS Proxy is an AWS-managed proxy with IAM integration. ProxySQL supports MySQL and PostgreSQL, with capabilities that vary by protocol and release. Choose by workload compatibility and operational ownership, then benchmark your own traffic.

The underlying problem is fixed: Postgres runs one OS process per connection, and every one costs memory. That makes max_connections a memory setting wearing a connection setting’s clothes. Exceed it and you get FATAL: sorry, too many clients already. No retry logic fixes a server out of slots.

Key takeaways

  • Choose by supported engine, session compatibility, failover requirements, and operational ownership.
  • Transaction pooling reduces backend connections but requires careful handling of session state.
  • Budget every application pool and proxy replica against shared database capacity.
  • Pooling does not fix inefficient SQL; measure query latency and connection waits separately.

PgBouncer vs RDS Proxy vs ProxySQL: connection pooling in Postgres, compared

Each row is a constraint you may already have. Everything after argues the cells.

DimensionPgBouncerRDS ProxyProxySQL
OperationsSelf-managed releases and security patchesAWS-managed serviceSelf-managed releases; verify protocol-specific capabilities
EnginesPostgreSQL onlySupported RDS and Aurora engines, versions, and regions; check AWS availabilityMySQL and PostgreSQL; verify feature parity for the installed release
Pooling modesSession (the default), transaction, statementTransaction-level multiplexing; degrades to session when pinnedMultiplexing with per-session pinning, plus query-rule routing
Prepared statementsProtocol-level via max_prepared_statements since 1.21; the shipped default is 200 from 1.24+. SQL-level PREPARE is untrackedWorks through the extended query protocol; explicit ORM prepares can trigger pinningStatement cache and extended-query handling on both protocols
HADo it yourself: keepalived, DNS failover, or an NLB in frontManaged Multi-AZ availability and database failover integrationProxySQL Cluster syncs config; backend health checks
Authauth_file, auth_query, HBA, PAM, LDAP (1.25+). No native IAMIAM end-to-end plus Secrets Manager; up to 200 secrets per proxyOwn user tables per protocol; pass-through supported
Kubernetes fitStrong. Small image, runs as a Deployment or per-service. You own HA either wayUsable from Kubernetes when networking permits; AWS-managed outside the clusterReal extra hop; multi-layer config to manage
Pricing modelOpen source plus your compute plus your timeDatabase-capacity-based pricing; verify engine, region, minimums, and endpoint chargesGPLv3 open source plus your compute; commercial tier exists
Failure visibilityFull: SHOW POOLS, logs, pg_stat_activityLimited. Pinning and latency are inferred from CloudWatchFull via the admin interface on port 6032
Best fitLatency-sensitive, non-AWS or self-hosted, team with ops maturityAWS-only, IAM auth required, serverless or bursty, low appetite for opsExisting MySQL estate needing routing and rewrite in the same layer

Check the current PgBouncer configuration reference, RDS Proxy documentation, and ProxySQL documentation against your engine, driver, and deployment before choosing.

Why a Postgres connection pooler exists

The pooler exists because the database is finite, in a way that is easy to miss.

max_connections is a memory allocation

At startup Postgres sizes shared structures from max_connections. That includes PGPROC entries, pg_stat_activity rows and lock-manager hash tables scaled by max_locks_per_transaction times max_connections. PostgreSQL 18 added per-connection async I/O handles to that list. The setting is server-start only, so changing it means a restart.

Raising max_connections increases shared-memory requirements, and active backends add process memory and workload-dependent allocations. Measure these on your own PostgreSQL build and workload; a fixed number of megabytes per connection is not a reliable sizing rule.

More connections do not mean more parallelism

CPU-bound, I/O-bound, and lock-heavy workloads have different useful concurrency limits. Parallel queries can also use additional workers. More connections may improve throughput up to saturation, then increase queuing and memory pressure. Core count alone does not determine that boundary.

Size the pool using database throughput, latency, CPU, I/O, lock waits, and memory under representative load. There is no universal 20-to-50-connection production setting. Client admission limits and backend pool capacity are separate controls.

Two exhaustion points, one symptom

Application-pool exhaustion means clients are waiting for a connection inside HikariCP, pgx, or another client pool. Database exhaustion means aggregate connections have reached the server limit. A server-side pooler can reduce connection churn and backend pressure, but it cannot by itself repair long transactions, application leaks, or an undersized application pool.

PgBouncer: when the classic wins

PgBouncer is a lightweight, event-driven PostgreSQL connection pooler. It keeps client connections open while reusing a smaller backend pool. Its overhead depends on traffic, deployment, TLS, and configuration; compare latency under your own workload rather than assuming one product is always fastest.

Session versus transaction mode, plainly

In session mode, a server connection is reserved for a client until it disconnects. Every PostgreSQL feature works. This is PgBouncer’s default, and it gives the least pooling benefit because idle clients hold real server connections.

In transaction mode, a backend returns to the pool at commit or rollback. The next transaction may use a different backend, so session continuity is not guaranteed. Unsupported session state can persist on a backend without following the client. Check tracked parameters and feature compatibility for your version; use session pooling or a direct connection for LISTEN and other features requiring a persistent session.

Prepared statements stopped being the blocker

The old advice to disable server-side prepares is outdated. Since PgBouncer 1.21, with max_prepared_statements above zero, the pooler tracks protocol-level prepared statements and prepares them on whichever connection it hands out. 1.24 raised the default to 200.

Protocol-level prepared-statement tracking requires a nonzero max_prepared_statements. SQL-level PREPARE has different compatibility constraints. Modern compatible drivers can use protocol-level prepares; JDBC prepareThreshold=0 disables server-side preparation and is a workaround, not a universal requirement. Test your driver and ORM against the actual PgBouncer release.

A minimal transaction-mode pgbouncer.ini

[databases]
appdb = host=postgres-primary.internal port=5432 dbname=app

[pgbouncer]
listen_addr = 0.0.0.0
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt

pool_mode = transaction
max_client_conn = 2000
default_pool_size = 40
max_db_connections = 80
min_pool_size = 5
reserve_pool_size = 10
reserve_pool_timeout = 3

max_prepared_statements = 200
server_lifetime = 1800
server_idle_timeout = 300
server_round_robin = 1

default_pool_size limits each user/database pool. max_db_connections caps backend connections for a configured PgBouncer database, not all PgBouncer replicas or all aliases targeting the same server. max_client_conn limits accepted clients. Budget the sum across instances, users, aliases, reserve pools, and direct connections, leaving administrative headroom.

Choose auth_file or auth_query according to your credential-management design. An authentication query can centralize lookup, but requires carefully restricted privileges and, when used, a securely defined SECURITY DEFINER function. Protect the authentication connection and configure TLS and network access for this example before production use.

The operational bill

Plan backend discovery and failover explicitly. PgBouncer supports DNS-based connection handling and reconnect controls, but does not elect a database primary. server_round_robin changes reuse order within the pool; it is not a read/write query router. Check multi-host behavior for your release and test failover with your deployment topology.

The single-threaded design is the high-end failure mode. A serverless platform spinning up many functions at once. One thread may not assign connections fast enough, so clients spike while the pooler-to-database count sits below its limit. The bottleneck is the pooler, not Postgres. Run several instances behind SO_REUSEPORT if you expect that shape.

Keep 1.26.1 or newer. It fixed a SCRAM authentication bypass across 1.17.0 through 1.26.0.

RDS Proxy: what managed buys and what it costs

RDS Proxy provides managed pooling and availability integration for supported AWS databases. IAM and Secrets Manager options depend on the authentication mode and engine. It can reduce failover disruption, but applications still need safe retry handling for failed transactions and disconnected sessions.

You pay per vCPU of the database

RDS Proxy pricing is based on the capacity of associated database instances or supported serverless capacity, rather than the number of client connections. Check current AWS pricing for the engine, region, minimum billing capacity, and additional endpoint charges.

The model is defensible when the proxy replaces a recurring incident. Ten Fargate tasks with a pool of 20 open 200 connections, which a 1,000-connection instance absorbs. Autoscale them to 100 and the pools reach 2,000. Proxy while the fleet swings, not while it is flat.

Pinning is the number to measure

RDS Proxy multiplexes at transaction level, returning connections to the pool between transactions. That stops when the proxy detects a session-state change it cannot safely share. The connection is then pinned to one client until that session ends, and nobody else can borrow it.

Ordinary framework behaviour triggers pinning: session-level SET, advisory locks, temporary tables, and prepared statements created explicitly by some ORM configurations. For Postgres, pinning filters are unavailable and any statement text over 16 KB causes a pin. AWS exposes DatabaseConnectionsCurrentlySessionPinned, so watch it in production for a week rather than assume a zero rate. A mixed ORM setup can sit at a double-digit pin rate for days before anyone notices.

The limits you hit at scale

Check service quotas, authentication limits, and endpoint support for the target region and engine. RDS Proxy is not a general-purpose proxy for arbitrary replicas. Supported Aurora configurations can expose read-only proxy endpoints, so a blanket โ€œwriter onlyโ€ rule is incorrect.

MaxConnectionsPercent expresses a pool limit relative to database capacity, but reserved connections and internal requirements affect the usable count. Monitor MaxDatabaseConnectionsAllowed, borrow latency, and session pinning rather than treating the percentage as an exact capacity promise. RDS Proxy remains tied to supported AWS database deployments.

ProxySQL: more than a pooler

ProxySQL sits in front of your database as a protocol-aware proxy, and it does far more than pool. It routes queries to hostgroups, rewrites them, caches results, mirrors traffic and logs queries. For a MySQL estate that needs read/write split without code changes, that is a real architectural win.

Check PostgreSQL-specific capabilities

ProxySQL supports PostgreSQL as well as MySQL. Consult its current protocol-specific documentation instead of assuming MySQL feature parity or inferring release maturity from old beta announcements. Test prepared statements, transaction semantics, authentication, routing, and failure recovery for the version you deploy.

That does not make ProxySQL unfit for Postgres. It does mean new software sits on your transaction path. Test it against your driver and ORM before production.

The complexity tax

Configuration is layered. You write to an admin interface backed by SQLite, run LOAD ... TO RUNTIME to make it live, then SAVE ... TO DISK to survive a restart. Skip it and the change vanishes, unlike editing pgbouncer.ini and sending SIGHUP.

Query rules carry the real risk. They are ordered and pattern-matched, so a split that sends any SELECT to a replica also sends reads-after-write there. Only a more specific rule above it catches the exception, so rule ordering becomes part of your correctness argument. ProxySQL Cluster syncs config, which helps HA but does not shrink that risk.

ProxySQL is relevant when routing and query rules are part of the requirement. PgBouncer does not support MySQL, so a MySQL evaluation should compare ProxySQL with other MySQL-compatible proxies rather than treating PgBouncer as an alternative.

The Kubernetes trap: HPA scales pods, your pool does not

On Kubernetes, capacity grows faster than default pools survive. An HPA going from 2 replicas to 8 with a per-pod pool of 100 opens 800 connections against a database whose default max_connections is 100. The autoscaler did exactly what you configured, against a finite resource it cannot see.

Failure here compounds and looks like an application outage. A scale-up spikes demand, so connections queue and requests time out. Readiness probes fail, and retries add attempts to a database with no slots left. That turns a slow window into a hard one.

Replicas multiplied by pool size must stay under max_connections, with headroom for migrations and admin sessions. Capping maxReplicas and shrinking per-pod pools is one fix. The better fix puts a pooler between pods and database, so one number governs connections, not deployment count. Editing max_connections through a ConfigMap does nothing. The parameter is server-start only.

Deployment shape matters as much as tool choice. A sidecar multiplies independent backend pools as pods scale; a centralized service changes availability and networking requirements. Account for the full fleet when configuring horizontal and vertical autoscaling.

When each wins

Choose PgBouncer when

You run Postgres, edge latency matters, and your team already owns deployment, patching and failover for stateful services. You are self-hosted, on a non-AWS cloud, or unwilling to pay per vCPU. You want to query the pooler directly rather than infer state from a metrics API. First step this week: run a non-critical service’s connection spike through PgBouncer in transaction mode and compare SHOW POOLS snapshots before and after to see what your per-pod pools actually do at the ceiling.

Choose RDS Proxy when

You are on AWS, IAM auth is mandatory, and connection counts swing with serverless or batch. Your team does not want another stateful deployment, and paying per vCPU beats an on-call rotation for a pooler. First step this week: chart DatabaseConnectionsCurrentlySessionPinned against total connections for a week before you commit, and if a double-digit share of sessions are pinned, fix the session-level SET and ORM prepares before you assume the proxy will multiplex for you.

Choose ProxySQL when

You have a MySQL estate and want routing, read/write split or query rewriting in the pooling layer. You have a polyglot fleet, want one proxy vocabulary across protocols and treat rule ordering as production code. A pure Postgres shop rarely has a reason. First step this week: diff your live query-rule order against your replica routing intent and fix any rule sitting below a broader one, since misplaced rules are the usual source of stale reads after a write.

Estimate the managed premium using your actual database fleet and the current pricing page. Include proxy charges, compute, monitoring, high availability, and the operational effort of maintaining a self-managed alternative.

DBO does not sell a per-vCPU pooler, so read its current pricing terms rather than extrapolating from the AWS rate.

Where managed pooling fits

Cast AI pooling view comparing application client connections with database backend connections.
Pooling separates application connections from database backend connections. This Cast AI demo illustrates that distinction; it does not establish the behavior or performance of PgBouncer, RDS Proxy, or ProxySQL.

Up to this point the comparison has been neutral: three poolers, three sets of trade-offs, no product in the room. What follows is one managed option, judged against the same criteria.

Cast AI Database Optimization combines a read-only Performance Advisor with an optional proxy for connection pooling and query caching. Current deployment guidance covers Kubernetes and MySQL on ECS. Applications use the proxy endpoint when enabling proxy features. Validate transaction-pooling compatibility, session state, prepared statements, authentication, and failover for your workload; do not assume feature parity with RDS Proxy. The demo below illustrates 235 application connections mapped to 44 database connections. These are demonstration values, not a customer benchmark or expected reduction.

The payoff is fewer connections per instance, and pooling hides connection cost, but a slow query stays slow. If a bad plan is the bottleneck, how to find and fix slow PostgreSQL queries with pg_stat_statements shows the query-side work that a pooler cannot do for you.

If the constraint is owning HA, config drift and upgrade windows, this is the path. Before you cut traffic over, run this checklist against one service:

  • Validate pooling-mode compatibility with every driver and ORM in use.
  • Inventory session state: temp tables, advisory locks, LISTEN and session GUCs.
  • Size the pool against measured workload capacity, not client count alone.
  • Reserve headroom for admin and migration sessions.
  • Alert on pinned and queued connections.

Conclusion

The table is three answers. Match the row that describes your constraint.

Two numbers decide whether any of them works. One is server pool size against database CPU. The other is replicas multiplied by per-pod pool against max_connections. Get those wrong and the pooler just moves the queue. To compare broader options, best database optimization tools comparison covers what each category observes versus what it acts on, and our database optimization techniques overview covers where pooling sits among the other levers.

FAQ

What is the difference between PgBouncer transaction and session mode?

Session mode reserves a backend for a client until disconnect. Transaction mode releases it after each transaction, allowing more multiplexing but without guaranteed session continuity. Check PgBouncerโ€™s feature matrix and driver compatibility before changing modes.

How much does RDS Proxy cost?

RDS Proxy uses capacity-based billing for associated database instances or supported serverless deployments. Region, engine, minimum capacity, and additional endpoints affect the bill. Use the current AWS pricing page and your actual topology rather than a fixed per-connection estimate.

Can I run PgBouncer on Kubernetes?

Yes, and the pattern is common. PgBouncer is a small binary, so it runs as a Deployment, a sidecar, or a centralized service behind a Kubernetes Service. Kubernetes does not solve HA for you. You still need multiple replicas, a readiness check that reflects real state, and a failover path. For scalable apps sharing one database, Microsoft recommends a standalone service over a sidecar.

ProxySQL or PgBouncer for MySQL?

ProxySQL. PgBouncer speaks only the PostgreSQL protocol, so it cannot serve MySQL. ProxySQL is MySQL-first and mature there, with query rules, read/write split, caching and clustering. For MySQL the real comparison is ProxySQL against your cloud’s managed proxy, not against PgBouncer.

Do I need a connection pooler for a small application?

Not necessarily. Compare aggregate application-pool capacity, measured concurrent work, connection churn, and administrative headroom with database limits. Even a small application can exhaust a small server, while a stable workload with bounded pools may not need another proxy.

Does RDS Proxy work with Postgres prepared statements?

Yes, through the extended query protocol. The risk is pinning. Statements created explicitly by some ORM configurations count as a session-state change, so the proxy pins that client’s connection until the session ends. Watch DatabaseConnectionsCurrentlySessionPinned after any ORM or driver upgrade, and consider disabling client-side statement caching if the pin rate rises.

Cast AI โ€บ Blog โ€บ PgBouncer vs RDS Proxy vs ProxySQL: Connection Pooling Compared