<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Evaldo Rodrigues on Medium]]></title>
        <description><![CDATA[Stories by Evaldo Rodrigues on Medium]]></description>
        <link>https://medium.com/@evaaldormj?source=rss-a3671220143e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lJwkxPHXfwqB-Sck1YQG_Q.jpeg</url>
            <title>Stories by Evaldo Rodrigues on Medium</title>
            <link>https://medium.com/@evaaldormj?source=rss-a3671220143e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 01:14:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@evaaldormj/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[N+1 Problem in GraphQL (.NET)]]></title>
            <link>https://medium.com/@evaaldormj/n-1-problem-in-graphql-net-74f5670123fc?source=rss-a3671220143e------2</link>
            <guid isPermaLink="false">https://medium.com/p/74f5670123fc</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[n-plus-1-problem]]></category>
            <category><![CDATA[greendonut]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[hot-chocolate]]></category>
            <dc:creator><![CDATA[Evaldo Rodrigues]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 15:12:14 GMT</pubDate>
            <atom:updated>2026-10-25T15:12:14.873Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, i’m going to help you to understand the N+1 problem in GraphQL and how to solve it. The implementations were done with .NET, so this article may be particularly helpful for .NET developers looking to understand this problem.</p><p>Reference Repository: <a href="https://github.com/evaaldo/Account.GraphQL">https://github.com/evaaldo/Account.GraphQL</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mlrRgC6aWSwCyTtrf33Pyw.png" /><figcaption>GraphQL Queries with and without Dataloaders</figcaption></figure><h3>What is GraphQL?</h3><p>Probably you already know a GraphQL is, but to make sure we’re all on the same page, let’s briefly go over the basics.</p><p>When fetching data from an API, you may have wanted to retrieve only some specific fields from your database. However, your REST endpoint returned you a large amount of nested information, resulting in a unnecessarly huge payload.</p><p>To solve this problem, you don’t need to create an especific REST endpoint only to retrieve that data. You can use GraphQL instead!</p><p>For example, if you only want to retrieve an account’s id and the basic information about the person who owns it, you can write a query that returns only the fields you need:</p><pre>query {<br>  accounts {<br>    id<br>    person {<br>      id<br>      name<br>      email<br>      birthdate<br>    }<br>    createdAt<br>    updatedAt<br>  }<br>}</pre><p>GraphQL allows you to fetch data however you want, eliminating the overfetch problem that you may face using REST.</p><h3>Real-World Example of the N+1 Problem</h3><p>Imagine that you’re querying an e-commerce product and its reviews, as shown in the following example:</p><pre>query {<br>  product {<br>    name<br>    price<br>    review {<br>      title<br>      description<br>      rate<br>    }<br>  }<br>}</pre><p>This query can easily fall victim to the N+1 problem.</p><p>When this GraphQL query is executed, the application may execute multiple database queries:</p><ol><li>One query fetches the products;</li><li>N additional queries fetches the reviews for each product.</li></ol><p>With 500 products, you would make 501 queries, which is highly inefficient. After understanding the N+1 problem and how to solve it, you can reduce the number of queries to two (or even one, depending on the scenario that you’re facing).</p><blockquote>Don’t worry, you’ll understand it better after the following explanation.</blockquote><h3>Understanding the N+1 Problem</h3><h4>What is the N+1 Problem</h4><p>To have a better understanding of this problem, let’s break down the previous e-commerce example.</p><p>When you make that GraphQL query, the application may execute the following database queries:</p><ol><li>First query: Fetch all products from the database.</li></ol><pre>SELECT * FROM products;</pre><p>2. N additional queries: For each product, fetch its reviews.</p><pre>SELECT * FROM reviews WHERE product_id = 1;<br>SELECT * FROM reviews WHERE product_id = 2;<br>SELECT * FROM reviews WHERE product_id = 3;<br>SELECT * FROM reviews WHERE product_id = 4;<br>...</pre><p>If there are 500 products, this results in:</p><ul><li>1 query to fetch all the products;</li><li>500 additional queries to fetch the reviews of every product;</li></ul><p>Leading to 501 queries.</p><p>In summary, the N+1 problem occurs when one initial query is followed by N additional queries for each related item.</p><h4>Impact of the N+1 Problem</h4><p>The main impact of the N+1 Problem is degraded performance:</p><ol><li><strong>High latency:</strong> As the number of queries increases, response times can also increase</li><li><strong>Innefficient resource usage:</strong> The additional queries hitting the database can create an unnecessary load, pottentially affecting other applications that rely on the same database.</li></ol><h3>How to solve the N+1 Problem</h3><p>Depending on your use case, there are differents approaches to solving the N+1 Problem. The common strategies are using dedicated SQL queries with JOINs and implementing Dataloaders.</p><h4>When You Have a Predictable Query</h4><p>If a particular query is frequently used and its data requirements are well understood, you can implement a dedicated repository query using SQL JOINs to fetch the required data in a single database round trip.</p><p>For example, suppose your frontend frequently requests the following data to render a header section:</p><pre>query {<br>  book {<br>    title<br>    description<br>    released_at<br>    author {<br>      name<br>      role<br>      birthDate<br>    }<br>  }<br>}</pre><p>Instead of resolving the book and its associated authors through separate queires, you can retrieve the required data using a single SQL query:</p><pre>SELECT<br>  B.title,<br>  B.description,<br>  B.released_at,<br>  A.name,<br>  A.role,<br>  A.birth_date<br>FROM tb_book B<br>INNER JOIN tb_author A<br>  ON A.book_id = B.id</pre><p>By doing this, you can retrive the book and its associated authors information in a single database round trip, avoiding additional unnecessary queries.</p><p>This approach is particularly useful when the query is predictable, frequently executed, and has well-defined data structure.</p><blockquote>However, GraphQL APIs usually support many different query shapes and nested relationships. Maintaning dedicated queries for every use case can become cumbersome. In this case…</blockquote><h4>Use Dataloaders! (Recommended)</h4><p>When the data structure is very flexible and its requirements may change, you should use Dataloaders.</p><p>They can provide a more reusable approach to batch data from the database and resolve the N+1 problem.</p><h4>How Dataloaders Works</h4><p>Dataloaders operates in two main steps:</p><ol><li><strong>Batching:</strong> Instead of executing queries one-by-one, Dataloaders waits until all queries for related data are collected, then batches them into a single query.</li><li><strong>Caching:</strong> Dataloaders caches the result of queries, ensuring that if the same query is requested again, it can be returned from the cache without making a new database call.</li></ol><h4>Why Dataloaders Solves the Problem</h4><p>Let’s break down how a Dataloader helps solve the N+1 problem.</p><p>Using the previous e-commerce example, the API might execute N additional queries for every product:</p><pre>SELECT * FROM reviews WHERE product_id = 1;<br>SELECT * FROM reviews WHERE product_id = 2;<br>SELECT * FROM reviews WHERE product_id = 3;<br>SELECT * FROM reviews WHERE product_id = 4;<br>...</pre><p>As the number of products increases, the number of database queries increases as well.</p><p>With a Dataloader, the GraphQL API collects the requested product IDs and passes them to a batch-loading function. Instead of executing a single query for every product, the API now only hits the database once with a batch of product IDs:</p><pre>SELECT * FROM reviews WHERE product_id IN (1, 2, 3, 4);</pre><p>This reduces the N+1 problem to a 2-query problem: one query for fetching the products and one batched query to fetch its reviews.</p><h3>Implementing Dataloaders in a .NET GraphQL API</h3><p>Now, let’s break down the implementation of Dataloaders in a GraphQL API. In this particular case, we’re going to use Hot Chocolate as the GraphQL library and GreenDonut to create the Dataloaders.</p><p>The examples used bellow are available in the following GitHub repository: <a href="https://github.com/evaaldo/Account.GraphQL">https://github.com/evaaldo/Account.GraphQL</a></p><p>It is a straightforward GraphQL API for a imaginary account service.</p><h4>Step 1: Install GreenDonut</h4><p>GreenDonut provides the BatchDataLoader used by Hot Chocolate. Add it to the API project by running the following commands:</p><pre>dotnet add .\src\Account.GraphQL.Api\ package GreenDonut --version 16.6.8<br>dotnet restore .\Account.GraphQL.slnx</pre><h4>Step 2: Create a Batch Method in your Repository</h4><p>A Dataloader needs to fetch multiple related records in the same call, so it’s necessary to create a repository method to support it. Here is an example:</p><pre>public async Task&lt;IEnumerable&lt;PersonResponseDto&gt;&gt; GetPersonsByIdsAsync(IEnumerable&lt;int&gt; ids, CancellationToken cancellationToken = default)<br>{<br>    var sql = &quot;SELECT * FROM tb_account_person WHERE id = ANY(@Ids)&quot;;<br><br>    await using var dataSource = _factory.CreateConnection();<br>    await using var connection = await dataSource.OpenConnectionAsync(cancellationToken);<br><br>    return await connection.QueryAsync&lt;PersonResponseDto&gt;(sql, new { Ids = ids });<br>}</pre><blockquote>Note: I’m using the ANY statement, but you can use IN or any other statement that solves the problem.</blockquote><h4>Step 3: Create the Dataloader</h4><p>A <strong>BatchDataLoader</strong> calls the repository method created previously and returns the results keyed by ID. For example, the following <strong>PersonByIdDataLoader.cs</strong> batches person IDs and returns null when an ID was not found:</p><pre>public class PersonByIdDataLoader : BatchDataLoader&lt;int, PersonResponseDto?&gt;<br>{<br>    private readonly IPersonRepository _personRepository;<br><br>    public PersonByIdDataLoader(<br>      IBatchScheduler scheduler,<br>      IPersonRepository personRepository)<br>        : base(scheduler, new DataLoaderOptions())<br>    {<br>        _personRepository = personRepository;<br>    }<br><br>    protected override async Task&lt;IReadOnlyDictionary&lt;int, PersonResponseDto?&gt;&gt; LoadBatchAsync(IReadOnlyList&lt;int&gt; keys, CancellationToken cancellationToken)<br>    {<br>        var persons = await _personRepository.GetPersonsByIdsAsync(keys, cancellationToken);<br>        var dict = persons.ToDictionary(p =&gt; p.Id);<br>        return keys.ToDictionary(id =&gt; id, id =&gt; dict.TryGetValue(id, out var p) ? p : null);<br>    }<br>}</pre><h4>Step 4: Create a Resolver for the Dataloader</h4><p>Now you need to create a method to receive the account requested and then ask to the created Dataloader for its person data:</p><pre>[ExtendObjectType(typeof(AccountResponseDto))]<br>public class AccountResolvers<br>{<br>    public Task&lt;PersonResponseDto?&gt; GetPerson(<br>      [Parent] AccountResponseDto account,<br>      PersonByIdDataLoader loader,<br>      CancellationToken cancellationToken)<br>    {<br>        return loader.LoadAsync(account.IdPerson, cancellationToken);<br>    }<br>}</pre><p>Understanding the method:</p><ul><li><strong>[Parent]</strong> provides the account currently begin resolved.</li><li><strong>loader.LoadAsync() </strong>uses its foreign-key ID.</li><li><strong>loader.LoadAsync()</strong> batches those IDs across accounts.</li></ul><h4>Step 5: Register the Dataloader and the Resolver</h4><p>Register your Dataloader and your resolver, so it can be made related queries without N+1 problem. In your Program.cs, write it:</p><pre>services.AddGraphQLServer()<br>    ... // Here is the previous configuration of your code<br>    .AddQueryType&lt;Query&gt;()<br>    .AddTypeExtension&lt;AccountResolvers&gt;()<br>    .AddDataLoader&lt;PersonByIdDataLoader&gt;();</pre><p>To test it, make a request:</p><pre>query {<br>  accounts {<br>    id<br>    person {<br>      name<br>      email<br>    }<br>  }<br>}</pre><h3>Benefits of Using Dataloaders</h3><p>Here is some benefits of using Dataloaders:</p><ul><li><strong>N+1 Problem Solved!</strong> Now you can hit the database with one query instead of N+1 queries.</li><li><strong>Faster Response to the Client:</strong> With less queries, the time response for fetching data is reduced, improving the overall user experience.</li><li><strong>Database Relieved:</strong> With less queries, the number of open connections with the database is reduced, leading to more efficient resource usage.</li></ul><h3>Stay Sharp!</h3><p>Dataloaders are a great solution for the N+1 Problem, but keep some things in mind when using it:</p><ul><li><strong>Cache:</strong> Dataloader caching is per-request, meaning that cache data is only valid during the request. For long-term caching, consider using an external cache solution, like Redis.</li><li><strong>Batching Correctly:</strong> You need to correctly decide which fields and relation should use Dataloader. Batching too aggressively can lead to inefficient queries, while batching too conservatively can miss opportunities for optimization.</li></ul><h3>Conclusion</h3><p>Now you know what is the N+1 Problem. This problem is a common pitfall while creating a GraphQL API, but with Dataloaders you can easily resolve it. Hope this article was helpfull for you and don’t hesitate in accessing the GraphQL repository to see the examples with a better code context.</p><p>GraphQL Repository: <a href="https://github.com/evaaldo/Account.GraphQL">https://github.com/evaaldo/Account.GraphQL</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74f5670123fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>