Back to blog

Connecting Cloudflare Workers to Relational Databases: A Step-by-Step Guide

Cloudflare Workers allow developers to deploy serverless code instantly to a global network of edge locations. By executing close to the user, Workers provide incredibly fast response times. However, connecting these distributed serverless runtimes to centralized relational databases (like PostgreSQL or MySQL) has historically been a major challenge.

Edge environments face three major database hurdles: they lack raw TCP capabilities in standard runtimes, have short lifecycles that exhaust connection pools, and introduce geographic latency when connecting across the globe.

In this guide, we will explore the solutions to these bottlenecks, look at Cloudflare Hyperdrive, and write a Worker that queries a PostgreSQL database using a WebSocket-based serverless driver.

The Bottlenecks of Edge-to-Database Connections

Traditional web servers maintain a persistent pool of TCP connections to the database. Workers, however, are ephemeral. They boot up in milliseconds, run for a short period, and shut down. This model presents three issues:

  • TCP Support: Standard JavaScript environments on edge nodes did not historically support standard raw TCP connections, limiting them to HTTP-based communication.
  • Connection Exhaustion: If a database accepts up to 100 concurrent connections, and your globally distributed Worker experiences a traffic surge, hundreds of worker instances booting up simultaneously will quickly crash your database with "too many connections" errors.
  • Latency Overheads: If your database is in US-East, and a worker fires up in Tokyo, the handshake over TCP/SSL adds massive network latency (up to 300ms) for every single database query.

Modern Solutions for Edge Databases

Fortunately, database providers and Cloudflare have built solutions specifically for the edge:

1. Cloudflare Hyperdrive

Hyperdrive is a Cloudflare service designed to turn your existing relational databases into edge-compatible, high-performance databases. It acts as a connection pool proxy distributed across Cloudflare's network, intercepting connections from your Workers. It maintains persistent connections to your actual database to prevent connection exhaustion and automatically caches queries to reduce latency.

2. WebSocket and HTTP Drivers

Serverless-native database providers, such as Neon (PostgreSQL) and PlanetScale (MySQL/Vitess), offer specialized client drivers. Instead of requiring a raw TCP socket, these drivers tunnel SQL commands over standard HTTP or secure WebSockets, making them native and efficient inside the edge runtime.

Connecting a Worker to Neon PostgreSQL via WebSockets

Let us build a Cloudflare Worker that connects to a Neon PostgreSQL database using the @neondatabase/serverless driver.

First, initialize a new worker project and install the serverless driver:

pnpm init
pnpm add @neondatabase/serverless

Next, write the Worker code in index.ts:

// src/index.ts
import { Client } from '@neondatabase/serverless';

export interface Env {
  DATABASE_URL: string;
}

export default {
  async fetch(
    request: Request,
    env: Env,
    ctx: ExecutionContext
  ): Promise<Response> {
    if (!env.DATABASE_URL) {
      return new Response('Database configuration error', { status: 500 });
    }

    // Initialize the serverless client using the environment variable
    const client = new Client(env.DATABASE_URL);
    
    try {
      await client.connect();
      
      // Execute a sample SQL query
      const { rows } = await client.query('SELECT NOW(), version();');
      
      await client.end();

      return new Response(JSON.stringify({
        success: true,
        timestamp: rows[0].now,
        databaseVersion: rows[0].version,
      }), {
        headers: { 'content-type': 'application/json' },
      });
    } catch (error: any) {
      return new Response(JSON.stringify({
        success: false,
        error: error.message || 'Database connection failed',
      }), {
        status: 500,
        headers: { 'content-type': 'application/json' },
      });
    }
  },
};

Configure your local credentials in wrangler.toml:

name = "edge-db-worker"
main = "src/index.ts"
compatibility_date = "2026-06-16"

[vars]
DATABASE_URL = "postgresql://user:password@hostname/dbname?sslmode=require"

Start the local development server:

npx wrangler dev

The serverless driver seamlessly runs database queries over WebSockets. When deployed to Cloudflare, the WebSocket handshakes are optimized to minimize connection setup times.

Best Practices for Edge Database Access

To keep your edge applications fast and secure, follow these guidelines:

  • Colocate Databases and Workers: If your database is hosted in a single AWS region (e.g., us-east-1), configure your Cloudflare Worker's routing or caching to query only from closest edge hubs, or utilize database read-replicas.
  • Keep Actions Ephemeral: Open the connection as late as possible in your Worker fetch handler, and close it immediately using client.end() once you retrieve the query results.
  • Leverage caching: Cache read-heavy data using Cloudflare KV or Cache API, preventing unnecessary database trips altogether.

Conclusion

Running high-performance relational databases in serverless environments is now fully viable. By leveraging WebSocket-based serverless drivers or configuring Cloudflare Hyperdrive as a caching connection proxy, you can connect globally distributed Workers to relational databases without exposing ports, overloading connection limits, or degrading edge performance.