Connection pooling helps your serverless app reuse database connections. This makes your app faster and avoids errors from opening too many connections.
Connection pooling for serverless in NextJS
Start learning this pattern below
Jump into concepts and practice - no test required
import { createPool } from 'mysql2/promise'; const pool = createPool({ host: 'localhost', user: 'user', password: 'password', database: 'mydb', waitForConnections: true, connectionLimit: 10, queueLimit: 0 }); export default pool;
This example uses mysql2/promise for MySQL connection pooling.
Adjust connectionLimit to control max simultaneous connections.
import { createPool } from 'mysql2/promise'; const pool = createPool({ host: 'db.example.com', user: 'admin', password: 'secret', database: 'appdb', waitForConnections: true, connectionLimit: 5, queueLimit: 10 });
import { Pool } from 'pg'; const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 20, idleTimeoutMillis: 30000 });
This Next.js API route uses a connection pool to query the current time from the database. It reuses connections efficiently for each request.
import { createPool } from 'mysql2/promise'; const pool = createPool({ host: 'localhost', user: 'root', password: 'password', database: 'testdb', waitForConnections: true, connectionLimit: 5, queueLimit: 0 }); export default async function handler(req, res) { try { const [rows] = await pool.query('SELECT NOW() AS now'); res.status(200).json({ time: rows[0].now }); } catch (error) { res.status(500).json({ error: 'Database query failed' }); } }
Serverless functions can start and stop often, so connection pooling helps avoid opening too many new connections.
Always close or release connections if you manage them manually, but pools handle this automatically.
Use environment variables to keep database credentials safe and configurable.
Connection pooling lets serverless apps reuse database connections.
This improves speed and prevents connection limits errors.
Use libraries like mysql2/promise or pg with pooling options.
Practice
Solution
Step 1: Understand connection pooling purpose
Connection pooling allows reusing existing database connections instead of opening new ones each time.Step 2: Identify benefits in serverless context
This reuse improves speed and prevents hitting database connection limits common in serverless environments.Final Answer:
It reuses database connections to improve speed and avoid connection limits. -> Option BQuick Check:
Connection pooling = reuse connections [OK]
- Confusing pooling with caching data
- Thinking pooling scales serverless functions
- Assuming pooling encrypts connections
mysql2/promise in Next.js?Solution
Step 1: Recall mysql2/promise usage
When importingmysqlfrom'mysql2/promise',mysql.createPool()directly creates a promise-based pool.Step 2: Match correct syntax
const pool = mysql.createPool({ host: 'localhost', user: 'root', database: 'test' });correctly uses the mysql2/promise import.Final Answer:
const pool = mysql.createPool({ host: 'localhost', user: 'root', database: 'test' }); -> Option CQuick Check:
mysql2/promise + mysql.createPool() = correct syntax [OK]
- Trying to call createPool directly on mysql2/promise import
- Missing .promise() for async support
- Using wrong import or syntax
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' });
}
}Solution
Step 1: Analyze try-catch behavior
Ifpool.connect()fails, the code jumps to the catch block.Step 2: Check catch block response
The catch block sends a 500 status with JSON error message 'Database connection failed'.Final Answer:
Returns JSON with error message 'Database connection failed'. -> Option AQuick Check:
Error caught = JSON error response [OK]
- Assuming unhandled exception crashes server
- Expecting successful time JSON on failure
- Thinking empty JSON is returned
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);
}Solution
Step 1: Check connection usage
The code gets a connection from the pool but never releases it back.Step 2: Understand pooling best practice
Connections must be released withconnection.release()to avoid leaks and exhaustion.Final Answer:
Missing connection.release() after query. -> Option AQuick Check:
Always release pooled connections [OK]
- Forgetting to release connections
- Thinking getConnection() is invalid
- Creating pool inside handler causing overhead
Solution
Step 1: Understand serverless connection challenges
Serverless functions can run many instances, so creating many pools wastes connections.Step 2: Choose pooling strategy
Creating a single global pool reused by all handlers limits total connections and improves reuse.Final Answer:
Create a single global pool instance reused across requests. -> Option DQuick Check:
Global pool reuse prevents connection exhaustion [OK]
- Making new pool each request causing connection overload
- Not using pooling at all
- Closing pool too early causing errors
