hardPerformanceNext.js
The connection exhaustion
A developer asked an AI assistant to add a database query to a Next.js API route. The suggested code works fine in local testing, but under real traffic the app starts throwing 'too many connections' errors and the database eventually stops responding.
route.ts
import { Client } from 'pg';
export async function GET(request: Request) {
const client = new Client({ connectionString: process.env.DATABASE_URL });
await client.connect();
const result = await client.query('SELECT * FROM products LIMIT 20');
return Response.json(result.rows);
}Why does this route work fine in local testing but crash the database under real traffic?
A new client connects to the database on every request and is never explicitly closed or reused — under concurrent traffic this quickly exhausts the database's max connection limit.
SELECT * always locks the entire products table until the request completes.
process.env.DATABASE_URL is re-read from disk on every request, adding latency but no connection issue.
Response.json() keeps the database connection open until the client's browser tab closes.