Skip to main content
Menu
Challenges/The Connection Pool That Never Releases
// challenge_CO

The Connection Pool That Never Releases

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

mediumDatabaseNode.jsPerformance5-10 min
Attempts
1,089
Solved
42%
Avg time
7min
Published
2024-03-01
// the code

Here's what passed code review.

A standard pattern. Nothing in this code is obviously wrong. It works perfectly in dev. It works perfectly in staging. It even works in production — for a while.

queries.jsjavascript
const { Pool } = require('pg');

const pool = new Pool({
  max: 20,
  connectionTimeoutMillis: 5000,
});

async function getOrdersByUser(userId) {
  const client = await pool.connect();

  try {
    const orders = await client.query(
      'SELECT * FROM orders WHERE user_id = $1',
      [userId]
    );

    const enrichedOrders = await Promise.all(
      orders.rows.map(async (order) => {
        const items = await client.query(
          'SELECT * FROM order_items WHERE order_id = $1',
          [order.id]
        );
        return { ...order, items: items.rows };
      })
    );

    return enrichedOrders;
  } catch (error) {
    console.error('Query failed:', error);
    throw error;
  }
}

// This function will exhaust your connection pool.
// The bug is subtle but devastating.
// Can you spot it?
// stuck? progressive hints

Reveal hints one at a time.

Each hint nudges you closer without giving it away. Use as many as you need.

hint_01Start here →+
What happens to the connection after the function completes?
hint_02Need another nudge?+
Look at what's missing from the try/catch block.
hint_03Need another nudge?+
The connection is never returned to the pool.
// submit your guess
// solution lands in your inbox

Want more code challenges? Subscribe.

New challenge every two weeks. Production bugs that passed review. ~5 min reads.