Back to Cloudflare

Connect Workers to Existing Databases With Hyperdrive

November 5, 2026 Wasil Zafar 33 min read

Distinguish connection acceleration from a database migration

Table of Contents

  1. Your Database Still Owns the Data
  2. Pooling and Query Caching Reduce Different Costs
  3. Drivers, Credentials, and Private Reachability
  4. Latency, Stale Queries, and Transaction Requirements
  5. Design a Worker-to-Postgres or MySQL Connection
  6. Compare Connection and Query Latency With Safe Test Data

Your Database Still Owns the Data

Northwind Trader runs its storefront on a single Postgres 16 instance in Frankfurt. The catalog API is read-heavy: categories, featured products, and stock counts. To cut latency for customers in Singapore and San Francisco, the team moves that API to a Worker. Staging, in the database's region, looks excellent; production does not. Every invocation opens a client, completes a TCP handshake, negotiates TLS, authenticates, runs three queries, and drops the connection. Postgres logs too many clients already.

Two conclusions look reasonable and are both wrong. The first, "migrate to D1," ignores a 400 GB catalog, Postgres extensions, and an ERP nobody will port. The second, "run PgBouncer on the VM," fixes the connection count but not the expensive part: every request still pays cross-region setup before it can query. The right answer is a proxy between the Worker and the database that terminates the driver connection near the Worker and keeps a warm pool near the origin.

That proxy is Hyperdrive: not a database, and not a custodian of your data, but a connection pooler and read-result cache in front of a Postgres or MySQL database you already operate.

Six terms matter:

  • The origin database is your existing Postgres or MySQL instance. It remains the system of record for schema, data, grants, backups, and extensions.
  • A connection is a stateful session between a driver and a server. Setting one up is expensive: the documented path is seven round trips — one TCP handshake, three for TLS negotiation, and three for database authentication.
  • A connection pool is a set of already-authenticated connections kept open for reuse. Reusing one skips all seven round trips.
  • Transaction pooling means a client checks out a pooled connection for the duration of a transaction and returns it when the transaction ends. Session state does not survive the return.
  • Query caching stores the result of an eligible read and serves it to a later matching read without contacting the origin.
  • A binding is the object the platform injects as env.HYPERDRIVE. At runtime it supplies a host, port, user, password, and database name, which your existing driver consumes as a connection string.

The analogy is a coffee counter in a distant city. Without Hyperdrive, every customer calls the roastery abroad, waits through seven identity checks, and only then orders. With Hyperdrive, a local counter takes the order in milliseconds, keeps a standing relationship with the roastery, and pins yesterday's price list for drinks that rarely change. The roastery still owns the beans, the recipes, and the invoices; the counter can neither invent a drink nor show a price change before the list is refreshed.

Figure 1 draws the boundary. The Worker only ever speaks to Hyperdrive. Hyperdrive speaks to a pool in the origin's region, and the pool speaks to the database. Writes follow the same path and are never served from cache.

Your Database Still Owns the Data
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    subgraph EDGE["Cloudflare edge, near the user"]
        W["Worker isolate
new Client per request"] H["Hyperdrive endpoint
TLS, auth, query parser, read cache"] end subgraph REGION["Origin region"] P["Connection pool
warm, pre-authenticated"] D[("Postgres or MySQL
schema, data, backups, grants")] end W -->|"driver connection to env.HYPERDRIVE"| H H -->|"cache hit: no origin round trip"| W H -->|"checkout a pooled connection"| P P -->|"SQL, including every write"| D D -->|"rows or acknowledgement"| P P -->|"return connection to the pool"| H H -->|"rows or cached rows"| W H -.->|"pool exhausted or origin down"| E["Error to the Worker
no silent fallback"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class W,H,P secondary; class E danger;

Figure 2 redraws the same system as layers. The dashed vertical line is the data boundary: everything to its right is unchanged by adopting Hyperdrive.

Hyperdrive sits between the Worker and the origin database A Worker isolate connects to a Hyperdrive endpoint in the same Cloudflare location. Hyperdrive terminates TLS and authentication, parses the statement, and serves eligible reads from a local cache. On a miss or a write it uses a pooled connection near the origin. Schema, data, grants, extensions, and backups remain on the origin database. Where Hyperdrive sits, and what it never owns Worker isolate new Client() inside the handler no global pool no client.end() 1 invocation driver Hyperdrive endpoint same Cloudflare location TLS and authentication statement parser read or write? read cache max_age 60s default writes never cached 1 hop Origin pool pre-authenticated near the database 5 to ~100 connections shared across Workers Origin database Postgres or MySQL schema and data grants and extensions backups and migrations system of record Pool exhausted Failed to acquire a connection Data boundary: the dashed vertical line separates your existing database estate. Connection setup moves to the edge. The origin still executes every statement and owns every byte.

Acceleration you can add or remove

Hyperdrive is an acceleration layer, not a data migration. You keep your ORM, migrations, backups, and runbook; only the handshake location and read freshness change. Removing the configuration leaves the origin untouched.

Pooling and Query Caching Reduce Different Costs

The Northwind catalog endpoint runs three sequential statements — categories, featured products, then stock counts. Compare three deployments.

Direct from the Worker. Each invocation performs seven setup round trips across the Internet, then three query round trips. If a San Francisco to Frankfurt round trip is about 150 ms — an assumption for arithmetic, not a measurement — setup alone is roughly 1.05 seconds. The queries add another 450 ms. The database also sees one connection per concurrent request, which is how too many clients already happens.

Hyperdrive with caching disabled. The driver still connects, but to an endpoint in the same Cloudflare location, so the handshake is local rather than intercontinental. Hyperdrive then uses a pre-authenticated pooled connection near Frankfurt, costing one region hop. The first statement starts after that hop, not after seven, and pooling caps the origin at the configured connection count regardless of concurrency.

Hyperdrive with caching enabled. The two read statements are eligible, so a repeat within max_age never reaches Frankfurt at all. Any write, and any read that is not eligible, still travels to the origin.

Pooling and caching remove different costs. Pooling removes setup cost and protects the origin's connection limit. Caching removes origin execution and transfer for repeated reads. Neither removes a fresh query's round trip; that is what placement does when an invocation issues several sequential statements. Inside Hyperdrive, a cache hit short-circuits before the pool, while every write checks out a connection.

PathWhat you operateCost before the first statementRead freshnessChoose it when
Worker to origin directlyNothing beyond the database7 round trips across the Internet, every invocationWhatever the origin returnsOne-off admin jobs, raw sessions, or a database already in the same region
Hyperdrive, caching disabledHyperdrive configuration and a least-privilege database userLocal handshake, then 1 region hop to a pooled connectionFresh from the originExisting Postgres or MySQL, write-heavy traffic, or read-after-write paths
Hyperdrive, caching enabledThe same, plus a freshness budgetLocal handshake, then 0 hops on a hitUp to max_age (default 60 s) plus 15 s stale-while-revalidatePublic catalogs, dashboards, search, and other reads that tolerate brief staleness
D1A managed SQLite database and its migrationsNone; it is a bindingPrimary reads are current; read replicas can lagNew lightweight apps, read-heavy global users, at most 10 GB per database
Durable Objects with SQLiteA class, a migration, and an ID schemeNone; it is a binding and an RPCStrongly consistent per objectCoordination, per-user or per-tenant state, WebSockets, strict ordering

The last two rows are alternatives. D1 suits a new, read-heavy application database below its hard 10 GB per-database ceiling. Durable Objects suit coordination: one identity serializing decisions or holding a socket, with strongly consistent SQLite per object. Hyperdrive suits data that already lives in Postgres or MySQL, exceeds a serverless database's appetite, and is written by systems you are not rewriting.

Figure 3 is the sequence with failure branches. The parser decides cache eligibility before any connection is checked out, which is why an uncacheable read still consumes a pool slot.

Pooling and Query Caching Reduce Different Costs
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
sequenceDiagram
    participant W as Worker
    participant H as Hyperdrive edge
    participant P as Pool near origin
    participant D as Postgres or MySQL
    W->>H: connect with env.HYPERDRIVE.connectionString
    H->>H: parse statement and read or write intent
    alt eligible read and cache hit
        H-->>W: rows, cacheStatus=hit
    else eligible read and cache miss
        H->>P: check out a connection
        P->>D: SELECT with bound parameters
        D-->>P: rows
        P-->>H: rows, connection returned to pool
        H-->>W: rows, cacheStatus=miss
    else write or uncacheable read
        H->>P: check out a connection
        P->>D: statement, then COMMIT or ROLLBACK
        D-->>P: result
        P-->>H: result, connection reset and returned
        H-->>W: result, cacheStatus=uncacheable or disabled
    end
    alt pool exhausted
        H--xW: Failed to acquire a connection from the pool
    else origin unreachable
        D--xP: connection refused
        P--xH: checkout fails
        H--xW: error, no cached write
    end

The widget is the smallest complete version of the pattern: a per-request client, a parameterized cacheable read, a short transaction, and a second cache-disabled binding for a read that must be fresh. The SQL panel creates the tables it uses.

// src/index.ts
import { Client } from "pg";

interface Env {
  HYPERDRIVE: Hyperdrive;
  HYPERDRIVE_FRESH: Hyperdrive;
}

async function withClient<T>(
  connectionString: string,
  fn: (client: Client) => Promise<T>,
): Promise<T> {
  // Create the client inside the invocation. Never at module scope.
  const client = new Client({ connectionString });
  await client.connect();
  // No end() needed: Workers cleans up the edge connection when the
  // invocation ends. The origin connection stays pooled for reuse.
  return fn(client);
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);

    if (url.pathname === "/articles") {
      const day = new Date().toISOString().slice(0, 10);
      // Stable within a UTC day: a per-request timestamp would create a
      // new cache key on every call and defeat caching.
      const since = url.searchParams.get("since") ?? `${day}T00:00:00Z`;

      const rows = await withClient(env.HYPERDRIVE.connectionString, (client) =>
        client
          .query(
            `SELECT id, title, published_at
               FROM articles
              WHERE published_at >= $1
              ORDER BY published_at DESC
              LIMIT 50`,
            [since],
          )
          .then((result) => result.rows),
      );

      return Response.json(rows, {
        headers: { "cache-control": "public, max-age=30" },
      });
    }

    if (url.pathname === "/orders" && request.method === "POST") {
      const body = await request.json<{ sku: string; qty: number }>();

      const result = await withClient(env.HYPERDRIVE.connectionString, async (client) => {
        await client.query("BEGIN");
        try {
          const stock = await client.query<{ stock: number }>(
            "SELECT stock FROM inventory WHERE sku = $1 FOR UPDATE",
            [body.sku],
          );
          const available = stock.rows[0]?.stock ?? 0;
          if (available < body.qty) {
            await client.query("ROLLBACK");
            return { status: 409, body: { error: "out_of_stock" } };
          }
          await client.query(
            "UPDATE inventory SET stock = stock - $1 WHERE sku = $2",
            [body.qty, body.sku],
          );
          const order = await client.query<{ id: string }>(
            "INSERT INTO orders (sku, qty) VALUES ($1, $2) RETURNING id",
            [body.sku, body.qty],
          );
          await client.query("COMMIT");
          return { status: 201, body: { id: order.rows[0].id } };
        } catch (error) {
          await client.query("ROLLBACK").catch(() => undefined);
          throw error;
        }
      });

      return Response.json(result.body, { status: result.status });
    }

    if (url.pathname === "/me") {
      // Authentication and permissions must not read a stale cache entry.
      const rows = await withClient(env.HYPERDRIVE_FRESH.connectionString, (client) =>
        client
          .query("SELECT id, email FROM users WHERE session_id = $1", [
            request.headers.get("x-session-id"),
          ])
          .then((result) => result.rows),
      );
      return Response.json(rows);
    }

    return Response.json({ error: "not_found" }, { status: 404 });
  },
} satisfies ExportedHandler<Env>;
-- PostgreSQL 13 or later. MySQL equivalents use AUTO_INCREMENT and DATETIME.
-- Run against the origin database as a migration, once.
CREATE TABLE IF NOT EXISTS articles (
  id BIGSERIAL PRIMARY KEY,
  title TEXT NOT NULL,
  published_at TIMESTAMPTZ NOT NULL
);

CREATE TABLE IF NOT EXISTS inventory (
  sku TEXT PRIMARY KEY,
  stock INTEGER NOT NULL CHECK (stock >= 0)
);

CREATE TABLE IF NOT EXISTS orders (
  id BIGSERIAL PRIMARY KEY,
  sku TEXT NOT NULL REFERENCES inventory(sku),
  qty INTEGER NOT NULL CHECK (qty > 0),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

INSERT INTO articles (id, title, published_at) VALUES
  (1, 'Cache boundaries', '2026-10-01T09:00:00Z'),
  (2, 'Pool exhaustion', '2026-10-02T09:00:00Z')
ON CONFLICT (id) DO NOTHING;

INSERT INTO inventory (sku, stock) VALUES ('SKU-1', 10)
ON CONFLICT (sku) DO NOTHING;

CREATE TABLE IF NOT EXISTS users (
  id BIGSERIAL PRIMARY KEY,
  email TEXT NOT NULL,
  session_id TEXT UNIQUE NOT NULL
);

INSERT INTO users (id, email, session_id) VALUES
  (1, 'ops@example.com', 'test-session')
ON CONFLICT (id) DO NOTHING;

-- Cacheable: the Worker binds this window as $1. A literal keeps the
-- script runnable as written.
SELECT id, title, published_at
FROM articles
WHERE published_at >= TIMESTAMPTZ '2026-10-01T00:00:00Z'
ORDER BY published_at DESC
LIMIT 50;

-- Uncacheable: NOW() is STABLE, so Hyperdrive skips the cache.
SELECT id, title, published_at
FROM articles
WHERE published_at >= NOW() - INTERVAL '1 day'
ORDER BY published_at DESC
LIMIT 50;

-- The transaction shape the Worker relies on: one connection, short,
-- and no external calls between BEGIN and COMMIT. ROLLBACK keeps this
-- script re-runnable; the Worker performs the same shape with COMMIT.
BEGIN;
SELECT stock FROM inventory WHERE sku = 'SKU-1' FOR UPDATE;
UPDATE inventory SET stock = stock - 1 WHERE sku = 'SKU-1';
INSERT INTO orders (sku, qty) VALUES ('SKU-1', 1);
ROLLBACK;

Two details in the widget matter more than they look. The read passes its lower bound as a parameter, because a literal timestamp makes the query uncacheable — and so does naming a volatile function in a SQL comment, since detection is textual.

The transaction stays short on purpose. It holds its connection across three statements, because a pooled connection is unavailable to every other Worker until COMMIT or ROLLBACK.

Drivers, Credentials, and Private Reachability

Reachability, authorization, and consistency are separate settings. A green connection test proves only the first.

Reachability is a name and a route. A connection-string configuration resolves a public hostname to a public address; name resolution, private-address, and routing failures produce distinct errors in the 2008–2010 range. For a database inside a VPC or an on-premises network, do not paste a private IP into a connection string. Create a TCP VPC Service, route it over a Cloudflare Tunnel, and point the configuration at that service.

# TLS is mandatory. Postgres refuses sslmode=none and sslmode=prefer;
# sslmode=require or sslmode=verify-full are accepted.
# MySQL: sslMode=REQUIRED, VERIFY_CA, or VERIFY_IDENTITY.
dig +short db.internal.example.com

# A private address such as 10.0.4.12 will not resolve from the edge.
# Route it through a TCP VPC Service instead.
npx wrangler vpc service create northwind-postgres \
  --type tcp \
  --tcp-port 5432 \
  --app-protocol postgresql \
  --tunnel-id "$TUNNEL_ID" \
  --ipv4 10.0.4.12

# Cached configuration: eligibility is decided per read.
npx wrangler hyperdrive create northwind \
  --service-id "$VPC_SERVICE_ID" \
  --database northwind \
  --user hyperdrive_app \
  --password "$DB_PASSWORD" \
  --scheme postgresql

# Second configuration for reads that must see the latest write.
npx wrangler hyperdrive create northwind-fresh \
  --service-id "$VPC_SERVICE_ID" \
  --database northwind \
  --user hyperdrive_app \
  --password "$DB_PASSWORD" \
  --scheme postgresql \
  --caching-disabled
// wrangler.jsonc
{
  "name": "northwind-catalog",
  "main": "src/index.ts",
  "compatibility_date": "2026-11-02",
  "hyperdrive": [
    { "binding": "HYPERDRIVE", "id": "<CACHED_CONFIG_ID>" },
    { "binding": "HYPERDRIVE_FRESH", "id": "<FRESH_CONFIG_ID>" }
  ]
}

Workers VPC is the recommended path because it avoids Access applications and service tokens. The older Tunnel-plus-Access route remains when you need Access policies in front of the hostname; the service id is what the Hyperdrive configuration consumes.

Credentials are a separate axis from reachability. Create a dedicated user with only the privileges the application needs. The configuration-time test issues an empty query and fails with 2016 when the user cannot read and write, so it proves reachability and basic grants — not least privilege.

Use one user per application. Revocation then becomes a privilege change on the origin and a configuration update, not a redeploy.

TLS is mandatory and lives on the connection. Postgres refuses plaintext and opportunistic modes; its accepted modes validate the chain, and the strictest also checks the hostname. MySQL mirrors that ladder from encryption to chain verification to identity. A private CA or client certificate needs the separate TLS certificate configuration, and a mismatch surfaces as a certificate-validation failure rather than a password error.

Support is a version floor, not a range. Each driver has a documented minimum, and all of them need Node.js compatibility enabled.

// src/index.ts
import { Client } from "pg";

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // One client per invocation. Hyperdrive owns the origin-side pool.
    const client = new Client({
      connectionString: env.HYPERDRIVE.connectionString,
    });
    await client.connect();
    const result = await client.query("SELECT 1 AS ok");
    return Response.json(result.rows);
  },
} satisfies ExportedHandler<Env>;
# Postgres: pg is the recommended driver
npm i pg@8.16.3
npm i -D @types/pg

# Postgres.js is also supported
npm i postgres@3.4.5

# MySQL instead of Postgres
npm i mysql2@3.13.0

One client per invocation, created inside the handler. Do not cache it at module scope and do not call end(): the platform cleans up the edge connection when the invocation ends, while the origin connection stays pooled for reuse. With Postgres.js, leave prepared statements at their default — disabling them adds type-discovery messages that transaction pooling cannot relay, and queries can hang.

Consistency is neither TLS nor the tunnel. Freshness is controlled by caching and by transaction isolation. If a path must see its own writes, route it through a second configuration created with --caching-disabled, bind both, and keep separate clients.

Do not lower the freshness window to one second. The stale window still exists and the origin load returns. A cache-disabled path is the only guarantee.

Check the layer before the password. A name that resolves to a private address fails with 2009; a public endpoint with a wrong password fails with 2013. The code identifies the layer, and neither one says whether a cached read is stale.

The password lives in the configuration, not the repository. The binding supplies a generated connection string at runtime, which protects your repository but not your account: anyone who can edit the configuration can change the user, and anyone who can read the Worker's environment can use the binding. Scope dashboard roles accordingly, and rotate by updating the configuration rather than redeploying code.

Latency, Stale Queries, and Transaction Requirements

A database call has four costs: connection setup, pool queueing, origin execution, and transfer. Edge termination removes most of setup; the origin pool removes repeated authentication and caps concurrency; query caching removes execution and transfer for a repeated read. Queueing appears only under contention, and it is the one that turns a latency problem into an outage.

Placement addresses the remaining hop. Cloudflare documents 20–30 ms per query from a distant region versus 1–3 ms nearby. One query per request does not benefit, because the total round trip is the same wherever it happens; five sequential queries do, and the difference compounds. That makes placement.region a query-count decision, not a universal default.

Caching has a narrow contract. Defaults are a 60-second max_age and 15 seconds of stale_while_revalidate, with a one-hour maximum. Only eligible reads are stored; writes, multi-statement queries, and queries that call volatile functions are not.

Volatile functions disqualify a read. Anything that depends on the clock or on randomness, such as NOW() or RANDOM(), makes a query uncacheable — which is why the widget computes its window in TypeScript. A parameter helps only if it repeats; deriving one from the current time on every request creates a new cache key each time.

A write does not invalidate the cache

A read issued immediately after an UPDATE can return the pre-write result until the freshness window expires, and the metric still reports cacheStatus=hit. That is the cache working as documented, not a bug; route the path through a cache-disabled binding when it must see its own write, and never use a SQL comment as a cache-control switch.

Figure 4 shows the before-and-after timeline and the freshness window that makes stale reads possible. The cache hit is fast precisely because it is allowed to be old.

Connection setup and freshness before and after Hyperdrive Three timelines share a time axis. A direct connection spends seven round trips on TCP, TLS, and authentication before the query. Hyperdrive performs setup in the same location, then one cross-region hop to a pooled connection. A cache hit performs setup locally and returns a stored result with no origin hop. A freshness bar shows the default 60 second max_age followed by 15 seconds of stale-while-revalidate. Same query, three cost profiles Direct TCP TLS x3 auth x3 query and rows 7 setup round trips before SQL Pooled edge setup 1 region hop query and rows no re-authentication at the origin Cache hit edge setup cached rows origin never consulted Freshness max_age, default 60 s SWR 15 s origin required A write does not reset this bar. Cache-disabled reads skip it entirely. Setup cost: paid once per invocation in the edge, not once per request across an ocean. Query cost: one origin hop, reducible with placement. Cache cost: bounded staleness.

Transaction pooling changes what a connection can hold. The connection belongs to your transaction from its first statement to its commit or rollback, then returns to the pool and is reset.

Supported: normal multi-statement transactions, settings scoped to the transaction, transaction-level advisory locks such as pg_advisory_xact_lock, and named prepared statements.

Unsupported: session-scoped settings such as a search path, session-level advisory locks, pub/sub notification through LISTEN and NOTIFY, and SQL-level prepared statements. A session lock can outlive your client and block other requests.

MySQL is stricter. Prepared statements, multi-statement queries, database switching with USE, and non-UTF8 queries are unsupported.

Four failure modes account for most production incidents. Each has a signature that names the layer.

FailureSignatureResponse
Stale read after a writecacheStatus=hit on a value older than the writeMove the read to the cache-disabled binding; do not add a comment as a workaround
Transaction assumptionprepared statement does not exist, a lost session setting, or the MySQL prepare messageKeep the state inside the statement, or use a transaction-scoped feature
Pool exhaustionFailed to acquire a connection from the pool.Shorten transactions, remove external calls between the boundaries, and watch waitingClients and currentPoolSize
TLS or authentication mismatch2012 for no TLS, 2013 for bad credentials, 2011 or a refused connection for a firewallFix the TLS mode, then the credentials, then the provider cap or the CA and hostname

Durable Objects hold connections open

A regular Worker's client is cleaned up at invocation end. A Durable Object that keeps a client open holds a pooled origin connection for as long as the object lives, and many such objects can exhaust the pool. Close clients when idle, or keep database access in ordinary Workers.

Design a Worker-to-Postgres or MySQL Connection

The exercise builds the smallest defensible deployment: one public Postgres database, two Hyperdrive configurations, two bindings, and a measurement plan that distinguishes a cache hit from a fast query.

Guided exercise

Design a Worker-to-Postgres or MySQL Connection

Status: design-only — not executed for this draft. Commands and expected observations come from Cloudflare documentation reviewed on 2026-11-05. No Wrangler command was run, no request was measured, and no cost was incurred. Treat every result below as a prediction to verify.

Prerequisites. A Cloudflare account on the Workers Free plan is enough; Hyperdrive is included on Free and Paid. Node.js 20 or later, npm, and a terminal whose Wrangler session points at the intended account. A Postgres 13+ or MySQL 8 database you control, reachable on a public hostname over TLS, with permission to create a schema. The local-only variant needs only Docker with a postgres:16 container and no Cloudflare resources. Do not use production data; the seed rows are synthetic.

Inputs. A dedicated user and database both named hyperdrive_lab, the SQL from the earlier widget, a compatibility date of 2026-11-02, and a project name such as hd-lab-initials. The walkthrough uses Postgres and the pg driver; a MySQL run substitutes mysql2 and a MySQL URL.

Steps.

  1. Create the user and database on the origin. Grant connect, schema usage, and select, insert, and update on the four tables only — never superuser or create-database rights.
  2. Run the SQL panel against the origin. Expect two catalog rows and a stock level of ten for the seeded SKU.
  3. Create the cached configuration with the create command from the configuration widget, substituting your own connection string. Record the printed ID; the command performs a test connection and an empty query, so a failure here is a configuration error, not a runtime one.
  4. Create the fresh configuration against the same database with --caching-disabled, and record its ID separately.
  5. Bind both in the Wrangler file, set the compatibility date, and enable observability. Add the Node.js compatibility flag if your date predates 2026-08-04. Run npx wrangler types.
  6. Replace the Worker source with the earlier widget, point local development at a direct connection string, and start the dev server. Local mode bypasses Hyperdrive, so this step validates SQL and types only.
  7. Insert an order with a POST, then request the catalog twice. Locally both reads reach the database; confirm the JSON shape and that the session lookup returns the seeded user. Cache behavior is not observable in this mode.
  8. Deploy and repeat the request pair against the deployed URL. Expect the first catalog read to record a miss and the second within 60 seconds to record a hit. Then change a row in the origin and repeat the read inside 60 seconds: the old value is the cache working as documented.
  9. Inspect the Hyperdrive metrics tab and the per-query dataset. Record cache status, connection latency, and query latency for both bindings, plus waiting clients under load.
# Local: a direct connection string, not the Hyperdrive endpoint
export CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE="postgres://hyperdrive_lab:PASSWORD@HOST:5432/hyperdrive_lab"
export CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE_FRESH="$CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE"
npx wrangler dev

# Hosted
npx wrangler deploy

# Cleanup
npx wrangler hyperdrive delete <CACHED_ID>
npx wrangler hyperdrive delete <FRESH_ID>
npx wrangler delete

Expected observations.

CheckPredicted observation
First deployed catalog readcacheStatus=miss, rows returned
Second read within 60 secondscacheStatus=hit, origin not contacted
Read through the fresh bindingcacheStatus=disabled, seeded user
Query with a relative date windowcacheStatus=volatile, not cached
Origin row edited, read inside 60 secondsThe pre-write value, served from cache
Statement longer than 60 secondsTerminated at the query limit
Response larger than 50 MBReturned, not cached
Long transaction under loadPool exhaustion, rising waiting clients

Failure checks.

  • Change the password in the connection string and update the configuration: expect a credentials error (2013).
  • Replace the host with a private address such as 10.0.4.12: expect 2009, because a connection-string configuration requires a public address.
  • Run a query that sleeps for 70 seconds: expect termination at the 60-second limit.
  • Open a transaction that calls an external API between the boundaries under load: expect pool exhaustion and rising waiting clients.
  • Query with a relative date window: expect a volatile cache status and no caching.

Cost dimensions. Free plan: 100,000 Hyperdrive queries per day, 10 configurations, roughly 20 origin connections per configuration. Every statement counts, cached or not, and the counter resets at 00:00 UTC. Paid removes the daily query cap and raises the configuration and connection ceilings. Egress through Hyperdrive is not charged. A managed Postgres provider may bill its own compute and storage separately.

Cleanup. Delete both configurations and the Worker, then drop the lab database and user on the origin. Stop the dev server, remove the local state directory and the project folder, and remove the Docker container if you used one.

The two checks that teach the most are the 70-second statement and the transaction held across an external call. Both look like a slow database and are actually pool hygiene: one statement runs past the 60-second ceiling, and one transaction holds a connection across a non-database call. Neither is fixed by adding connections.

Compare Connection and Query Latency With Safe Test Data

Verification date: 2026-11-05. Basis: official Cloudflare documentation reviewed on that date. Execution status: design-only. No Wrangler command, deployed request, or database query was executed for this draft, so the criteria below are documented expectations, not measurements. Tested versions: none. Record your own npx wrangler --version, Node.js version, driver version, compatibility_date, database engine version, and account plan before treating a result as evidence.

Pass evidence. A correct deployment should show:

  • A first request to /articles returns 200 with rows, and Hyperdrive metrics record cacheStatus=miss.
  • A second identical request within 60 seconds records cacheStatus=hit, and queryLatency is near zero because the origin was not contacted.
  • A request to /me through HYPERDRIVE_FRESH records cacheStatus=disabled and returns the seeded user rather than a cached copy.
  • A query containing NOW() records cacheStatus=volatile, not hit.
  • A read of the same row through the cached and fresh bindings, within 60 seconds of a write, returns the pre-write and post-write values respectively.
  • connectionLatency stays low and stable across requests, while queryLatency tracks origin execution. A rising waitingClients means contention, not slow SQL.
  • A statement longer than 60 seconds is terminated, and a response larger than 50 MB is returned but not cached.

Fail signatures. These distinguish the layers:

  • Failed to acquire a connection from the pool. — pool exhaustion, usually a long transaction or a leaked client in a Durable Object.
  • connection_refused — a firewall or ACL rejection, or the provider's own connection cap.
  • 2012, 2013, 2014 — TLS unsupported, bad credentials, missing database.
  • TLS handshake failed: cert validation failed — wrong CA or hostname, not a wrong password.
  • prepared statement ... does not exist or the MySQL COM_STMT_PREPARE message — a driver assumption that transaction pooling does not support.
  • A stale read with cacheStatus=hit — caching, by design; move the path to the fresh binding.

Self-check. Answer before reading the explanations.

  1. Does a cache hit mean the query never reached Postgres? For an eligible read inside max_age, yes: Hyperdrive serves the stored result and the origin is not contacted. It does not mean the data is current, only that it was current when the entry was stored.
  2. Can you keep pooling and still get fresh reads? Yes. Create a second configuration with --caching-disabled and bind it alongside the cached one. You lose the cache, not the edge setup or the origin pool.
  3. Why is SET search_path unreliable across requests? The pooler is in transaction mode and resets a connection when it returns to the pool. Session state belongs to a connection, and your next query may get a different one. Scope the setting inside the transaction, or qualify object names.
  4. Does Hyperdrive replace migrations, backups, or extensions? No. It forwards the wire protocol to the database you already run. Schema changes, pg_dump, point-in-time recovery, and extension upgrades remain origin responsibilities.

Execution gaps remain. This draft did not execute the exercise, so no latency, throughput, cache-hit ratio, or cost figure is claimed. Local development bypasses Hyperdrive when a direct connection string is set, so it cannot validate pooling or caching; remote development can, but it writes to the configured origin and must not point at production.

Documented ranges are not guarantees. The 20–30 ms versus 1–3 ms guidance is an order of magnitude, not a promise for a region pair. Limits, quotas, and prices change, so re-check them when you rely on them. Connection counts are a soft limit, so a partition can briefly exceed the configured maximum.

Authoritative references.

Next in the Series

In Choose Queues or K2 for Asynchronous Events, we'll explore Separate units of work from replayable event streams.