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:
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•12mo ago
What's your use case of using Singleton?
(trying to understand)
absent-sapphire•12mo 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•12mo 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-blueOP•12mo ago
Thank you! I didn't know Neon maintains a list of examples. That really helps!