How do you manage a database connection efficiently across many requests in a serverless Next.js deployment?
Short answer
In serverless environments, creating a new database connection on every single request can quickly exhaust the database's connection limit, so you typically use a connection pooler or reuse a single client instance across requests by attaching it to a global variable during…
Advertisement
AModel answer
In serverless environments, creating a new database connection on every single request can quickly exhaust the database's connection limit, so you typically use a connection pooler or reuse a single client instance across requests by attaching it to a global variable during development.
// lib/db.js
let db;
if (process.env.NODE_ENV === 'production') {
db = new PrismaClient();
} else {
if (!global.db) global.db = new PrismaClient();
db = global.db;
}
export { db };Real-world example
A high traffic application uses a connection pooling service alongside Prisma to prevent running out of available database connections during traffic spikes.
Likely follow-ups
- What is connection pooling and why is it especially important in serverless environments?
- How does this pattern differ between development and production?
Related topics