Cloudflare Hyperdrive tutorial: use PostgreSQL with Workers

By

Updated

Tagged: Cloudflare

Learn Cloudflare Hyperdrive with PostgreSQL and Workers, configure pooling and caching, and see how it fits with D1, R2, Queues, Supabase, and Neon.

Cloudflare Hyperdrive connects Cloudflare Workers to an existing PostgreSQL or MySQL database. It keeps database connections ready to reuse and can cache read queries, so your Worker spends less time opening connections and waiting for repeated results.

Your database stays where it is. You can keep PostgreSQL on a VPS, Supabase, Neon, or RDS and build the application on Workers.

In this tutorial, we’ll build a small PostgreSQL-backed notes API, run it locally, and configure Hyperdrive for deployment. Then we’ll look at how it fits with Pages, D1, R2, Queues, Durable Objects, and AI apps, and which parts of an existing stack it can replace.

If you’re new to Workers, start with my Cloudflare Workers tutorial. My free PostgreSQL Handbook covers the PostgreSQL side.

What problem does Cloudflare Hyperdrive solve?

Imagine your database runs in Frankfurt, and a visitor in Sydney hits a Worker running nearby.

The Worker needs a database connection. Opening a TCP connection, negotiating TLS, and authenticating all take round trips across the network before the SQL query even runs. Across that distance, connection setup can take longer than the query itself.

A traditional Node.js server usually keeps a pool of connections alive. Workers run differently, and you shouldn’t share a live database client across unrelated requests.

Hyperdrive handles those long-lived origin connections for you. Your Worker opens a nearby connection to Hyperdrive, which forwards queries through its pool near the database. Closing the client in your Worker doesn’t destroy that reusable origin pool (see Cloudflare’s connection lifecycle docs for the full picture). Here’s how a request moves through it:

How a Worker reaches PostgreSQL through HyperdriveA browser calls a Worker. The Worker connects to Hyperdrive, which either returns an eligible cached read or uses a pooled connection to the existing database.YesNoBrowserCloudflare WorkerHyperdriveEligible cachedread?Return cached resultReusable databaseconnectionExisting PostgreSQLdatabase

An uncached query still travels to your database, and a slow query still needs an index or a rewrite. You’re still talking to a single PostgreSQL server in one region, just without paying the connection setup cost on every request.

What can Hyperdrive replace in an existing stack?

Hyperdrive sits between your Worker and your database. Whether you can drop another service depends on what else that service does for the rest of your app.

Existing componentWhat Hyperdrive can take overWhat you still need
PgBouncer or a provider’s connection poolerPooling for traffic coming from WorkersPooling for other apps, or features Hyperdrive doesn’t support
A small API server that only forwards SQL requestsWorkers plus Hyperdrive can handle those endpointsAuthentication, validation, authorization, and any business logic
Neon HTTP or WebSocket database driverA Worker-to-Postgres path using a standard driverNeon still hosts the database
Redis or KV used only to cache repeated SQL resultsSome caching of eligible, stale-tolerant readsExplicit invalidation, counters, sessions, locks, and other app data
Prisma or DrizzleThe connection path under a supported ORM setupThe ORM’s schema, queries, types, and migrations
Supabase, Neon, RDS, or a PostgreSQL VPSConnection setup and pooling for WorkersThe database, backups, storage, and provider-specific services
D1A different choice when you need existing PostgreSQL or MySQLA database behind Hyperdrive, since it doesn’t host one

Before you remove anything from your stack, check what else talks to it. Let’s look at the two most common cases: PgBouncer, and hosted platforms like Neon and Supabase.

Hyperdrive vs PgBouncer

PgBouncer is a PostgreSQL connection pooler that you run yourself or get through your database provider. Hyperdrive gives Workers a managed connection path with pooling and optional query caching.

If you only set up PgBouncer to handle connections from Workers, Hyperdrive can let you remove that instance. Check which PostgreSQL features your app relies on first, since Hyperdrive uses transaction pooling and has its own compatibility limits.

If a Rails app, a Node.js server, and reporting tools also connect through PgBouncer, keep it running for them until you have another plan. Hyperdrive works through a Workers binding, so other apps in your stack can’t connect to it directly.

Hyperdrive vs Neon and Supabase

With Neon, you keep the same database and change how Workers talk to it. The Neon serverless driver sends queries over HTTP or WebSockets, while Hyperdrive uses supported PostgreSQL drivers through its binding. Test both paths with your real queries before switching.

When setting up Hyperdrive, Cloudflare’s Neon instructions use the direct connection string with Neon’s connection pooling unchecked, since Hyperdrive provides the pool on this path.

Cloudflare’s Supabase instructions also ask for a direct database connection, bypassing Supabase’s pooler for those Worker queries. Everything else you use on Supabase (Auth, Storage, Realtime, and the generated data API) stays on Supabase.

Be careful when replacing Supabase API calls with direct SQL. A raw database connection doesn’t inherit the signed-in user’s JWT context, and a privileged database role can bypass row-level security. Your Worker has to verify who is calling and enforce access rules on its own.

What a stack migration would look like

If you’re running Vercel Functions → Neon, you can move supported endpoints to Workers and use Hyperdrive with pg against the same Neon database. Neon still manages PostgreSQL. You’ll also need to adapt the endpoints to the Workers runtime and migrate your environment variables and deployment config, since swapping a database URL alone won’t move the app.

With a VPS running Express → PgBouncer → PostgreSQL, you can move the HTTP API to Workers and let Hyperdrive take over pooling for that traffic, while PostgreSQL stays on the VPS. If Express also runs a scheduler, serves WebSockets, or processes background jobs, make sure those have a new home before shutting the server down.

On a Supabase Auth + database + Storage stack, Hyperdrive lets your Worker connect directly to the database while the other Supabase services stay in place. Replacing the whole platform is a much bigger project, so start by mapping out which requests use SQL and which depend on the provider’s other APIs.

Build a PostgreSQL API with Hyperdrive

We’ll expose published notes through two read-only endpoints:

RequestResult
GET /notesThe latest 20 published notes
GET /notes/1One published note, or a 404

There’s no public write endpoint. We’ll insert the sample data straight with SQL so we don’t have to build authentication into this first example, and we won’t leave an unprotected editing API sitting online.

To follow along, you need Node.js, a Cloudflare account, and PostgreSQL. A local PostgreSQL server is fine for running the code on your machine. Once you deploy, though, Hyperdrive needs to reach your database over TLS, either publicly or through the private networking setup we’ll cover later.

1. Create the Worker project

Start by scaffolding a new Worker project:

npm create cloudflare@latest -- hyperdrive-notes
cd hyperdrive-notes

Pick the Hello World example, Worker only, and TypeScript. Skip deployment for now.

Install the PostgreSQL driver and its TypeScript definitions:

npm install pg
npm install -D @types/pg

Stick with the current pg package here. Cloudflare recommends it for PostgreSQL and lists the supported driver requirements in its node-postgres guide.

2. Create the database tables

In a development database named notes, save this schema as schema.sql:

CREATE TABLE notes (
  id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  title text NOT NULL,
  body text NOT NULL,
  published boolean NOT NULL DEFAULT false
);

CREATE INDEX notes_published_id_idx
  ON notes (id DESC)
  WHERE published = true;

INSERT INTO notes (title, body, published)
VALUES
  ('First note', 'PostgreSQL stores the notes.', true),
  ('Working draft', 'This note is private.', false);

Apply it with psql against your development database:

psql -d notes -f schema.sql

Your database provider’s SQL editor works just as well. The partial index matches our public list query, and the unpublished row gives us an easy sanity check later because requesting it must return a 404.

Give the app a dedicated runtime database role with only the permissions it needs. For this API, that’s SELECT on notes plus the schema access required to reach it. Keep schema changes on a separate migration role.

3. Create a Hyperdrive configuration

In the Cloudflare dashboard, open Storage & databases → Hyperdrive → Create configuration.

Name it notes-db and enter your development database’s direct connection details. If you’re using a hosted database, copy the direct PostgreSQL connection string from your provider and connect with that restricted runtime role.

Cloudflare tests the connection before creating the configuration, so a PostgreSQL server bound only to your laptop’s loopback address won’t be reachable.

Turn off query caching for this first configuration. While you’re learning the connection path, you want every read to reflect the latest data in the database.

You can also disable caching on an existing configuration with Wrangler:

npx wrangler hyperdrive update YOUR_HYPERDRIVE_ID --caching-disabled true

Swap YOUR_HYPERDRIVE_ID for the ID Cloudflare gives you. That ID only identifies the configuration, while the database password stays inside Hyperdrive instead of your Worker source.

If you haven’t authenticated Wrangler yet, run npx wrangler login. My Wrangler guide walks through the CLI setup.

Hyperdrive requires TLS to the origin database. If you use a private certificate authority or need explicit certificate and hostname verification, configure the SSL mode and certificates using Cloudflare’s TLS guide. Don’t work around certificate errors by disabling verification in your app.

4. Add the Hyperdrive binding

Replace the generated wrangler.jsonc with this configuration:

{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "hyperdrive-notes",
  "main": "src/index.ts",
  "compatibility_date": "2026-10-24",
  "compatibility_flags": ["nodejs_compat"],
  "observability": {
    "enabled": true
  },
  "hyperdrive": [
    {
      "binding": "HYPERDRIVE",
      "id": "YOUR_HYPERDRIVE_ID"
    }
  ]
}

Swap in your real configuration ID, and keep the binding name HYPERDRIVE since our Worker code will use it.

Set compatibility_date to today’s date for a new project. Current compatibility dates turn on Node.js compatibility by default, though keeping the flag explicit makes the database driver’s runtime requirement clear. You can read how those dates behave in Cloudflare’s setup guide.

Generate the TypeScript types for your bindings:

npx wrangler types

Wrangler generates Env, including Env.HYPERDRIVE. Re-run this command whenever you change bindings.

5. Write the complete Worker

Replace src/index.ts with this Worker handler:

import { Client } from 'pg'

export default {
  async fetch(request, env): Promise<Response> {
    const url = new URL(request.url)
    const detail = /^\/notes\/([1-9]\d*)$/.exec(url.pathname)

    if (url.pathname !== '/notes' && !detail) {
      return Response.json({ error: 'Not found' }, { status: 404 })
    }

    if (request.method !== 'GET') {
      return Response.json(
        { error: 'Method not allowed' },
        { status: 405, headers: { Allow: 'GET' } }
      )
    }

    const id = detail ? Number(detail[1]) : undefined

    if (id !== undefined && (!Number.isSafeInteger(id) || id > 2147483647)) {
      return Response.json({ error: 'Invalid note ID' }, { status: 400 })
    }

    const client = new Client({
      connectionString: env.HYPERDRIVE.connectionString,
      connectionTimeoutMillis: 5000,
      query_timeout: 5000
    })

    try {
      await client.connect()

      const result = id === undefined
        ? await client.query(
            'SELECT id, title FROM notes WHERE published = true ORDER BY id DESC LIMIT 20'
          )
        : await client.query(
            'SELECT id, title, body FROM notes WHERE id = $1 AND published = true',
            [id]
          )

      if (id !== undefined && result.rows.length === 0) {
        return Response.json({ error: 'Not found' }, { status: 404 })
      }

      return Response.json(id === undefined ? result.rows : result.rows[0], {
        headers: { 'Cache-Control': 'no-store' }
      })
    } catch {
      console.error({ event: 'notes_database_error' })
      return Response.json({ error: 'Database unavailable' }, { status: 503 })
    } finally {
      await client.end().catch(() => {})
    }
  }
} satisfies ExportedHandler<Env>

The detail query passes user input through $1 in a separate values array so it never becomes part of the SQL string, and both queries explicitly filter out unpublished notes.

If the table is empty, /notes returns []. A missing or unpublished note returns a 404, and database failures return a generic 503 so credentials and raw SQL details never leak to callers.

Create the database client inside the request handler, because Hyperdrive manages the reusable origin pool for you. Calling end() releases the direct connection during local development, while in production Workers cleans up the Worker-to-Hyperdrive connection automatically when an invocation finishes.

query_timeout only caps how long this client waits. If you need PostgreSQL itself to stop long-running queries on the server, set a server-side statement_timeout as well.

6. Run locally

In zsh, read your development PostgreSQL URL without echoing it, then pass it to Wrangler through the environment:

read -rs 'notes_db_url?Development PostgreSQL URL: '
CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE="$notes_db_url" npx wrangler dev
unset notes_db_url

Enter the full URL with the username, password, host, port, and notes database name. Even when a local PostgreSQL server uses trust authentication, Wrangler’s local Hyperdrive binding still requires a non-empty password in the URL. URL-encode any special characters in the credentials, and never put real credentials in wrangler.jsonc.

If you want to run locally before creating a remote Hyperdrive configuration, use a dummy ID like 00000000000000000000000000000000 with your local connection string, then replace it with a real ID before remote testing or deployment.

In another terminal, hit the four endpoints:

curl -i http://localhost:8787/notes
curl -i http://localhost:8787/notes/1
curl -i http://localhost:8787/notes/2
curl -i -X POST http://localhost:8787/notes

Those requests return the published note in the list, its body in the detail response, a 404 for the private draft, and a 405 for POST.

Local development connects straight to the database you configured, without exercising Hyperdrive’s deployed connection pool or query cache. To test those, run npx wrangler dev --remote with a real configuration pointing at a development database. Remote mode uses the remote database even if you have a local connection string configured. You can check the details in Cloudflare’s local development guide.

7. Deploy and check the remote path

Type-check and deploy the Worker:

npx tsc --noEmit
npx wrangler deploy

Wrangler prints the deployed URL when it finishes. Repeat the same four requests against that URL and check the Hyperdrive metrics in the dashboard, keeping your test database separate from production.

Before adding real users, also test what happens when the database is unreachable and when the notes table is empty. Deploying only uploads the Worker, so running those requests is how you verify that the binding, credentials, and SQL work together.

Add query caching when stale reads are acceptable

For a public notes feed, serving a slightly older result briefly is usually fine. For a permission check or an account balance, it isn’t.

When caching is enabled, Hyperdrive caches eligible reads for 60 seconds by default, plus another 15 seconds of stale-while-revalidate. Writes don’t invalidate cached query results, so any read that has to be fresh belongs on a cache-disabled configuration. You can read the full consistency rules in Cloudflare’s query caching guide.

For example, if you unpublish a note that’s already in a cached query result, the cached response can still return it until the cache expires. If unpublishing needs to remove public access right away, keep this tutorial’s API uncached.

To experiment safely, create a second configuration named notes-public-cache pointing at the same development database, and enable caching there with a shorter window:

npx wrangler hyperdrive update YOUR_CACHED_HYPERDRIVE_ID --caching-disabled false --max-age 30 --swr 0

Add it alongside HYPERDRIVE in your existing hyperdrive array:

{
  "binding": "PUBLIC_DB",
  "id": "YOUR_CACHED_HYPERDRIVE_ID"
}

Regenerate your types. For a public query where that short delay is acceptable, build its client with the cached binding:

const client = new Client({
  connectionString: env.PUBLIC_DB.connectionString
})

Keep security checks, editing screens, and immediate read-after-write queries on env.HYPERDRIVE. If you’re using an ORM or authentication library, pass it the client connected to the right binding.

Setting an HTTP Cache-Control: no-store header won’t disable SQL query caching because they work at different layers. Skip SQL-comment tricks to force cache misses too, and pick the right Hyperdrive configuration instead.

Transactions and connection limits

Hyperdrive uses transaction pooling, meaning a transaction holds an origin connection until it commits or rolls back, and then another request can reuse that connection. Don’t expect session settings to carry over between independent queries. Cloudflare’s pooling guide explains these boundaries in detail.

Suppose publishing a note also needs to create an audit record. Save this additional schema as audit.sql and apply it with your migration role:

CREATE TABLE note_audit (
  id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  note_id integer NOT NULL REFERENCES notes(id),
  action text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);

Save this function as src/publish-note.ts. Call it only after authenticating an editor and checking their permission to publish, and give the database role for that write path the write and sequence permissions it needs:

import { Client } from 'pg'

export async function publishNote(env: Env, id: number): Promise<void> {
  const client = new Client({
    connectionString: env.HYPERDRIVE.connectionString
  })

  try {
    await client.connect()
    await client.query('BEGIN')

    try {
      const result = await client.query(
        'UPDATE notes SET published = true WHERE id = $1 RETURNING id',
        [id]
      )

      if (result.rowCount !== 1) {
        throw new Error('Note not found')
      }

      await client.query(
        'INSERT INTO note_audit (note_id, action) VALUES ($1, $2)',
        [id, 'published']
      )
      await client.query('COMMIT')
    } catch (error) {
      await client.query('ROLLBACK')
      throw error
    }
  } finally {
    await client.end().catch(() => {})
  }
}

Both writes run on the same client, so if the audit insert fails, the note update rolls back too. Never make an external API call between BEGIN and COMMIT, or you’ll hold a database connection open the whole time you wait.

Each Hyperdrive configuration has its own connection budget. If both a cached and an uncached configuration point to one database, count both when planning capacity, and leave room for migrations, admin access, and other applications.

You can tune a configuration’s pool limit with Wrangler:

npx wrangler hyperdrive update YOUR_HYPERDRIVE_ID --origin-connection-limit 10

This is a soft limit, so leave headroom instead of assigning Hyperdrive every connection your database allows. Cloudflare’s pool tuning guide covers the details.

Use Hyperdrive with Drizzle or MySQL

Because an ORM sits above the database driver, Hyperdrive just changes the connection path underneath it.

To use Drizzle with PostgreSQL, run:

npm install drizzle-orm

This optional src/db.ts module creates a request-scoped Drizzle client. Call it inside a handler and close client in a finally block once your queries finish:

import { drizzle } from 'drizzle-orm/node-postgres'
import { Client } from 'pg'

export async function connectDb(env: Env) {
  const client = new Client({
    connectionString: env.HYPERDRIVE.connectionString
  })
  await client.connect()
  return { db: drizzle(client), client }
}

Use the PostgreSQL adapter here, since the D1 adapter targets a different database engine. Keep migrations in your development or release process, using your provider’s direct connection where needed. You can see more details in Cloudflare’s Drizzle integration guide.

For MySQL, create a separate Hyperdrive configuration targeting your MySQL database. Use mysql2 with disableEval: true, and stick to its query() API instead of protocol-level prepared statements. Hyperdrive’s MySQL support has different restrictions from PostgreSQL, so don’t try to adapt the PostgreSQL example by swapping only the connection URL. Follow Cloudflare’s MySQL driver example instead.

How Hyperdrive fits with other Cloudflare services

You can build a full app on Cloudflare while keeping your existing database somewhere else. Pick each extra service based on the job it needs to do.

Cloudflare serviceIts job alongside Hyperdrive
WorkersRun endpoints and server-side application code
Pages FunctionsRun server-side routes for an existing Pages app
D1Store SQLite data when you want a Cloudflare-managed database
R2Store files while PostgreSQL holds their metadata
KV or the Cache APICache application values or HTTP responses explicitly
QueuesDeliver background jobs to a consumer that writes through Hyperdrive
WorkflowsRetry and coordinate multi-step background work
Durable ObjectsCoordinate access to a single entity or manage realtime connections
Workers AI and VectorizeRun models and semantic search alongside your SQL records
Workers VPC and TunnelReach a database inside a private network

Pages Functions and Astro

If you already have a Cloudflare Pages site, you can add a Hyperdrive binding to its Functions environment. Your database query runs inside the Function through context.env.HYPERDRIVE, and the browser talks to that Function over HTTP. Check the Pages Hyperdrive bindings docs for the exact setup.

With Astro, keep database access inside server-rendered routes or server endpoints using the Cloudflare adapter’s runtime bindings. Prerendered pages run at build time, so adding a runtime binding won’t turn them into live database pages.

In an AHA stack app, HTMX requests HTML from one of those server endpoints. The endpoint verifies the caller, queries PostgreSQL through Hyperdrive, and returns the HTML fragment while Alpine.js handles the browser interactions. Neither frontend library ever sees database credentials.

D1: choose where the relational data lives

Reach for Hyperdrive when you already have PostgreSQL or MySQL, need their specific features, or want to keep your current database provider.

D1 is a different path: it’s a Cloudflare-managed SQLite database with its own bindings and operational model. If a new app fits SQLite well, D1 saves you from managing an external database host.

Hyperdrive doesn’t connect to D1, and switching a PostgreSQL app over to D1 is a real database migration. You’ll need to adapt your schema and queries because D1 won’t carry over PostgreSQL extensions, types, or behaviors.

R2: files in object storage, metadata in SQL

If you’re building a document app, store the uploaded file in R2 and keep its object key, owner, and processing status in PostgreSQL.

When someone downloads a file, your authenticated endpoint checks permissions with an uncached database read, then fetches the object from R2. That keeps heavy file bytes out of PostgreSQL while SQL handles relationships and access control.

Keep in mind that an R2 upload and a PostgreSQL transaction can’t commit together atomically. Record a pending status first, retry failed steps, and run cleanup for any abandoned objects.

Queues: move database work off the request path

Say you want to log an analytics event every time someone views a note. Instead of making the request wait for a SQL insert, your Worker can push an event to a queue and let a consumer Worker write it through Hyperdrive in the background.

Cloudflare Queues uses at-least-once delivery, which means the same message can show up more than once. Give each event a stable ID and make the insert idempotent so duplicates are harmless. You can read more in the Queues delivery guarantees docs.

Start by creating views.sql in your analytics database:

CREATE TABLE note_views (
  event_id uuid PRIMARY KEY,
  note_id integer NOT NULL REFERENCES notes(id),
  viewed_at timestamptz NOT NULL
);

Next, set up a separate consumer Worker with pg installed and save this file as src/index.ts:

import { Client } from 'pg'

export default {
  async queue(batch, env): Promise<void> {
    const client = new Client({
      connectionString: env.HYPERDRIVE.connectionString
    })

    try {
      await client.connect()

      for (const message of batch.messages) {
        const event = message.body
        await client.query(
          'INSERT INTO note_views (event_id, note_id, viewed_at) VALUES ($1, $2, $3) ON CONFLICT (event_id) DO NOTHING',
          [event.eventId, event.noteId, event.viewedAt]
        )
        message.ack()
      }
    } finally {
      await client.end().catch(() => {})
    }
  }
} satisfies ExportedHandler<Env, {
  eventId: string
  noteId: number
  viewedAt: string
}>

Add this wrangler.jsonc to the consumer, replacing the Hyperdrive ID with a configuration whose runtime role can insert into note_views:

{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "note-view-consumer",
  "main": "src/index.ts",
  "compatibility_date": "2026-10-24",
  "compatibility_flags": ["nodejs_compat"],
  "observability": { "enabled": true },
  "hyperdrive": [
    { "binding": "HYPERDRIVE", "id": "YOUR_HYPERDRIVE_ID" }
  ],
  "queues": {
    "consumers": [
      {
        "queue": "note-views",
        "max_batch_size": 10,
        "max_concurrency": 2,
        "dead_letter_queue": "note-views-failed"
      }
    ]
  }
}

Create both queues before you deploy the consumer:

npx wrangler queues create note-views
npx wrangler queues create note-views-failed
npx wrangler types
npx wrangler deploy

Then add the producer binding to your original API Worker’s config:

"queues": {
  "producers": [
    { "binding": "NOTE_VIEWS", "queue": "note-views" }
  ]
}

Regenerate that Worker’s types, and you can send the event inside a successful detail request like this:

await env.NOTE_VIEWS.send({
  eventId: crypto.randomUUID(),
  noteId: id,
  viewedAt: new Date().toISOString()
})

Put that call after the missing-note check, inside if (id !== undefined). It only waits for the queue to accept the message, not for the consumer to finish the SQL insert. Decide up front whether a failed analytics push should fail the whole request or just get logged separately.

Notice how the consumer only acknowledges each message after its insert succeeds. If it crashes right after the insert and before acknowledging, the redelivered message hits the unique key and does nothing. Keep an eye on the dead-letter queue for events that keep failing.

In this example, the messages come from your own trusted Worker. If an external producer can ever push arbitrary messages into the queue, validate every field before running a query, because TypeScript types disappear at runtime.

If you’re dealing with a business event that can’t be lost between a database commit and a queue send, use a transactional outbox instead. Since PostgreSQL and Queues don’t share a transaction, write the event to a table inside the same PostgreSQL transaction and let a retrying dispatcher publish it to the queue.

Workflows, scheduled jobs, and Durable Objects

You can use a Cron Trigger to run periodic SQL queries through Hyperdrive for bounded jobs like rolling up yesterday’s totals, as long as you make reruns safe.

With Cloudflare Workflows, you can query PostgreSQL in one step, call an external service, and write the result back in a later step. Always open your database client inside the step that needs it, make retried writes idempotent, and never hold a SQL transaction open across a durable sleep or an external API call.

Durable Objects shine when you need one place to coordinate an entity like a chat room or a shared editing session. A Durable Object can talk to an external PostgreSQL database through Hyperdrive, though its built-in SQLite storage might already cover the state it owns, so don’t pull in a second database without a good reason.

Also remember that a Durable Object’s local transaction doesn’t cover PostgreSQL. If other apps can update the same PostgreSQL rows, keep your database constraints and transactional checks in PostgreSQL too.

Workers AI and Vectorize

For semantic document search, keep the original documents and ownership records in PostgreSQL. A background Worker can generate embeddings with Workers AI and store vectors tagged with document IDs in Vectorize.

When someone searches, Vectorize gives you candidate IDs, and your Worker checks permissions and fetches the real records through an uncached Hyperdrive configuration before returning anything or passing it to a model.

Treat Vectorize as a search index that can lag behind your database, never as your only permission check. If PostgreSQL already gives you the vector search you need, keeping search inside the database can be simpler.

Connect Hyperdrive to a private database

You don’t have to expose a public port on your database if you configure private connectivity.

Cloudflare recommends its Workers VPC integration (in beta) for this setup. A TCP VPC Service describes your database endpoint while cloudflared runs inside a network that can reach it, so Hyperdrive connects through that service and tunnel (covered in the private database guide):

Hyperdrive connecting to a private databaseThe Worker uses Hyperdrive, which reaches a private PostgreSQL server through a TCP VPC Service and an outbound Cloudflare Tunnel.WorkerHyperdriveTCP VPC ServiceCloudflare TunnelPrivate PostgreSQLserver

Set up the tunnel, create the TCP VPC Service using the PostgreSQL application protocol, and create a Hyperdrive configuration pointing to its service ID. Keep database TLS turned on.

There’s also a Tunnel and Access integration that uses an Access application and a service token, though the VPC path saves you from managing that extra Access token.

Your Worker code stays the same and still reads env.HYPERDRIVE.connectionString. Private routing only changes how Hyperdrive reaches the origin, not your SQL queries.

Measure performance before adding more services

Measure the real operations your app runs, including writes and uncached reads. A benchmark full of warm cache hits won’t tell you how an editing screen feels to use.

Watch request latency, query latency, database CPU, active origin connections, and your cache hit rate. Run your tests from the regions where your users live, and change one piece of the setup at a time so you know what helped.

If a request fires off several sequential database queries, cutting down those round trips often beats adding a cache. Use joins or batch queries where they fit, and inspect slow statements with PostgreSQL’s query tools.

Workers placement can also speed up database-heavy handlers by running them closer to your backend infrastructure. Because it changes the distance to every other service your Worker talks to as well, measure the full request before turning it on. You can read more in Cloudflare’s placement docs.

Pricing, limitations, and common problems

Hyperdrive is included on both the Workers Free and Paid plans. The Free plan gives you 100,000 database queries per day, while the Paid plan includes unlimited Hyperdrive queries. Every database statement counts toward that number, including writes and schema changes, and Workers execution plus your database host still carry their own pricing and limits. Check the Hyperdrive pricing page for full details.

Origin connections, configuration counts, and query execution each have their own caps, and your PostgreSQL server still has its own connection budget. Check the Hyperdrive limits alongside whatever your database provider allows.

SymptomWhat to check
Configuration creation failsDirect database hostname, credentials, firewall, TLS, and database reachability
Binding is undefinedBinding name, selected environment, and regenerated Wrangler types
Local works, deployed failsLocal dev bypasses the remote configuration, so check the remote database role and network path
A read returns an older value after an updateQuery caching, plus any separate HTTP or application cache
Connections fail under loadLong transactions, consumer concurrency, and the combined budgets of all configurations
Every request is still slowUncached network trips, SQL execution, missing indexes, or an overloaded database

A few PostgreSQL features don’t work through Hyperdrive, including LISTEN/NOTIFY, advisory locks, and SQL-level prepared statement management (driver-level PostgreSQL prepared statements are handled separately). Check the supported features list before migrating an existing app.

Keep a separate direct connection path for admin tasks, migrations, or any unsupported operations, and never put your migration role inside a public-facing Worker.

How I would use Hyperdrive

If you already have an app backed by PostgreSQL and want to move its HTTP endpoints to Workers, keep the database where it is and start with a single uncached Hyperdrive configuration.

Start by moving one read-only endpoint and comparing its behavior against the original. Once that looks solid, move authenticated writes after verifying transactions and authorization. Leave public query caching for last, and only turn it on for queries where stale data is acceptable.

For a small new app that fits SQLite, look at D1 before spinning up an external PostgreSQL host. And if you already have a Node.js server sitting right next to its database, stick with your existing connection pool unless moving to Workers solves a real problem for you.

The best fit for Hyperdrive is that small API server whose only job is connecting a frontend to PostgreSQL. You can move those endpoints to Workers and leave the database right where it is.

Want me to talk about your product? You can sponsor this site.

Related posts about cloudflare: