Comparison & Data Fetching Mechanics:
1. GraphQL vs REST:
- REST: Architectural style using standard HTTP verbs and fixed endpoint URLs (/users/1/posts). Can suffer from Over-fetching (downloading unused fields) or Under-fetching (requiring multiple waterfall requests to assemble data).
- GraphQL: Query language and server runtime where clients send declarative queries requesting the exact fields needed in a single round-trip over a single /graphql endpoint.
- Trade-offs: GraphQL adds server parsing complexity, complicates standard HTTP edge caching (requests are POSTs), and requires custom rate limiting.
2. The N+1 Query Problem:
- Occurs when resolving nested relationships. Example: Fetching 50 users and their recent posts. A naive resolver executes 1 query for the users, and then N (50) separate queries for each user's posts, resulting in 51 database round-trips.
3. Solution: DataLoader Pattern:
- DataLoader batches and deduplicates database requests within a single tick of the event loop. Instead of 50 individual queries, DataLoader collects all user IDs and executes one single batch query: SELECT * FROM posts WHERE user_id IN (1, 2, ... 50).