iTranslated by AI
Do Not Reuse Prisma + PostgreSQL Instances Across Requests on Cloudflare Workers
Cloudflare Workers Limitations
In Cloudflare Workers, connections created within a Worker cannot be reused across requests. Therefore, when using external connections such as Prisma or PostgreSQL, you must create a new instance for each request. For databases that do not involve persistent connections, like D1, reusing instances is not an issue.
Example of Prisma + PostgreSQL
I conducted a verification to see what happens when a Prisma instance is reused with minimal code. You can see it in action at the link below; the first request succeeds, but the second one fails with an error. Since the Worker then crashes, the third request succeeds again. It continues to alternate between failure and success.
export * from "@prisma/adapter-pg";
import { Pool } from "pg";
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "@prisma/client";
export interface Env {
DATABASE_URL: string;
prisma: Fetcher;
}
// Errors occur when Prisma instances are used around.
let prisma: PrismaClient;
export default {
async fetch(
request: Request,
env: Env,
_ctx: ExecutionContext
): Promise<Response> {
const url = new URL(request.url);
if (url.pathname !== "/") return new Response("Not Found", { status: 404 });
if (!prisma) {
const databaseUrl = new URL(env.DATABASE_URL);
const schema = databaseUrl.searchParams.get("schema") ?? undefined;
const pool = new Pool({
connectionString: env.DATABASE_URL,
});
const adapter = new PrismaPg(pool, { schema });
prisma = new PrismaClient({ adapter });
}
await prisma.test.create({ data: {} });
const result = await prisma.test
.findMany()
.then((r) => r.map(({ id }) => id));
return new Response(JSON.stringify(result, undefined, " "), {
headers: { "content-type": "application/json" },
});
},
};
- Successful request

- Error output

Summary
When using Prisma or PostgreSQL with Cloudflare Workers, make sure to create a new instance for every request.
By the way, if you enable nodejs_compat_v2 in the compatibility_flags and install the pg-compat package, you can use pg directly on Cloudflare just as you would in a Node.js environment.
Discussion