Bird
Raised Fist0
NextJSframework~20 mins

Connection pooling for serverless in NextJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Serverless Connection Pooling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why use connection pooling in serverless Next.js apps?

In serverless environments like Next.js API routes, why is connection pooling important?

AIt reduces the number of database connections by reusing existing ones, improving performance and avoiding connection limits.
BIt creates a new database connection for every request to ensure data freshness.
CIt caches database queries on the client side to reduce server load.
DIt automatically scales the database server horizontally without configuration.
Attempts:
2 left
💡 Hint

Think about how serverless functions start and stop frequently and how databases limit connections.

component_behavior
intermediate
2:00remaining
What happens when you don't use connection pooling in Next.js API routes?

Consider a Next.js API route that opens a new database connection on every request without pooling. What is the most likely outcome under heavy traffic?

AThe database will reject all queries due to slow network latency.
BThe serverless functions will cache connections automatically, so no problem occurs.
CThe app will run smoothly with no issues because serverless functions are stateless.
DThe database will quickly reach its maximum connection limit, causing errors and failed requests.
Attempts:
2 left
💡 Hint

Think about how many connections a database can handle and what happens if too many open at once.

📝 Syntax
advanced
2:00remaining
Identify the correct way to implement connection pooling in a Next.js API route

Which code snippet correctly implements connection pooling using a global variable to reuse a single database client instance in Next.js API routes?

NextJS
import { Client } from 'pg';

let client;

export default async function handler(req, res) {
  if (!client) {
    client = new Client({ connectionString: process.env.DATABASE_URL });
    await client.connect();
  }
  const result = await client.query('SELECT NOW()');
  res.status(200).json({ time: result.rows[0].now });
}
AThe code creates a new client on every request without reusing, causing connection overload.
BThe code correctly reuses the client connection across requests by storing it in a global variable.
CThe code uses a client but never calls connect(), so queries will fail.
DThe code closes the client after each request, preventing reuse.
Attempts:
2 left
💡 Hint

Look for where the client is created and if it is reused across requests.

🔧 Debug
advanced
2:00remaining
Why does this Next.js API route cause 'too many clients' error?

Given this code, why might the app throw a 'too many clients' error under load?

NextJS
import { Pool } from 'pg';

export default async function handler(req, res) {
  const pool = new Pool({ connectionString: process.env.DATABASE_URL });
  const client = await pool.connect();
  const result = await client.query('SELECT NOW()');
  client.release();
  res.status(200).json({ time: result.rows[0].now });
}
AThe environment variable DATABASE_URL is missing, causing connection failures.
BThe query syntax is incorrect, causing the database to reject connections.
CA new Pool instance is created on every request, so connections are not reused, causing overload.
DThe client is never released back to the pool, causing connection leaks.
Attempts:
2 left
💡 Hint

Check where the Pool is created and how often.

state_output
expert
2:00remaining
What is the output of this Next.js API route with connection pooling under concurrent requests?

Consider this Next.js API route code. What will be the output when 3 requests arrive almost simultaneously?

NextJS
import { Pool } from 'pg';

const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 2 });

export default async function handler(req, res) {
  const client = await pool.connect();
  const result = await client.query('SELECT pg_sleep(1); SELECT NOW()');
  client.release();
  res.status(200).json({ time: result[1].rows[0].now });
}
ATwo requests will complete after about 1 second; the third will wait for a connection and complete after about 2 seconds.
BAll three requests will complete simultaneously after 1 second because the pool allows unlimited connections.
CThe third request will fail immediately with a connection error because the pool max is 2.
DAll requests will fail because pg_sleep is not supported in queries.
Attempts:
2 left
💡 Hint

Think about the pool max connections and how pg_sleep delays queries.

Practice

(1/5)
1. What is the main benefit of using connection pooling in a Next.js serverless app?
easy
A. It automatically scales the number of serverless functions.
B. It reuses database connections to improve speed and avoid connection limits.
C. It caches API responses for faster loading.
D. It encrypts database connections for security.

Solution

  1. Step 1: Understand connection pooling purpose

    Connection pooling allows reusing existing database connections instead of opening new ones each time.
  2. Step 2: Identify benefits in serverless context

    This reuse improves speed and prevents hitting database connection limits common in serverless environments.
  3. Final Answer:

    It reuses database connections to improve speed and avoid connection limits. -> Option B
  4. Quick Check:

    Connection pooling = reuse connections [OK]
Hint: Pooling means reusing connections to avoid limits [OK]
Common Mistakes:
  • Confusing pooling with caching data
  • Thinking pooling scales serverless functions
  • Assuming pooling encrypts connections
2. Which code snippet correctly creates a MySQL connection pool using mysql2/promise in Next.js?
easy
A. const pool = mysql2.createPool({ host: 'localhost', user: 'root', database: 'test' }).promise();
B. const pool = mysql2.promise.createPool({ host: 'localhost', user: 'root', database: 'test' });
C. const pool = mysql.createPool({ host: 'localhost', user: 'root', database: 'test' });
D. const pool = mysql2/promise.createPool({ host: 'localhost', user: 'root', database: 'test' });

Solution

  1. Step 1: Recall mysql2/promise usage

    When importing mysql from 'mysql2/promise', mysql.createPool() directly creates a promise-based pool.
  2. Step 2: Match correct syntax

    const pool = mysql.createPool({ host: 'localhost', user: 'root', database: 'test' }); correctly uses the mysql2/promise import.
  3. Final Answer:

    const pool = mysql.createPool({ host: 'localhost', user: 'root', database: 'test' }); -> Option C
  4. Quick Check:

    mysql2/promise + mysql.createPool() = correct syntax [OK]
Hint: mysql from 'mysql2/promise'; mysql.createPool() [OK]
Common Mistakes:
  • Trying to call createPool directly on mysql2/promise import
  • Missing .promise() for async support
  • Using wrong import or syntax
3. Given this Next.js API handler using a PostgreSQL pool, what will be the output if the database connection fails?
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' });
  }
}
medium
A. Returns JSON with error message 'Database connection failed'.
B. Returns empty JSON object {}.
C. Throws an unhandled exception crashing the server.
D. Returns JSON with current time from database.

Solution

  1. Step 1: Analyze try-catch behavior

    If pool.connect() fails, the code jumps to the catch block.
  2. Step 2: Check catch block response

    The catch block sends a 500 status with JSON error message 'Database connection failed'.
  3. Final Answer:

    Returns JSON with error message 'Database connection failed'. -> Option A
  4. Quick Check:

    Error caught = JSON error response [OK]
Hint: Errors in try send JSON error response [OK]
Common Mistakes:
  • Assuming unhandled exception crashes server
  • Expecting successful time JSON on failure
  • Thinking empty JSON is returned
4. Identify the bug in this Next.js serverless function using MySQL connection pooling:
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);
}
medium
A. Missing connection.release() after query.
B. Using getConnection() instead of connect().
C. Pool should be created inside the handler.
D. Query syntax is incorrect.

Solution

  1. Step 1: Check connection usage

    The code gets a connection from the pool but never releases it back.
  2. Step 2: Understand pooling best practice

    Connections must be released with connection.release() to avoid leaks and exhaustion.
  3. Final Answer:

    Missing connection.release() after query. -> Option A
  4. Quick Check:

    Always release pooled connections [OK]
Hint: Always release connections after use [OK]
Common Mistakes:
  • Forgetting to release connections
  • Thinking getConnection() is invalid
  • Creating pool inside handler causing overhead
5. You want to optimize a Next.js serverless app connecting to PostgreSQL with connection pooling. Which approach best prevents exhausting database connections during high traffic?
hard
A. Close the pool after each query to free resources.
B. Create a new pool inside each API handler call.
C. Use a new client connection for every query without pooling.
D. Create a single global pool instance reused across requests.

Solution

  1. Step 1: Understand serverless connection challenges

    Serverless functions can run many instances, so creating many pools wastes connections.
  2. Step 2: Choose pooling strategy

    Creating a single global pool reused by all handlers limits total connections and improves reuse.
  3. Final Answer:

    Create a single global pool instance reused across requests. -> Option D
  4. Quick Check:

    Global pool reuse prevents connection exhaustion [OK]
Hint: Use one global pool, not new pools per request [OK]
Common Mistakes:
  • Making new pool each request causing connection overload
  • Not using pooling at all
  • Closing pool too early causing errors