Skip to main content
This guide covers understanding N+1 query problems and how to solve them using Sonamu’s Subset and Relation features.

What is the N+1 Problem?

The N+1 problem is a performance issue where 1 main query triggers N additional queries.

Problem Example

Performance Impact:
  • 100 users = 101 queries
  • 1000 users = 1001 queries
  • Accumulated network round-trip time
  • Increased database load

Sonamu’s Solution

Sonamu automatically solves the N+1 problem through Subsets.

1. Define Subset

Define a Subset in the Entity:

2. Use Subset

Internal Operation:
  1. Fetch users (1 query)
  2. Fetch all orders with user IDs in batch (1 query)
  3. Join in memory

Subset Usage Patterns

Single Relation

Multiple Relations

Nested Relations

Manual Solution with whereIn

When Subsets are not available, you can optimize with whereIn:

DataLoader Pattern

Use the DataLoader pattern when repeated queries are needed:

Practical Examples

API Endpoint Optimization

Dashboard Data

Detecting N+1

Query Logging

Check the console after execution:
Repetitive similar queries indicate an N+1 problem!

Detection with Tests

Performance Comparison

With N+1 Problem

Optimized with Subset

Over 40x performance improvement!

Best Practices

1. Always Consider Subset First

2. Define Necessary Subsets for API Responses

3. Consider JOIN for Complex Queries

4. Monitor Queries During Development

Checklist

To prevent N+1 problems:
  • Avoid DB queries inside loops
  • Pre-load relation data with Subset
  • Use whereIn for bulk queries
  • Use JOIN for aggregations
  • Enable query logging during development
  • Verify query count with tests
  • Monitor API response times