0xOX0X
Cloud & SaaS

PgBouncer for PostgreSQL, Cloudflare for App Traffic

Quick Answer

Use PgBouncer to cap PostgreSQL backend connections when application instances open more connections than the database can handle. Add Cloudflare Load Balancing only if you need to steer application traffic to healthy regional origins. Test application routing and database reconnection separately in staging.

By Elena RostovaUpdated 2026-11-274 min read
Server rack corridor with fiber-optic patch cables and indicator lights

Pool database connections; route app traffic separately

Systems engineer reviewing database connection metrics on dual monitors

The request path is browser → optional Cloudflare proxy → regional app → PgBouncer → PostgreSQL. PgBouncer limits how many database backends the app fleet uses. Cloudflare can route incoming HTTP(S) traffic, but it does not increase database capacity. A single-region app can use PgBouncer without changing DNS.

PostgreSQL uses a backend process per direct connection; memory varies with workload and settings. A burst of 500 Lambda invocations might create far fewer than 500 new connections if warm execution environments reuse them. Measure connection churn and active transactions before resizing the database. Pooling helps most when many clients are idle between short transactions. If queries already saturate CPU or hold locks, a smaller pool mainly moves the wait upstream.

Pick a pooling mode your driver can handle

ModeBackend held forPrepared statementsWhen to use it
SessionClient sessionProtocol-level and SQL PREPAREApps that need persistent session state
TransactionTransactionProtocol-level named statements on PgBouncer 1.21+ with max_prepared_statements nonzero; not SQL PREPARE across transactionsAPIs with short transactions
StatementStatement; no multi-statement transactionsProtocol-level named statements with the same version and setting; not SQL PREPARE across statementsClients issuing independent statements

Test your actual ORM and driver versions rather than turning off every statement cache. In transaction mode, a session-level SET search_path is not tracked by default. A later transaction can land on a different backend. Schema-qualify queries or use SET LOCAL search_path inside each transaction that needs it.

What Cloudflare does at each layer

  • Authoritative DNS answers hostname lookups. DNS alone does not inspect requests, shield origins, or proxy PostgreSQL.
  • Cloudflare Load Balancing requires the paid feature or a contract that includes it. Configure regional HTTPS origins in pools, attach health monitors to an application readiness path, and select steering supported by your plan. Verify geographic or latency steering entitlements before relying on them.
  • Proxied HTTP(S) puts Cloudflare in the request path for edge DDoS protection and plan-dependent WAF features. Restrict direct origin access; otherwise clients can bypass edge controls.

DNS-only failover affects new resolutions and subsequent connections, subject to caching. Proxied load balancing can steer new requests without waiting for client DNS caches to expire, once monitors mark an origin unhealthy. Existing TCP sessions do not migrate. A read replica cannot take writes until promoted and configured as the write target. Regional routing may save little latency if each request still makes several database round trips across regions.

Illustrative Scenario: Budget connections and cost

Two PgBouncer pods capped at 20 backend connections each can use up to 40 for the configured database alias. Budget 60 if a rolling update can temporarily add a third pod, then leave headroom for migrations, monitoring, and direct access. If pooling avoids a hypothetical $0.15/hour database upgrade and adds $0.04/hour in pooler compute, the net savings are about $80 per 730-hour month before other charges. Check AWS RDS and compute pricing for your region; price Cloudflare Load Balancing separately if needed.

Stage PgBouncer on Kubernetes with TLS on both hops

Use an existing staging namespace. Create an RDS login named app_rw with only the database, schema, table, and sequence privileges the app needs. Restrict RDS ingress to the pooler network path. Save this as pgbouncer.ini and replace the RDS endpoint with the actual hostname, not a custom alias.

ini
[databases]
app = host=REPLACE_RDS_ENDPOINT port=5432 dbname=app_staging

[pgbouncer]
listen_addr = 0.0.0.0
listen_port = 6432
pool_mode = transaction
max_client_conn = 200
max_db_connections = 20
default_pool_size = 20
max_prepared_statements = 100
query_wait_timeout = 5
server_connect_timeout = 5
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
client_tls_sslmode = require
client_tls_cert_file = /etc/pgbouncer/tls.crt
client_tls_key_file = /etc/pgbouncer/tls.key
server_tls_sslmode = verify-full
server_tls_ca_file = /etc/pgbouncer/rds-ca.pem

Create userlist.txt with a line in the form "app_rw" "REPLACE_WITH_RDS_PASSWORD". Keep it out of source control: this setup uses the password for upstream login. Provide the AWS RDS CA bundle and a pooler certificate whose SAN includes pgbouncer.staging.svc.cluster.local (adjust for your cluster domain).

sh
kubectl -n staging create secret generic pgbouncer-files \
  --from-file=pgbouncer.ini --from-file=userlist.txt \
  --from-file=tls.crt --from-file=tls.key --from-file=rds-ca.pem

Save as pooler.yaml. Replace the image with a pinned PgBouncer 1.21+ image that accepts the config path as its entrypoint argument.

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: pgbouncer
spec:
  replicas: 1
  selector:
    matchLabels: {app: pgbouncer}
  template:
    metadata:
      labels: {app: pgbouncer}
    spec:
      containers:
        - name: pgbouncer
          image: registry.example.com/pgbouncer:replace-me
          args: [/etc/pgbouncer/pgbouncer.ini]
          readinessProbe:
            tcpSocket: {port: 6432}
          volumeMounts:
            - {name: files, mountPath: /etc/pgbouncer, readOnly: true}
      volumes:
        - name: files
          secret:
            secretName: pgbouncer-files
---
apiVersion: v1
kind: Service
metadata:
  name: pgbouncer
spec:
  selector: {app: pgbouncer}
  ports:
    - {port: 6432, targetPort: 6432}
sh
kubectl -n staging apply -f pooler.yaml
kubectl -n staging rollout status deployment/pgbouncer

From a staging client pod with the pooler CA mounted, use this libpq connection-string template and enter the staging password when prompted:

sh
psql 'postgresql://app_rw@pgbouncer.staging.svc.cluster.local:6432/app?sslmode=verify-full&sslrootcert=/certs/pooler-ca.pem' \
  -W -v ON_ERROR_STOP=1 -c 'SELECT current_user, pg_is_in_recovery();'

Expect app_rw and f for a primary. TCP readiness checks only the listener; SQL checks the backend path. Keep SHOW POOLS for diagnostics on the pgbouncer console under a separate restricted account.

Before rollout

  • Load-test realistic transaction lengths. Watch queue time, connections, and tail latency; keep pool waits below request deadlines.
  • Test origin withdrawal and database reconnection separately. Verify writes after promotion and retry only when safe, especially if a commit outcome is unknown.
  • Restrict pooler access and rotate credentials. Roll back to a known-good pooler config first; throttle app concurrency before any direct-to-RDS fallback.
Share this article

Frequently Asked Questions

Why does transaction mode break certain PostgreSQL features?

Transaction mode releases the backend connection back to the pool as soon as a transaction finishes. Features that rely on session persistence—such as temporary tables, advisory locks, and certain prepared statements—fail because subsequent queries may land on an entirely different database backend.

How do I handle prepared statements when using PgBouncer?

You must configure your application's database driver or ORM to disable client-side prepared statement caching (often by setting `prefer_simple_protocol=true` or equivalent driver flags) so that queries are executed as simple SQL strings compatible with transaction pooling.

Can Cloudflare DNS routing replace traditional cloud load balancers?

No. Cloudflare DNS handles global traffic direction, IP resolution, and DDoS mitigation at the edge, but you still require regional load balancers (like AWS ALBs) to distribute traffic across your internal container clusters or serverless compute instances.

Free Weekly Dispatch

Get the Weekly SMB AI & SaaS Brief

Practical software benchmarks, prompt templates, and ROI breakdowns delivered every Tuesday. No fluff, unsubscribe anytime.