Performance: Connection pooling for serverless
This affects backend response time and serverless function cold start latency by managing database connections efficiently.
Jump into concepts and practice - no test required
import { MongoClient } from 'mongodb'; let cachedClient = null; let cachedDb = null; export default async function handler(req, res) { if (!cachedClient) { cachedClient = await MongoClient.connect(process.env.MONGO_URI); cachedDb = cachedClient.db(); } const data = await cachedDb.collection('items').find().toArray(); res.json(data); }
export default async function handler(req, res) { const client = await MongoClient.connect(process.env.MONGO_URI); const db = client.db(); const data = await db.collection('items').find().toArray(); await client.close(); res.json(data); }
| Pattern | Connection Setup | Latency Impact | Resource Usage | Verdict |
|---|---|---|---|---|
| Open/close connection per request | New connection every time | High latency (100-300ms delay) | High CPU and memory usage | [X] Bad |
| Cached connection pooling | Single connection reused | Low latency (minimal delay) | Low resource usage | [OK] Good |
mysql2/promise in Next.js?mysql from 'mysql2/promise', mysql.createPool() directly creates a promise-based pool.const pool = mysql.createPool({ host: 'localhost', user: 'root', database: 'test' }); correctly uses the mysql2/promise import.import { Pool } from 'pg';
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
export default async function handler(req, res) {
try {
const client = await pool.connect();
const result = await client.query('SELECT NOW()');
client.release();
res.status(200).json({ time: result.rows[0].now });
} catch (error) {
res.status(500).json({ error: 'Database connection failed' });
}
}pool.connect() fails, the code jumps to the catch block.import mysql from 'mysql2/promise';
const pool = mysql.createPool({ host: 'localhost', user: 'root', database: 'test' });
export default async function handler(req, res) {
const connection = await pool.getConnection();
const [rows] = await connection.query('SELECT * FROM users');
res.status(200).json(rows);
}connection.release() to avoid leaks and exhaustion.