Cloudflare Failover With PgBouncer Health Checks
Attach a Cloudflare Load Balancing monitor to the origin pool it should evaluate; standalone Health Checks report failures but do not steer traffic. Serve a cached readiness result from a bounded sampler that checks both PgBouncer queueing and the application’s database route. Test shared database failure before enabling automatic failover.

Steer on readiness, not just HTTP reachability

A web server can answer /health while user requests time out waiting for a PostgreSQL connection. A database-aware probe can help Cloudflare route around an origin-specific failure, but moving traffic won't fix a bottleneck both origins share. It can make that bottleneck worse as the destination opens new connections and clients retry.
Cloudflare standalone Health Checks report health; they don't steer traffic. A Load Balancing monitor attached to an origin pool informs steering. A 503 fails an individual probe when the monitor expects 200. Traffic changes only after Cloudflare evaluates the configured health thresholds, pool health, and steering policy.
Diagnose before you steer
| What you see | What it may mean | What to verify |
|---|---|---|
HTTP checks pass; users get 504s | Requests may be queueing behind busy PostgreSQL connections. Reaching default_pool_size alone isn't proof. | Check sustained cl_waiting, maxwait, and application connection-acquisition latency for the affected database/user pools. |
| Some clients still hit the old origin | Cached DNS answers delay convergence for DNS-only steering; existing connections can also persist. | Compare fresh DNS answers with answers from affected resolvers and check whether clients reuse connections. |
| A replica's replay timestamp is old | The primary may simply be idle. | Compare primary WAL position with replica replay position over time, or verify freshness with a staging heartbeat. DNS TTL doesn't make replica data stale. |
Sample in the background and serve from cache
SELECT 1 is cheap; acquiring a connection during saturation is the risk. Don't make Cloudflare probes wait for PostgreSQL. Run one sampler per origin if practical, and budget for extra samplers if you deploy multiple workers or instances. Check queue depth and the application database route independently: SHOW POOLS can succeed while application authentication, backend connectivity, or connection acquisition fails.
Save this as readiness.py. Install fastapi, uvicorn, and psycopg[binary]. Inject PGBOUNCER_STATS_DSN for a restricted stats_users login to the pgbouncer database and APP_DB_DSN for the origin's normal PgBouncer route and role. Set APP_POOLS_JSON to pairs such as [["appdb","appuser"]], matching the names in SHOW POOLS. Set MAX_WAITING to the positive per-pool cutoff where staging tests show queueing threatens your latency objective. Start with uvicorn readiness:app --workers 1.
import asyncio
import json
import logging
import os
import subprocess
import sys
import time
from contextlib import asynccontextmanager
if __name__ == "__main__":
import psycopg
from psycopg.rows import dict_row
mode = sys.argv[1]
key = "PGBOUNCER_STATS_DSN" if mode == "stats" else "APP_DB_DSN"
with psycopg.connect(os.environ[key], autocommit=True,
row_factory=dict_row) as conn:
if mode == "stats":
pools = {tuple(p) for p in json.loads(os.environ["APP_POOLS_JSON"])}
limit = int(os.environ["MAX_WAITING"])
rows = conn.execute("SHOW POOLS").fetchall()
if any((r["database"], r["user"]) in pools
and r["cl_waiting"] >= limit for r in rows):
sys.exit(3)
else:
conn.execute("SELECT 1").fetchone()
sys.exit(0)
from fastapi import FastAPI, Response
cache = (0.0, "starting")
def check(mode):
try:
return subprocess.run(
[sys.executable, os.path.abspath(__file__), mode],
timeout=2, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
).returncode
except (subprocess.TimeoutExpired, OSError):
return -1
async def sample():
global cache
while True:
started = time.monotonic()
stats = await asyncio.to_thread(check, "stats")
database = await asyncio.to_thread(check, "app")
reason = "ok"
if database != 0:
reason = "app_db_failed"
elif stats == 3:
reason = "pool_queue_high"
elif stats != 0:
reason = "pool_stats_failed"
if reason != cache[1]:
logging.getLogger("uvicorn.error").info("readiness: %s", reason)
cache = (started, reason)
await asyncio.sleep(5)
@asynccontextmanager
async def lifespan(app):
task = asyncio.create_task(sample())
try:
yield
finally:
task.cancel()
await asyncio.gather(task, return_exceptions=True)
app = FastAPI(lifespan=lifespan)
@app.get("/health/ready")
async def readiness():
started, reason = cache
ready = reason == "ok" and time.monotonic() - started <= 12
return Response(status_code=200 if ready else 503,
headers={"Cache-Control": "no-store"})The example gives each check a two-second subprocess timeout and rejects samples older than 12 seconds. Tune both under staging load. PgBouncer pools can appear on demand, so confirm the configured pairs show up under representative traffic. This canary checks the database route, not checkout from your app's own client pool; track checkout latency separately. Restrict probe access where practical and keep credentials and diagnostics out of HTTP responses.
Configure Cloudflare and test the failure paths
- Set up the monitor in staging. Save the current monitor, pool attachments, pool order, fallback, steering policy, and proxy settings. Create an HTTPS Load Balancing monitor for
/health/ready, expect200, and set the Host header if the origin requires it. Attach the monitor to the intended pool. Check Cloudflare's monitor documentation for supported intervals, regions, and health thresholds for your plan. - Measure detection and convergence separately. Saturate only the intended PgBouncer pool. Verify the endpoint response, Cloudflare's origin and pool health, and where fresh requests land. For DNS-only steering, also measure when cached answers expire across resolvers. There's no blanket rule that TTL must be shorter than the monitor interval.
- Test shared failure and fallback capacity. Interrupt staging database access for both origins and verify where requests go when no regular pool is healthy. Cloudflare can still send traffic to the configured fallback pool regardless of its health. Then load-test that target at expected shifted traffic, including retries. If it can't carry the load, prioritize load shedding or independent database capacity over faster probes.
- Rehearse rollback. Restore the previous monitor and pool attachments, steering policy, pool order, fallback, and any DNS settings you changed. Verify health and routing again; already-cached DNS answers won't change immediately.
Budget headroom before raising pool limits
Count possible PostgreSQL connections across PgBouncer instances and database/user pools, including reserves, direct clients, and operational headroom. Raising min_pool_size can keep more connections open; raising reserve_pool_size can increase peak demand. Check the PostgreSQL connection budget before changing either.
Illustrative Scenario: If failover requires one extra warm instance at an assumed $0.12/hour, compute alone costs $87.60 per 730-hour month. Add database capacity, transfer, and Load Balancing charges using your providers' current pricing. Warm capacity is worth paying for only if it can actually carry shifted load.
Before rollout: Confirm pool filters and deadlines, validate database access independently, record steering and DNS convergence times, and sign off on fallback capacity and rollback.
Frequently Asked Questions
Why not just use a standard TCP port check for DNS health?
A TCP check only confirms that PgBouncer is listening on the port. It cannot see if PgBouncer is unable to talk to the backend Postgres database or if the connection pool is entirely exhausted, leading to silent failures for your users.
How does replication lag affect DNS steering?
If you are steering traffic to read-replicas, a replica that is 10 minutes behind the primary is effectively 'broken' for many SaaS applications. Including a check for `pg_last_xact_replay_timestamp()` in your deep health check ensures traffic only hits fresh data.
Can I use Cloudflare Workers for this probing logic?
Yes, Cloudflare Workers can be used to aggregate health signals from multiple backends, but the primary health check should still originate from the DNS level to ensure automatic IP-level steering without adding execution latency to every request.
Get the Weekly SMB AI & SaaS Brief
Practical software benchmarks, prompt templates, and ROI breakdowns delivered every Tuesday. No fluff, unsubscribe anytime.