Hyperdrive + Neon PostgreSQL Integration

Priority: P0 (Immediate)

What is Hyperdrive?

Hyperdrive accelerates queries from Cloudflare Workers to existing PostgreSQL databases by providing:

\1 (included with Workers Paid plan, no per-query charges)

Why This Matters for Company Manager

Current Pain Points

1. \1: The 4 existing Workers (chat, rate-limit, gaming, bookings) each establish new connections to Neon per request 2. \1: Serverless PostgreSQL has connection pooling limits; each Worker adds pressure 3. \1: Workers at the edge → Neon region = network round trips for every query 4. \1: Identical queries (tenant config, permissions, feature flags) hit the DB every time

What Hyperdrive Solves

BeforeAfter
Worker → Neon (new TCP + TLS per request)Worker → Hyperdrive (pooled, cached)
~50-200ms per query (cold)~1-5ms for cached queries
Connection exhaustion under loadHyperdrive manages pool (5-100 connections)
No cross-request cachingDefault-on caching for hot queries

Architecture


┌─────────────────────────────────────────┐
│ Cloudflare Edge (any PoP)                │
│                                          │
│  chat-worker ──┐                         │
│  rate-limit ───┤                         │
│  gaming ───────┤──► Hyperdrive ──► Neon  │
│  bookings ─────┤    (pool+cache)   (PG)  │
│  new-workers ──┘                         │
└─────────────────────────────────────────┘

Implementation

Step 1: Create Hyperdrive Configuration


# Get your Neon connection string from apps/app/.env (DATABASE_URL)
npx wrangler hyperdrive create company-manager-db \
  --connection-string="postgres://user:pass@ep-xxx.us-east-2.aws.neon.tech/neondb?sslmode=require"

Step 2: Configure Workers


// wrangler.jsonc (for each Worker)
{
  "compatibility_flags": ["nodejs_compat"],
  "compatibility_date": "2024-09-23",
  "hyperdrive": [
    {
      "binding": "HYPERDRIVE",
      "id": "<hyperdrive-config-id>"
    }
  ]
}

Step 3: Use in Worker Code


// In any Worker (e.g., chat-worker, gaming-worker)
import { Client } from "pg";

export default {
  async fetch(request: Request, env: Env) {
    // Hyperdrive manages the actual connection pool
    const client = new Client({
      connectionString: env.HYPERDRIVE.connectionString,
    });
    await client.connect();

    // Queries go through Hyperdrive's cache + pool
    const result = await client.query(
      "SELECT * FROM \"Tenant\" WHERE id = $1",
      [tenantId]
    );

    await client.end();
    return Response.json(result.rows);
  },
};

Step 4: Cache Configuration


# Disable caching for write-heavy paths
npx wrangler hyperdrive update company-manager-db \
  --caching-disabled=false \
  --max-age=60  # cache TTL in seconds

\1

Integration Points

Existing Workers

WorkerCurrent DB AccessHyperdrive Benefit
chat-workerDirect Neon (if any)Pooled connections, cached user lookups
rate-limit-workerDurable Objects (no DB)N/A -- already uses DO storage
gaming-workerDurable Objects + possible DBCache leaderboard metadata
bookings-workerLikely DB for availabilityCache venue/event configs

New Workers (planned)

All future Workers should use Hyperdrive as the standard database access pattern:


// Standard pattern for new Workers
const db = new Client({ connectionString: env.HYPERDRIVE.connectionString });
await db.connect();

// Multi-tenant query (ALWAYS include tenantId)
const products = await db.query(
  `SELECT id, name, price FROM "Product" WHERE "tenantId" = $1 AND active = true LIMIT 20`,
  [tenantId]
);

Next.js App Integration

The main Next.js app (apps/app) doesn't run on Workers, so Hyperdrive doesn't directly apply. However:

1. \1 could use Hyperdrive 2. \1 accessing DB could benefit 3. If migrating TRPC endpoints to Workers (future), Hyperdrive becomes the DB layer

Supported Drivers

DriverVersionNotes
`pg` (node-postgres)v8.16.3+**Recommended** -- best caching compat
`postgres` (postgres.js)v3.4.5+Alternative
Drizzle ORMv0.26.2+If switching from Prisma in Workers
Kyselyv0.26.3+Lightweight query builder

\1: Prisma itself can work with Hyperdrive if using the \1 adapter, but for Workers, a lighter driver like \1 or Drizzle is recommended.

Limits

MetricFreePaid
Hyperdrive configsAvailableAvailable
Origin connections~20~100 (soft, can exceed)
Client connectionsUnlimitedUnlimited
Cache response size50 MB max50 MB max
Query timeoutConfigurableConfigurable

Monitoring

Hyperdrive connections are visible in Neon's \1:


SELECT * FROM pg_stat_activity
WHERE application_name = 'Cloudflare Hyperdrive';

Risks & Mitigations

RiskMitigation
Cache stalenessConfigure TTL per query pattern; disable for writes
Connection mode (transaction)Hyperdrive uses transaction mode; avoid session-level state (temp tables, SET)
Neon sleep (free tier)Neon paid plan keeps connections alive; Hyperdrive handles reconnection
Schema migrationsHyperdrive is transparent to DDL; no impact on `prisma db push`

Estimated Impact