Reducing Database Round Trips

Learn to reduce database round trips.

A database round trip is a request from the web API to the database. Database round trips are expensive. The greater the distance between the web API and the database, the more expensive the round trip is. So, we want to keep the trips from the web API to the database to a minimum in order to gain maximum performance.

We will start this section by understanding the N+1 problem and experiencing how it negatively impacts performance. We will then learn how to execute multiple queries in a single database round trip.

Understanding the N+1 problem

The N+1 problem is a classic query problem where there is a parent-child data model relationship. When data is retrieved for this model, the parent items are fetched in a query and then separate queries are executed to fetch the data for each child. So, there are Nqueries for the children and 1 additional query for the parent, hence the term N+1.

We are going to add the ability to return answers as well as questions in a GET request to the questions REST API endpoint. We are going to fall into the N+1 trap with our first implementation. Let's open our backend project in Visual Studio and carry out the following steps:

1. First, let's add an Answers property at the bottom of the QuestionGetManyResponse model:

Get hands-on with 1200+ tech skills courses.