Skip to content
Rohan Khatua

Writing

One Global Postgres Pool Took My Site Down on Cloudflare Workers

5 min readweb

I moved my Hacker News reader, hn.rohankhatua.dev, from Vercel to Cloudflare Workers in November. The migration itself went well: smoke tests passed, the ingest job wrote rows through the new database path, and I merged the PRs. Minutes later the site started returning Cloudflare error 1101 on / and /best.

The cause was one line of thinking I'd carried over from Node: create a Postgres pool once, at module scope, and reuse it forever. On Workers that pattern doesn't just perform badly. It breaks.

The setup

The app is Next.js deployed with OpenNext. Data goes through Prisma with the @prisma/adapter-pg driver adapter, then through Cloudflare Hyperdrive to a Postgres database on Neon. Feed pages like / and /best use ISR (revalidate = 300), so they hit the database when they regenerate.

If the database isn't reachable, the feed code falls back to fetching stories live from the Hacker News API. That fallback ended up mattering a lot.

Narrowing it down

The first useful step was finding out what was not broken. Static assets, API routes, dynamic routes and 404s all responded. Only the ISR pages hung, and once an isolate hung, later requests to it failed fast with 500s.

That pointed me at OpenNext's caching layer, so I tried the obvious things first:

  1. Upgrade the tooling. Wrangler 4.160 → 4.162 plus the latest adapter. No change.
  2. Take the cache out of the request path. I swapped the R2 incremental cache and Durable Object queue for a bare defineCloudflareConfig({}). Still 500s on repeat requests.

The second result killed the caching theory. Looking at the failures again, every page that hung was a page that queried the database. Nothing else ever hung.

So I added aggressive pool timeouts, hoping a stuck socket would at least fail instead of hanging forever. The 500s stopped, but now roughly every third request took about 36 seconds, while still returning 200.

The tail told me everything

At that point I stopped guessing and ran wrangler tail against the live Worker while hitting the slow pages. Three things showed up together:

  • prisma:error Query read timeout
  • A runtime warning: "A promise was resolved or rejected from a different request context… continuations canceled"
  • Too many subrequests

That chain explains the whole outage:

  1. The pg pool lived on globalThis. A socket opened while handling request A was handed to request B. The Workers runtime doesn't allow I/O objects to cross request contexts, so B's query never completed and Prisma eventually timed out.
  2. On a database timeout, the app fell back to the live Hacker News feed. That path enriches each story with an excerpt, which is around 30 outbound fetches per render. Workers cap subrequests at 50 per invocation on the free plan, so slow renders turned into failed ones.
  3. Isolates that hit this state wedged, and Cloudflare served 1101s.

OpenNext's own database guide says this almost word for word: don't create a global client, because reusing one connection across requests "is not allowed in Cloudflare Workers and will cause subsequent requests to fail." I just hadn't read it before migrating. Upgrading packages was never going to help, because the bug was in my code, not the platform.

The fix: a client per request

The fix was to build the Prisma client per request, dedupe it within a request with React's cache(), and make every pooled socket single-use:

typescript
const POOL_CONFIG = {
  max: 3,
  maxUses: 1, // never reuse a socket
  connectionTimeoutMillis: 5_000,
  idleTimeoutMillis: 10_000,
  query_timeout: 30_000,
  statement_timeout: 30_000,
} as const;

export const getDb = cache((): PrismaClient => {
  const connectionString = hyperdriveConnectionString();
  if (connectionString) return newClient(connectionString);
  nodeDevClient ??= newClient(process.env.DATABASE_URL ?? "");
  return nodeDevClient;
});

export const prisma = new Proxy({} as PrismaClient, {
  get(_target, prop) {
    const client = getDb();
    const value = Reflect.get(client as unknown as object, prop, client);
    return typeof value === "function" ? value.bind(client) : value;
  },
});

A few details I'd point out:

  • Hyperdrive does the pooling. Creating a client per request sounds expensive, but Hyperdrive keeps the real connections to Neon warm. The Worker-side pool is just a thin, short-lived wrapper.
  • The Proxy kept the diff small. About 16 call sites used prisma.something directly. The Proxy resolves the current request's client on every property access, so none of them had to change.
  • There's an async variant. ISR revalidation can run without an incoming request, so getDbAsync() covers that path. Outside Workers (next dev, CI) both fall back to a normal Node singleton.

I also added Prisma to serverExternalPackages in next.config.mjs, which the OpenNext guide requires so the generated client gets patched for workerd. I'd missed that too.

Result

After redeploying, I hit the live site in a loop:

bash
for i in 1 2 3 4 5; do
  curl -s -o /dev/null -w "GET / -> %{http_code} (%{time_total}s)\n" \
    https://hn.rohankhatua.dev/
done

All 9 requests across /, /best and /newest came back 200 in 0.8–2.3 seconds, with no 36-second outliers. Just as important, the tail showed zero Query read timeout errors, zero fallbacks to the live HN feed and zero cross-context warnings. A 200 alone wasn't proof, since the fallback path also returns 200. The fix is in PR #5.

I left the R2 incremental cache turned off for now and rely on edge s-maxage headers for repeat traffic. That's a trade-off I'll revisit.

What I'd do differently

  • Read the platform's database guide before migrating. Workers isn't "Node on someone else's server." Module scope persists across requests, but I/O objects don't. The exact rule I broke was documented.
  • Run the tail first. I spent two rounds on upgrades and cache config before looking at the logs. The logs had the answer from the start.
  • Set timeouts from day one. Without them, a stuck socket hangs the isolate. With them, it becomes an error you can see and debug.
  • Keep fallback paths cheap. My fallback was more expensive than the main path: 30 extra fetches, triggered exactly when things were already going wrong. A degraded mode should do less work, not more.

The migration also changed how I think about "global singletons are fine." On a long-lived Node server they usually are. On an isolate that serves many requests and enforces per-request I/O ownership, the safe default is to create things per request and let a service like Hyperdrive handle the pooling.