Hyperdrive + Neon PostgreSQL Integration
Priority: P0 (Immediate)
What is Hyperdrive?
Hyperdrive accelerates queries from Cloudflare Workers to existing PostgreSQL databases by providing:
- **Global connection pooling** -- maintains persistent connections to your DB
- **Query result caching** -- sub-5ms latency for repeated queries
- **Network optimization** -- routes over Cloudflare's backbone instead of public internet
\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
| Before | After |
|---|---|
| Worker → Neon (new TCP + TLS per request) | Worker → Hyperdrive (pooled, cached) |
| ~50-200ms per query (cold) | ~1-5ms for cached queries |
| Connection exhaustion under load | Hyperdrive manages pool (5-100 connections) |
| No cross-request caching | Default-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
- **Enable** for: tenant config, permissions, product catalogs, site settings
- **Disable** for: order creation, real-time inventory, user sessions
Integration Points
Existing Workers
| Worker | Current DB Access | Hyperdrive Benefit |
|---|---|---|
| chat-worker | Direct Neon (if any) | Pooled connections, cached user lookups |
| rate-limit-worker | Durable Objects (no DB) | N/A -- already uses DO storage |
| gaming-worker | Durable Objects + possible DB | Cache leaderboard metadata |
| bookings-worker | Likely DB for availability | Cache 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
| Driver | Version | Notes |
|---|---|---|
| `pg` (node-postgres) | v8.16.3+ | **Recommended** -- best caching compat |
| `postgres` (postgres.js) | v3.4.5+ | Alternative |
| Drizzle ORM | v0.26.2+ | If switching from Prisma in Workers |
| Kysely | v0.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
| Metric | Free | Paid |
|---|---|---|
| Hyperdrive configs | Available | Available |
| Origin connections | ~20 | ~100 (soft, can exceed) |
| Client connections | Unlimited | Unlimited |
| Cache response size | 50 MB max | 50 MB max |
| Query timeout | Configurable | Configurable |
Monitoring
Hyperdrive connections are visible in Neon's \1:
SELECT * FROM pg_stat_activity
WHERE application_name = 'Cloudflare Hyperdrive';
Risks & Mitigations
| Risk | Mitigation |
|---|---|
| Cache staleness | Configure 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 migrations | Hyperdrive is transparent to DDL; no impact on `prisma db push` |
Estimated Impact
- **Latency**: 50-200ms → 1-5ms for cached queries (10-100x improvement)
- **Connection usage**: Reduce from N connections/worker to pooled ~20-100
- **Cost**: $0 additional (included in Workers plan)
- **Effort**: 1-2 days for existing Workers, 0 effort for new Workers (just configure binding)