tech/cloudflare/hyperdrive

HYPERDRIVE

Cloudflare Hyperdrive — database connection pooling for Postgres and MySQL.

production Cloudflare Workers (Paid), Postgres, MySQL
improves: tech/cloudflare

Cloudflare Hyperdrive

Hyperdrive creates a globally-distributed connection pool between Cloudflare Workers and external databases. Workers open a connection to the nearest Hyperdrive node (fast), which maintains a pool of connections to your database (amortised).

Requires: Workers Paid plan. Pricing: $0.15/GB data proxied beyond free tier.

Setup

wrangler hyperdrive create my-hyperdrive \
  --connection-string="postgresql://user:pass@db.example.com:5432/mydb"
# → prints the Hyperdrive ID

wrangler.toml

[[hyperdrive]]
binding = "DB"
id = "YOUR_HYPERDRIVE_ID"

Querying (use standard Postgres driver)

import { Pool } from 'pg';

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // Hyperdrive provides a connectionString that routes through the pool
    const pool = new Pool({ connectionString: env.DB.connectionString });

    const { rows } = await pool.query('SELECT * FROM users WHERE active = $1', [true]);
    await pool.end();

    return Response.json(rows);
  },
};

Common Gotchas

See Also