Faster PlanetScale Postgres connections with Cloudflare Hyperdrive

Published: (February 18, 2026 at 07:00 PM EST)
11 min read

Source: PlanetScale Blog

Cloudflare Hyperdrive & Real‑Time Apps with PlanetScale Postgres Metal

Cloudflare recently launched Hyperdrive, which provides efficient pooling and fast queries for any MySQL or Postgres database—making it incredibly easy to optimise how your application connects to its data store.
Once you’re operating inside the Cloudflare network you get access to the full suite of features, including WebSockets, which we can use to build a real‑time experience.

In this post I’ll outline the decisions made while building a real‑time application backed by PlanetScale Postgres Metal.

Note – You won’t see “how‑to” code snippets for application code or SQL queries here. I’m assuming you’re describing what you want to an LLM, so this post focuses on what I did (and didn’t do) rather than step‑by‑step code.


The Infrastructure Stack

  • PlanetScale Postgres Metal – the benchmarked fastest cloud Postgres. It uses locally‑attached NVMe SSD drives instead of network‑attached storage.
  • Cloudflare Hyperdrive – fast access and automated connection pooling for Postgres/MySQL. It’s an almost zero‑config way to build high‑performance apps.
  • Cloudflare Workers – globally distributed compute that gives you the network benefits of being inside the Cloudflare global network, including WebSockets.
  • Durable Objects – stateful, single‑origin request handlers for coordinating tasks (e.g., a list of open WebSocket connections).

That paragraph contains a lot of names of things—let’s unpack each of them and see how they intersect.

Cloudflare Global Network

Infrastructure that runs all Cloudflare services from physical locations within ~50 ms of 95 % of the world’s internet‑connected population, with faster‑than‑average connections to almost every service and cloud provider.

Hyperdrive Architecture

  1. Edge component – runs globally from every Cloudflare data centre and prepares the 7 round‑trip steps of creating a connection to your database within the Cloudflare network.
  2. Connection pool – sits physically close to your database and maintains warm connections to Postgres, automatically handing them to incoming requests.

Workers & Smart Placement

Workers distribute your application globally. Performance can be improved by moving the Worker closer to the database through “smart placement” (covered later).

WebSockets

Supported by Cloudflare; we’ll use them to coordinate real‑time updates from PlanetScale Postgres via a Durable Object.


Hyperdrive vs. Direct Connections

If you’d like a demo comparing Hyperdrive with direct database connections, see Jilles Soeters’ demo: Globally Fast Applications with Cloudflare Hyperdrive and PlanetScale.


The Front‑End Stack

  • React Router 7 – front‑end framework.
  • Tailwind CSS – styling.

I won’t go into detail because these choices matter less than they used to. Cloudflare even provides a React Router 7 starter template pre‑configured for Workers deployment.


Piecing the Puzzle Together

All of the above are excellent building blocks, but how and where you assemble them greatly impacts performance.

Durable Objects & Write Path

It might be tempting to make a Durable Object the write path to the database, but that hurts performance:

  • Durable Objects are single‑threaded and live in a single location.
  • They are therefore a poor choice for the write path.

Instead: Workers send transactions to the database via the Hyperdrive connection.

Global Distribution vs. Latency

  • Distributing the app via Workers places it worldwide, but those edge locations can be far from the database and the Hyperdrive pool (which exist in a single origin).
  • Smart placement can move the Worker to a single location, reducing latency between Worker and database while still keeping the user‑to‑Worker latency low.

In this demo I did not use smart placement and kept the Worker close to every user. Monitor your own app’s performance to decide whether minimizing Worker‑to‑database latency or user‑to‑Worker latency is more important.

WebSockets Reliability

WebSockets alone may not be a bullet‑proof source of real‑time data:

  • This demo omits reconnection logic, which would help recover from failed WebSocket updates.
  • Adding periodic polling could catch missed updates.

You need to draw the line somewhere. This app demonstrates extreme performance, but your mileage may vary; suitability depends on your workload.


Problem Solving

It’s one thing to build an app that returns fast queries through Hyperdrive’s connection pooling and caching… (the post continues).

Demo Overview

In a nutshell, our demo app recreates the core functionality of a prediction market: users can buy “Yes” or “No” options on each market. The price of each option fluctuates based on the current volume of purchases on either side.

This creates several layers of complexity that will need to leverage all of the previously mentioned Cloudflare functions.


Core Requirements

RequirementWhy it matters
Fast readsPrediction markets are based on live events, so retrieving the most up‑to‑date information with low latency is critical.
Real‑time updatesUsers should see changes (trends, purchase activity, price moves) instantly without refreshing the page.
Fast writesOption prices can be volatile; transactions must be sent with the correct price and persisted quickly enough to broadcast updates to all other users.

Step 1: Connecting Hyperdrive

You can connect Hyperdrive to a database through the Cloudflare dashboard, the CLI, or during the creation of a PlanetScale Postgres database.

  1. Create a PlanetScale database

    • In the PlanetScale dashboard, select the smallest Metal database (starts at $50/month).
    • The $5/month non‑Metal tier could also work for this demo.
  2. Link PlanetScale to Cloudflare

    • Once the cluster is ready, create a new role and follow the instructions to generate a connection link between PlanetScale and Cloudflare.
    • The result is a connection string that you add to your app’s wrangler.jsonc file:
{
  // ...
  "hyperdrive": {
    "binding": "HYPERDRIVE_PLANETSCALE",
    "id": "e4fe..."
  }
}

Note: During local development reads and writes to the remote database will be slower than in production. You can target a local database for faster reads/writes, but you won’t benefit from Hyperdrive’s pooling and caching optimizations.

  1. Deploy
    After scaffolding the basic read/write logic, deployment is as simple as:
npx wrangler deploy

More terminology

  • Wrangler – Cloudflare’s CLI and local development environment. It comes pre‑installed with the framework template.

The Alternative to Hyperdrive

You could build an app that connects directly to the primary database for writes and to replicas for reads. While feasible, you would lose Hyperdrive’s benefits:

  • Connection pooling & reuse
  • Query‑response caching

Hyperdrive gives you a highly optimized database connection without having to implement those features yourself.


Multi‑Environment Setup

When building, it’s tempting to use defaults everywhere, but planning for multiple environments now avoids surprises later.

  1. Create a database branch in PlanetScale (via dashboard or CLI).
  2. Configure the connection string in wrangler.jsonc and add an env block:
{
  // ... other settings
  "env": {
    "development": {
      "hyperdrive": {
        "binding": "HYPERDRIVE_PLANETSCALE",
        // Development branch database
        "id": "84c4..."
      }
    }
  }
}
  1. Target the environment in your local dev server by setting the CLOUDFLARE_ENV variable:
{
  "scripts": {
    "dev": "CLOUDFLARE_ENV=development react-router dev",
    // ... other scripts
  }
}

Now:

  • The deployed Worker uses the main‑branch (production) database.
  • Your local development points at the development branch.

Step 2: Real‑time with WebSockets

Our application would break if the latest data weren’t always rendered. The business logic must ensure, at the database level, that an option purchase won’t proceed if the price the user sees is no longer valid at write time.

Because option prices can change rapidly, the freshest data must be pushed to browsers. This is where we configure a Durable Object and Cloudflare WebSockets.

Flow

  1. The Worker receives a transaction request and writes it to the database via Hyperdrive.
  2. When the transaction completes, the Worker pings the Durable Object through the WebSocket connection.
  3. The Durable Object fans out the update to all connected browsers.

Reliability Boundaries

LayerAuthorityRole
Postgres (PlanetScale)✅ Source of truthPersists all writes and serves queries
WebSockets❌ Not authoritativeLow‑latency notification channel
  • WebSocket messages can be delayed or dropped due to normal network behavior.
  • Database writes are durable.

Contract for clients: “Updates are immediate most of the time, and eventually correct all of the time.”

We use WebSockets for fast notifications only; the PlanetScale Postgres database remains the ultimate source of truth.


What We Intentionally Did Not Build (Yet)

To keep this guide focused on core principles, several production‑hardening layers were omitted:

FeatureDescriptionReason for omission
Replay on reconnectA reconnecting client could request events since a known cursor.Skipped for simplicity.
Queue‑backed fan‑outA queue improves durability and retries between write completion and broadcast.Avoided extra moving parts; Cloudflare offers a Queueing service if needed.
Polling reconciliationPeriodic polling catches any missed WebSocket updates.Mentioned but not implemented in the demo.

Each of these can make the system more resilient, but they also add operational complexity. Feel free to add them as you evolve the demo into a production‑ready application.

Complexity, and for this demo I chose to show the fastest path to a working real‑time architecture first.


Step 3: Increasing Load

We now have a working application with support for:

  • Multiple environments
  • Transactions
  • Real‑time updates

But we’re not building a toy – we want to prove this application can handle some scale: many users, a lot of transactions, and many markets.

Load simulation

  1. Seed script – creates fake users and markets, then fans out a large volume of initial transactions across those markets.
  2. Start Trading button – enables a client‑side simulator that continuously posts trades at a fixed cadence to random open markets.
    • Each request carries expected price/version data and slippage tolerance, so the backend can reject stale quotes.
    • Successful writes are immediately broadcast over WebSockets to every connected browser.

This isn’t a replacement for faking traffic from around the world, but it gives a good sense of creating many transactions in one tab while another tab receives the same live updates. Because of our real‑time configuration, the user that sends the transaction gets feedback faster than listeners‑only users – a small, acceptable trade‑off for this demo. See the earlier notes about making real‑time more robust through queues and polling.


Monitoring PlanetScale Performance

Cloudflare Hyperdrive makes handling connections and requests fast and easy, but there’s still plenty we can do on the PlanetScale side to improve performance.

  • Query Insights – helps you understand how your database performs under load. After simulating traffic, you may see insights for query improvements.
    • Access these insights from the PlanetScale dashboard or the CLI.
  • PlanetScale MCP server – you can ask your LLM to read insights data and automatically suggest or apply improvements (e.g., creating indexes).

Implementing Database Best Practices

Your application likely contains a lot of AI‑authored code. That doesn’t mean it has to be bad.

  • PlanetScale offers a package of agent skills to train your LLM in best practices for data structures and query writing.
  • Make it a habit to routinely audit your application against these skills before it becomes a runaway success.

Increasing Capacity

If your application overwhelms the current cluster size, you can resize at any time:

  • Via the PlanetScale dashboard or CLI.
  • Options: increase CPU, memory, storage, or add more replicas.

You can get started with Cloudflare Workers, WebSockets, Durable Objects, and Hyperdrive for free. See their documentation for resource limits and upgrade options.


Sharding Durable Objects

Much of this demonstration focuses on global distribution, yet it still relies on a single Durable Object to send WebSocket updates to all users.

  • Cloudflare’s documentation recommends horizontal scaling of Durable Objects—sharding with a key—if you approach resource limits.

Conclusion

This demo shows how to build a real‑time application with Cloudflare and PlanetScale. It covers:

  • Connecting to the database
  • Setting up real‑time updates
  • Simulating load

It also highlights best practices such as:

  • Using a Durable Object to coordinate real‑time updates
  • Broadcasting updates via WebSockets to all connected browsers

You may need to adjust the approaches for your own application and add features to make it even more robust. Nonetheless, the time to a fairly complex, sound proof‑of‑concept has never been lower, and the stack is ready to scale.

0 views
Back to Blog

Related posts

Read more »

Apex B. OpenClaw, Local Embeddings.

Local Embeddings para Private Memory Search Por default, el memory search de OpenClaw envía texto a un embedding API externo típicamente Anthropic u OpenAI par...