Database & Performance

Code Review: N+1 Database Queries

mediumCode ReviewJS / TS

Problem Statement

Review the following user profile enrichment service. Identify performance issues (specifically N+1 database query patterns), explain the architectural impact on database connection pools, and propose an optimized batching/joining solution.

Code under review

JAVASCRIPT• handler.js
// Service handler fetching active user profiles and their recent orders
async function getUserDashboardData(userIds) {
  const users = [];

  for (const id of userIds) {
    const user = await db.query('SELECT * FROM users WHERE id = $1', [id]);
    const orders = await db.query('SELECT * FROM orders WHERE user_id = $1 ORDER BY created_at DESC LIMIT 5', [id]);
    const settings = await db.query('SELECT * FROM user_settings WHERE user_id = $1', [id]);

    users.push({
      ...user,
      recentOrders: orders,
      settings: settings[0] || {}
    });
  }

  return users;
}

Read only. Write down what you would flag below, then compare with the reference notes.

JavaScript & TypeScript versions included
Run this as a live interview

Practice solo

Write down what you would flag in this code, then compare it with the reference notes.

Write your findings first, then check yourself against the notes.

Get new interview exercises

Practice problems and review drills, sent when we publish new ones. No spam.

Unsubscribe anytime. We never share your address.