(N + 1) query problem
(N + 1) query problem occurs in backend systems while working with databases. It happens when the query count will not be constant, and might change depending on the several factors.
Take a look at the following example:
override suspend fun getAvailableOrders(): List<DriverOrderResponse> = dbQuery {
Orders.select { Orders.assignedDriverId.isNull() }
.orderBy(Orders.createdAt to SortOrder.DESC)
.map { row ->
DriverOrderResponse.from(
row = row,
restaurant = restaurantsRepository.getRestaurantById(row[Orders.restaurantId])!!,
client = clientsRepository.getClient(row[Orders.clientId])!!,
orderedFoods = OrderedFoods.select { OrderedFoods.orderId eq row[Orders.id] }
.map { OrderedFoodResponse.from(it) },
driver = null
)
}
}
Well, you might say "What's wrong here?". Here, we are fetching all orders from Orders table. sorting it descending by date. And mapping the row into DriverOrderResponse. The problem is when we are mapping, for each order we are making another database queries to fetch client, restaurant and food details. That means, if we have n orders. The query count will be 3n if not more.
The issue above is called (N+1) query issue in technical terms. We could have done better. Take a look at the following refactor below:
override suspend fun getAvailableOrders(): List<DriverOrderResponse> = dbQuery {
val joined = Orders
.leftJoin(Restaurants, { Orders.restaurantId }, { Restaurants.id })
.leftJoin(Clients, { Orders.clientId }, { Clients.id })
.select { Orders.assignedDriverId.isNull() }
.orderBy(Orders.createdAt to SortOrder.DESC)
.map { it }
val orderIds = joined.map { it[Orders.id] }
val foodsByOrder = OrderedFoods
.select { OrderedFoods.orderId inList orderIds }
.groupBy { it[OrderedFoods.orderId] }
joined.map { row ->
DriverOrderResponse.from(
row = row,
restaurant = OrderRestaurantResponse.from(row),
client = ClientResponse.from(row),
orderedFoods = foodsByOrder[row[Orders.id]]?.map { OrderedFoodResponse.from(it) } ?: emptyList(),
driver = null
)
}
}
In this refactored example, we are joining tables and querying orders. That is 1st query. After that we are querying foods, that's 2nd query. No matter of the number of orders, query count will be constant.
So, we have fixed (N+1) query issue. Do not make this mistake ! :)