Performance: Connection pooling for serverless
HIGH IMPACT
This affects backend response time and serverless function cold start latency by managing database connections efficiently.
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 |