N
Neon12mo ago
sensitive-blue

With the serverless driver adapter, is a singleton pattern still necessary for database connection?

With the Neon serverless driver adapter, is a singleton pattern still necessary for database connections? For context, I noticed that many Next.js + Prisma examples use a pattern like this:
const DatabaseSingleton = () => {
const neon = new Pool({ connectionString: vars.DATABASE_URL });
const adapter = new PrismaNeon(neon);
const database = new Prisma({ adapter });
return database
}

declare const globalThis: {
__database: ReturnType<typeof DatabaseSingleton>;
} & typeof global;

export const database = globalThis.__database ?? DatabaseSingleton();

if (process.env.NODE_ENV !== 'production') globalThis.__database = database;
const DatabaseSingleton = () => {
const neon = new Pool({ connectionString: vars.DATABASE_URL });
const adapter = new PrismaNeon(neon);
const database = new Prisma({ adapter });
return database
}

declare const globalThis: {
__database: ReturnType<typeof DatabaseSingleton>;
} & typeof global;

export const database = globalThis.__database ?? DatabaseSingleton();

if (process.env.NODE_ENV !== 'production') globalThis.__database = database;
In serverless or edge environments, where each request typically runs in isolation, does this pattern still provide any benefit with neon serverless http/ws driver, or is it effectively redundant?
4 Replies
stormy-gold
stormy-gold12mo ago
What's your use case of using Singleton? (trying to understand)
absent-sapphire
absent-sapphire12mo ago
Typically, singleton for db object is used for connection cache/pooling to you efficiently reuse the connections Strictly speaking, that connection reuse benefit is not seen in our http based serverless driver, as the connection cache is handled by nodejs and not by your app. There might be other caches to consider though (type information). I'm not certain, however For our websocket based driver, that connection reuse would be important. However, it does get nullified by runtimes like cloudflare where the singleton is discarded at the end of the request. This makes it easy for cloudflare to manage state at scale, but increases your latency. For that reason we heavily recommend the HTTP driver if applicable for cloudflare workers
stormy-gold
stormy-gold12mo ago
I see, in such cases (where it gets nullified) @Michael Li you can use an implementation like as in https://github.com/neondatabase/examples/blob/main/with-nextjs-prisma-edge/lib/prisma.server.ts.
sensitive-blue
sensitive-blueOP12mo ago
Thank you! I didn't know Neon maintains a list of examples. That really helps!

Did you find this page helpful?