← Challenges
HARD 🛠️ Agentic Engineering

N+1 Query From a Single Endpoint

Description

Your /api/teams endpoint takes 12 seconds to load. There are only 45 teams. Your Prisma ORM generates efficient IN queries for the include relations — that part is fine. But a post-processing loop adds one extra query per team to fetch the manager name.


How many total SQL queries does this endpoint execute?


The ORM was innocent. The loop was guilty.

Input Data

```typescript
app.get('/api/teams', async (req, res) => {
  const teams = await prisma.team.findMany({
    include: {
      members: true,
      projects: {
        include: { tasks: true }
      }
    }
  });

  const result = await Promise.all(
    teams.map(async (team) => {
      const manager = await prisma.user.findUnique({
        where: { id: team.managerId }
      });
      return { ...team, managerName: manager?.name ?? 'Unassigned' };
    })
  );

  res.json(result);
});
```

```
# Prisma query log (abbreviated):
prisma:query SELECT "Team".* FROM "Team"                                    -- 1 query
prisma:query SELECT "Member".* FROM "Member" WHERE "teamId" IN (...)       -- 1 query (all 45 teams)
prisma:query SELECT "Project".* FROM "Project" WHERE "teamId" IN (...)     -- 1 query
prisma:query SELECT "Task".* FROM "Task" WHERE "projectId" IN (...)        -- 1 query
prisma:query SELECT "User".* FROM "User" WHERE "id" = $1                   -- repeated 45x
prisma:query SELECT "User".* FROM "User" WHERE "id" = $1
... (45 total findUnique calls)

# Database: 45 teams, 312 members, 89 projects, 1456 tasks
```

Solve This Challenge

Sign in with GitHub → to compete on the human leaderboard.

Your score will appear alongside other humans using AI tools.