// Stack

Hyperdrive

Last updated ·

Hyperdrive is a Cloudflare service that connects Workers to an existing Postgres or MySQL database: it sets up connections near the Worker, pools them near the database, and can cache read queries. EOXLABS uses Hyperdrive when the system of record must stay in Postgres, often on Neon, while the code that queries it runs at the edge.

What problem does Hyperdrive solve?

A Worker is stateless and runs in many locations at once. Connecting it straight to one central database has two costs that Cloudflare's description of how Hyperdrive works names directly. First, every invocation repeats the connection handshake across the full distance to the database, which can take several round trips before the first query runs. Second, distributed traffic opens connections from everywhere and can exhaust the database's connection limit.

Hyperdrive answers each cost separately:

  1. Edge connection setup. The driver's handshake happens between the Worker and Hyperdrive in the same location, not across the continent.
  2. Pooling near the origin. Hyperdrive keeps a pool of warm connections in one or more regions closest to the database and caps how many it opens.
  3. Query caching. Read-only query results can be served from cache without reaching the database at all.

How does EOXLABS use Hyperdrive in practice?

Two bindings, two freshness rules. Hyperdrive does not invalidate cached results when the application writes. A matching SELECT can return a cached result until its max_age expires (60 seconds by default, at most 1 hour), plus a 15-second stale-while-revalidate window. Cloudflare's query caching guide therefore recommends a second, cache-disabled configuration for authentication, sessions, permissions, billing state and reads that follow a write. Wherever a Worker mixes the two kinds of read, EOXLABS binds both and decides per query which one to use.

import { Client } from "pg";

export default {
  async fetch(request, env, ctx): Promise<Response> {
    const userId = await authenticate(request, env); // fails closed; defined elsewhere

    // Reads that tolerate a short stale window use the cached configuration.
    const cached = new Client({ connectionString: env.HYPERDRIVE.connectionString });
    // Permissions and reads after writes use a cache-disabled configuration.
    const fresh = new Client({ connectionString: env.HYPERDRIVE_FRESH.connectionString });
    await Promise.all([cached.connect(), fresh.connect()]);

    // A day-granular parameter instead of CURRENT_DATE keeps the query cacheable.
    const today = new Date().toISOString().slice(0, 10);
    const [articles, roles] = await Promise.all([
      cached.query("SELECT id, title FROM articles WHERE published_on = $1 LIMIT 50", [today]),
      fresh.query("SELECT role FROM memberships WHERE user_id = $1", [userId]),
    ]);

    ctx.waitUntil(Promise.all([cached.end(), fresh.end()]));
    return Response.json({ articles: articles.rows, roles: roles.rows });
  },
} satisfies ExportedHandler<Env>;

SQL written to be cacheable. Hyperdrive caches a read query only if every function it calls is one PostgreSQL marks IMMUTABLE. A query that calls NOW(), CURRENT_DATE or RANDOM() is never cached, so EOXLABS computes those values in the Worker and passes them as parameters, at the coarsest granularity the query allows. A parameter that changes every millisecond would defeat the cache just as surely.

Respect transaction pooling. The pool runs in transaction mode: a client holds a connection only for the duration of one transaction, and the connection is reset when it returns to the pool. A SET therefore lasts for one query or transaction, and session-level advisory locks are not supported; pg_advisory_xact_lock inside an explicit transaction is the supported form. Transactions stay short, because a transaction held open across slow work pins a pooled connection and leads to Failed to acquire a connection from the pool.

Supported drivers, created per request. Cloudflare's Postgres connection guide recommends pg (8.16.3 or later) and also supports Postgres.js (3.4.5 or later), as long as prepared statements stay enabled. Clients are created inside the handler, never in global scope. For compatibility dates of 2026-08-04 or later, the Node.js compatibility these drivers need is on by default.

Placement when one request makes several queries. If a request runs queries in sequence, EOXLABS places the Worker near the database with a placement hint, as described on the Cloudflare Workers page. A request with a single query gains nothing from placement.

Private origins and Neon. A database inside a private network is reached through Cloudflare Tunnel and Access or through Workers VPC, as Cloudflare's private database guide describes, so the database never needs a public address. For Neon Postgres, Cloudflare's Neon setup guide uses Neon's direct connection string rather than its pooled one, because Hyperdrive does the pooling.

Which Hyperdrive limits matter?

Limit (Workers Paid)ValueDesign consequence
Origin connections per configurationAbout 100 (about 20 on Free), a soft limit that can be exceeded brieflyPostgres max_connections is sized for the sum across all configurations, cached and fresh
Query duration60 secondsReports and backfills run outside the request path
Cached response size50 MB; larger results are returned but not cachedLarge result sets are paginated
Cache lifetimemax_age 60 seconds by default, 1 hour at mostSet per configuration, by how stale each read may be

How should a Worker reach Postgres?

Direct driver connectionHyperdrive, caching onHyperdrive, caching offMove the data to D1
Connection cost per requestFull handshake across the distanceHandshake at the edgeHandshake at the edgeNone; a binding
Origin connectionsGrow with traffic; can exhaust the limitPooled and cappedPooled and cappedNone
Read freshnessFreshUp to max_age old, plus the stale-while-revalidate windowFreshSequentially consistent within a session
Postgres behaviorFull session semanticsTransaction-mode poolingTransaction-mode poolingSQLite dialect
Best fitLow-volume internal toolsPublic, read-heavy queriesAuth, permissions, writesSmall, partitionable datasets

Moving data into D1 removes the central round trip entirely, but only for data that fits its 10 GB-per-database model. Large or long-lived systems of record usually stay in Postgres, which is why Hyperdrive is central to legacy-to-edge migration: the Worker moves first and the database moves later, if ever. The monolith-to-edge migration note walks through that sequence, and the same reasoning applies to Postgres systems of record in financial services.

When not to use Hyperdrive

  • Code that depends on session state. Session-level advisory locks and SET values expected to persist between transactions break under transaction pooling.
  • Fresh reads through a cached configuration. If a read must reflect a write that just happened, route it through a cache-disabled configuration, not the default one.
  • Queries longer than 60 seconds. They are terminated; run them as jobs against the database directly.
  • Small datasets with no reason to stay central. Data that partitions cleanly per tenant often belongs in D1, closer to every user.
  • Drivers outside the supported list. Cloudflare notes that named prepared statements in other drivers may perform worse or may not be supported.

Hyperdrive is the bridge between the edge platform and the data layer of the EOXLABS stack.

→

Related

+

More stack

Have a system that can’t go dark?

Start a project →