Hyperdrive foundations

Understand what Hyperdrive accelerates

Separate database connection setup and network latency from query execution and schema design.

8 minute lesson

~~~

A Worker can run near a user while an existing PostgreSQL or MySQL database remains in one region. That distance is the problem Hyperdrive exists to solve, and it’s worth seeing exactly where the time goes.

Opening TCP, negotiating TLS, and authenticating for each request adds round trips before the first query. For Postgres, a cold connection looks like this:

TCP handshake            1+ round trip
TLS negotiation          1-2 round trips
Postgres auth exchange   2+ round trips
your actual query        1 round trip

With the database in Virginia and a user in Sydney, each round trip costs around 200 ms. The connection setup alone burns most of a second, and the query you cared about is one round trip at the end. Workers make this worse than a traditional server, because there is no long-lived process holding a warm connection between requests.

What Hyperdrive changes

Hyperdrive keeps connection pools near the database and gives the Worker a nearby connection endpoint. The expensive setup happens once, close to the database, and stays warm. Your Worker’s driver connects to the closest Cloudflare data center over a fast path, borrows a pooled connection, and pays roughly one round trip instead of seven.

It can also cache eligible reads, so repeated identical queries may not reach the origin at all. A later lesson covers when that’s safe.

What it doesn’t change

Hyperdrive does not fix slow SQL, missing indexes, or an overloaded database by itself. A query that takes 900 ms to execute still takes 900 ms. Hyperdrive removes the connection tax, nothing more.

Before adding it, measure a direct connection so you know what you’re buying:

const start = performance.now()
const client = await connectDirectly(env.DATABASE_URL)
const connected = performance.now()

await client.query('select id, title from posts limit 20')
const queried = performance.now()

console.log(`connect: ${connected - start}ms, query: ${queried - connected}ms`)
// connect: 640ms, query: 45ms  <- connection-dominated: Hyperdrive helps
// connect: 90ms, query: 1200ms <- query-dominated: fix the SQL first

List time spent connecting, querying, and returning the response. If connecting dominates, Hyperdrive will transform your latency. If querying dominates, you have a database problem, and the honest fix is an index or a better query.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →