Cloudflare Hyperdrive with GCP Cloud SQL PostgreSQL
Accelerate GCP Cloud SQL PostgreSQL queries from Cloudflare Workers using Hyperdrive smart connection pooling, query caching, and secure VPC tunnels.
When building globally distributed web applications with Cloudflare Workers, your compute code executes across 300+ edge locations worldwide, delivering single-digit millisecond latency to users. However, relational databases like Google Cloud SQL for PostgreSQL usually live in a single centralized region (such as us-central1 in Iowa or asia-southeast1 in Singapore).
Pairing globally distributed serverless workers with a centralized relational database introduces two critical bottlenecks: connection establishment latency and connection pool exhaustion. Cloudflare Hyperdrive eliminates both challenges.
1. The Problem: Why Direct Edge-to-Database Connections Are Slow#
In traditional monolithic architectures, the backend API server and PostgreSQL reside in the same data center or VPC, where connection setup latency is negligible (<1ms).
With serverless edge workers, the scenario changes drastically:
- High Handshake Overhead: When a Worker in Tokyo needs to query a Cloud SQL database in Iowa, it must establish a new connection:
- DNS lookup.
- TCP 3-way handshake (1 RTT).
- TLS negotiation (1–2 RTTs).
- PostgreSQL authentication handshake using MD5 or SCRAM-SHA-256 (1–2 RTTs). This requires 6 to 8 round-trips across the Pacific. Just opening the connection takes 200ms to 500ms before a single byte of SQL executes!
- Serverless Connection Exhaustion: Serverless workers scale dynamically on demand. If 5,000 requests arrive concurrently, 5,000 isolated worker instances will attempt to open 5,000 direct database connections, quickly exceeding Cloud SQL’s
max_connectionslimit and exhausting database memory.
2. Explain Like I’m 10 (ELI5)#
[!TIP] The Express Courier and the Bank Vault Analogy: Imagine you run a chain of local convenience stores across the globe (Edge Workers). Your primary financial ledger is locked inside a heavy bank vault in the United States (GCP Cloud SQL).
- Without Hyperdrive: Every time a customer in Tokyo asks, “Is this item in stock?”, the clerk must catch an international flight to the US, pass through multi-door security checkpoints, sign logbooks, open the vault, read the ledger, and fly all the way back to answer. It is painfully slow and expensive!
- With Hyperdrive: Hyperdrive places an authorized representative inside the bank vault with a permanent, encrypted hot-line telephone that stays connected 24/7 (Connection Pooling). In addition, each store keeps a local notepad of frequently asked answers (Query Caching). If a customer asks about a common price, the clerk reads the local notepad in 1 millisecond. If a new record needs writing, the clerk dials the hot-line immediately without traveling!
3. Network Architecture: Public IP vs Private IP (VPC)#
When connecting Hyperdrive to GCP Cloud SQL, you have two primary network architectures based on whether your database has a Public IP or is isolated within a Private VPC:
Option 1: Cloud SQL with Public IP#
- Simplicity: Easiest to set up.
- Security: Enforce SSL/TLS connections on Cloud SQL and allow-list Cloudflare’s Hyperdrive egress IP ranges under Authorized Networks. All traffic in transit is encrypted using TLS.
Option 2: Cloud SQL with Private IP (VPC) via Cloudflare Tunnel / GCE Proxy#
- Security: Cloud SQL has zero public internet exposure (bound only to internal RFC 1918 IPs like
10.x.x.x). - Implementation: Run a lightweight Google Compute Engine VM (
e2-micro) within the same VPC. Install thecloudflareddaemon to establish an outbound Cloudflare Tunnel (or run the Cloud SQL Auth Proxy). Hyperdrive reaches your private database over the tunnel securely without opening inbound firewall ports.
4. Step-by-Step Implementation Guide#
Step 1: Prepare GCP Cloud SQL PostgreSQL#
- Ensure your PostgreSQL instance (v14, v15, or v16) is active.
- Create an application user with appropriate privileges:
sqlCREATE USER worker_app WITH PASSWORD 'your_super_secret_password'; GRANT CONNECT ON DATABASE my_production_db TO worker_app; GRANT USAGE ON SCHEMA public TO worker_app; GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO worker_app; - If using Public IP, navigate to Google Cloud Console > Cloud SQL > Instance > Connections > Networking:
- Check Public IP.
- Enable Allow only SSL connections.
- Add Cloudflare Hyperdrive egress CIDR blocks to Authorized Networks.
Step 2: Create Hyperdrive Configuration via Wrangler CLI#
Make sure you have the latest Wrangler CLI installed, then create your Hyperdrive configuration:
wrangler hyperdrive create gcp-postgres-hyperdrive \
--connection-string="postgres://worker_app:your_super_secret_password@34.123.45.67:5432/my_production_db?sslmode=require"bashUpon success, Wrangler will output your Hyperdrive configuration details:
✅ Successfully created Hyperdrive configuration
📋 Details:
ID: fc7a9b12c3454e6789a0bcdef1234567
Name: gcp-postgres-hyperdrive
Host: 34.123.45.67
Port: 5432
Database: my_production_db
User: worker_appbashStep 3: Configure Worker Binding in wrangler.toml#
Bind Hyperdrive to your Worker project:
name = "my-fast-api"
main = "src/index.ts"
compatibility_date = "2026-09-01"
compatibility_flags = ["nodejs_compat"]
[[hyperdrive]]
binding = "HYPERDRIVE"
id = "fc7a9b12c3454e6789a0bcdef1234567"toml[!IMPORTANT] The
compatibility_flags = ["nodejs_compat"]flag is required to enable Node.js socket emulation and stream APIs in the Cloudflare Workers V8 runtime.
Step 4: Write Worker Connection Code#
Hyperdrive exposes env.HYPERDRIVE.connectionString. Under the hood, this connection string points directly to a local Hyperdrive proxy running inside Cloudflare’s nearest edge data center.
Option A: Using node-postgres (pg)#
Install dependencies:
npm install pg
npm install --save-dev @types/pgbashImplement the request handler:
import { Client } from 'pg';
export interface Env {
HYPERDRIVE: Hyperdrive;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
// Hyperdrive provides a dynamic local connection string
const client = new Client({
connectionString: env.HYPERDRIVE.connectionString,
});
try {
await client.connect();
// Execute your queries
const result = await client.query(`
SELECT
id,
title,
created_at,
NOW() AS query_timestamp
FROM articles
ORDER BY created_at DESC
LIMIT 10;
`);
return Response.json({
success: true,
count: result.rows.length,
data: result.rows,
});
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
return Response.json({ success: false, error: message }, { status: 500 });
} finally {
// client.end() returns the connection to Hyperdrive's pool
await client.end();
}
},
};tsOption B: Using postgres.js (Lightweight and Fast)#
Install package:
npm install postgresbashQuery execution:
import postgres from 'postgres';
export interface Env {
HYPERDRIVE: Hyperdrive;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const sql = postgres(env.HYPERDRIVE.connectionString, {
max: 5,
fetch_types: false,
});
try {
const articles = await sql`
SELECT id, title, created_at
FROM articles
LIMIT 10
`;
return Response.json({ articles });
} finally {
await sql.end();
}
},
};tsStep 5: Connecting to Private IP Cloud SQL via Cloudflare Tunnel (Optional)#
If your Cloud SQL instance does not have a public IP:
- Deploy a GCE Instance: Create an
e2-microVM in the same VPC subnet as Cloud SQL. - Install
cloudflaredon GCE:
bashcurl -L --output cloudflared.deb https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb sudo dpkg -i cloudflared.deb cloudflared tunnel login cloudflared tunnel create gcp-sql-tunnel - Configure TCP Ingress:
/etc/cloudflared/config.yml
yamltunnel: <TUNNEL_UUID> credentials-file: /etc/cloudflared/<TUNNEL_UUID>.json ingress: - hostname: db-private.yourdomain.com service: tcp://10.128.0.5:5432 # Internal Cloud SQL IP - service: http_status:404 - Run the Tunnel as a Service:
bashsudo systemctl enable --now cloudflared - Create Hyperdrive Configuration with Cloudflare Access Service Token:
Terminal
bashwrangler hyperdrive create gcp-postgres-hyperdrive \ --connection-string="postgres://worker_app:secret@db-private.yourdomain.com:5432/my_production_db" \ --access-client-id="<CLIENT_ID>" \ --access-client-secret="<CLIENT_SECRET>"
5. How Hyperdrive Query Caching Works#
Hyperdrive is protocol-aware, understanding the semantics of PostgreSQL wire protocol:
- Automatic Read Query Caching (
SELECT): Hyperdrive parses read-only queries and caches their responses at Cloudflare edge data centers. - Transactional Consistency (Read-Your-Own-Writes): When a transaction (
BEGIN ... COMMIT) or a mutation query (INSERT,UPDATE,DELETE) is issued, Hyperdrive instantly bypasses cache for subsequent operations in that session, ensuring zero stale reads. - Configurable TTL: You can adjust the maximum cache age to strike the ideal balance between real-time data freshness and database offloading.
6. Summary#
Connecting Cloudflare Hyperdrive to Google Cloud SQL for PostgreSQL combines the best of both worlds:
- Ultra-fast Edge Execution: Cloudflare Workers respond to worldwide users in milliseconds.
- Zero Handshake Latency: Database connection setup time drops from hundreds of milliseconds to near-zero.
- Database Health Protection: Warm pooled connections prevent connection exhaustion and reduce CPU overhead on your Cloud SQL cluster.
References#
- Cloudflare Documentation - Hyperdrive Overview ↗
- Cloudflare Documentation - Connect Hyperdrive to Google Cloud SQL PostgreSQL ↗
- Cloudflare Documentation - Connect to PostgreSQL via Hyperdrive ↗
- Cloudflare Documentation - Hyperdrive with Postgres.js Driver ↗
- Google Cloud Documentation - Cloud SQL for PostgreSQL ↗
- PlanetScale - Making Serverless Databases Fast with Cloudflare Hyperdrive ↗