Using one drizzle connection per request (Cloudflare + postgres)

When connecting to Drizzle postgres (Neon) through a cloudflare worker. I always get this error on first load.

Error: Cannot perform I/O on behalf of a different request. I/O objects (such as streams, request/response bodies, and others) created in the context of one request handler cannot be accessed from a different request's handler. This is a limitation of Cloudflare Workers which allows us to improve overall performance.


I think it's due to the db being shared between requests.

export const db = 
  drizzle({
    schema: { ...schema },
    connection: {
      url: process.env.DATABASE_URL,
      ssl: true,
    },
  });


What are some ideas to have one instance per worker?

My workaround is exporting this, but this means every single call to db.xxxx() will call the drizzle function.
Will this create a bunch of connections?
export const db = (() =>
  drizzle({
    schema: { ...schema },
    connection: {
      url: process.env.DATABASE_URL,
      ssl: true,
    },
  }))();
Was this page helpful?