Skip to main content
medium5-10 min42% solve rate

The Database Connection Leak

This query function works perfectly in testing but will bring down production.

DatabaseNode.jsPerformance

The Code

This code passed code review and works in development. But it has a bug that will cause problems in production.

queries.js
1const { Pool } = require('pg');
2
3const pool = new Pool({
4 max: 20,
5 connectionTimeoutMillis: 5000,
6});
7
8async function getOrdersByUser(userId) {
9 const client = await pool.connect();
10
11 try {
12 const orders = await client.query(
13 'SELECT * FROM orders WHERE user_id = $1',
14 [userId]
15 );
16
17 const enrichedOrders = await Promise.all(
18 orders.rows.map(async (order) => {
19 const items = await client.query(
20 'SELECT * FROM order_items WHERE order_id = $1',
21 [order.id]
22 );
23 return { ...order, items: items.rows };
24 })
25 );
26
27 return enrichedOrders;
28 } catch (error) {
29 console.error('Query failed:', error);
30 throw error;
31 }
32}
33
34// This function will exhaust your connection pool.
35// The bug is subtle but devastating.
36// Can you spot it?

Need a Hint?

0 of 3 revealed
Hint 1 locked
Hint 2 locked
Hint 3 locked

Ready for the Solution?

Enter your email to get the full solution with explanation, the fix, and why this bug is so common.