The N+1 Problem

アプリ開発者が最も踏みやすい地雷。「動くけど遅い」原因のNo.1。

N+1 Problem
1回の親クエリの後に、N回の子クエリが走ってしまう問題。パフォーマンス低下の主犯。

The Problem

sequenceDiagram
    participant App
    participant DB
    
    Note over App, DB: The "N+1" Pattern (Bad)
    App->>DB: 1. SELECT * FROM Users (Get 10 users)
    DB-->>App: Returns 10 users
    
    loop For each user (10 times)
        App->>DB: SELECT * FROM Posts WHERE user_id = ?
        DB-->>App: Returns posts
    end
    Note right of DB: Total Queries: 1 + 10 = 11

The Solution (Eager Loading)

sequenceDiagram
    participant App
    participant DB
    
    Note over App, DB: Eager Loading / JOIN (Good)
    App->>DB: SELECT * FROM Users JOIN Posts ON ...
    DB-->>App: Returns Users WITH Posts
    Note right of DB: Total Queries: 1

How to fix in Code?

  • ORM (Prisma): include: { posts: true }
  • ORM (TypeORM): relations: ['posts']
  • Plain SQL: JOIN