blog.dopana

Back

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:

  1. 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!
  2. 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_connections limit and exhausting database memory.
With Cloudflare HyperdriveTraditional Approach: Direct Connection1. TCP Handshake2. TLS Handshake3. Postgres SCRAM AuthTakes 6-8 RTTs ~ 300-500ms4. Send SQL QueryLocal Edge Connection ~1msInstant Response on Cache HitMaintains Warm Connection Pool0 RTT Connection OverheadEdge Worker - TokyoGCP Cloud SQL - us-central1Edge Worker - TokyoHyperdrive Edge EngineGCP Cloud SQL - us-central1

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 2: Private IP / VPCOption 1: Public IPCloudflare Global NetworkEncrypted TLS over Public InternetCloudflare Tunnel TCPVPC Private IP 10.x.x.xCloudflare WorkerHyperdriveCloud SQL - Public IPAuthorized NetworksGCE Instancecloudflared daemonCloud SQL - Private IP

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 the cloudflared daemon 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#

  1. Ensure your PostgreSQL instance (v14, v15, or v16) is active.
  2. Create an application user with appropriate privileges:
    CREATE 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;
    sql
  3. 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:

Terminal
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"
bash

Upon success, Wrangler will output your Hyperdrive configuration details:

Output
✅ Successfully created Hyperdrive configuration
📋 Details:
  ID: fc7a9b12c3454e6789a0bcdef1234567
  Name: gcp-postgres-hyperdrive
  Host: 34.123.45.67
  Port: 5432
  Database: my_production_db
  User: worker_app
bash

Step 3: Configure Worker Binding in wrangler.toml#

Bind Hyperdrive to your Worker project:

wrangler.toml
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:

Terminal
npm install pg
npm install --save-dev @types/pg
bash

Implement the request handler:

Option B: Using postgres.js (Lightweight and Fast)#

Install package:

Terminal
npm install postgres
bash

Query execution:


Step 5: Connecting to Private IP Cloud SQL via Cloudflare Tunnel (Optional)#

If your Cloud SQL instance does not have a public IP:

  1. Deploy a GCE Instance: Create an e2-micro VM in the same VPC subnet as Cloud SQL.
  2. Install cloudflared on GCE:
    curl -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
    bash
  3. Configure TCP Ingress:
    /etc/cloudflared/config.yml
    tunnel: <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
    yaml
  4. Run the Tunnel as a Service:
    sudo systemctl enable --now cloudflared
    bash
  5. Create Hyperdrive Configuration with Cloudflare Access Service Token:
    Terminal
    wrangler 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>"
    bash

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:

  1. Ultra-fast Edge Execution: Cloudflare Workers respond to worldwide users in milliseconds.
  2. Zero Handshake Latency: Database connection setup time drops from hundreds of milliseconds to near-zero.
  3. Database Health Protection: Warm pooled connections prevent connection exhaustion and reduce CPU overhead on your Cloud SQL cluster.

References#