iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐈

Solving N+1 Issues in Doctrine ORM with a GraphQL-Inspired DataLoader Pattern

に公開
2025/12/21

This is the 21st article of the Symfony Advent Calendar 2025 🎄


If you are using Symfony, you are likely using Doctrine ORM on a daily basis.
In this article, I will introduce a method to solve the N+1 problem that occurs when using Doctrine ORM—not by using standard Fetch Join (Eager Loading), but by using an approach similar to GraphQL's DataLoader.

TL;DR

  • How to solve the Doctrine ORM N+1 problem without using Fetch Join (Eager Loading).
  • Inspired by GraphQL's DataLoader, we store IDs during postLoad and execute batch loading lazily.
  • Even in cases where JOINs are too heavy or complex, you can return values as methods of the parent entity.

Entities (Tables) in this Sample

This article uses the entity (table) structure described below.
Assuming an e-commerce site for alcohol, there are Orders and LineItems, with Products associated with them. AlcoholType is an enum representing the type of alcohol.

The N+1 Problem in Doctrine ORM

First, let's review when the N+1 problem occurs in Doctrine ORM.

For example, when you fetch multiple Orders and reference their LineItems:

$orders = $orderRepository->findAll(); // ...(a)

foreach ($orders as $order) {
    foreach ($order->getLineItems() as $lineItem) { // ... (b)
        echo sprintf('%s: %s', $lineItem->getLineNumber(), $lineItem->getSubtotal()), PHP_EOL;
    }
}

With code like this:

  • (a) executes one SELECT query to the order table.
  • (b) executes N SELECT queries to the line_item table (one for each order).

This results in N queries being executed for the number of records in the order table, which leads to performance issues.

Solution via Eager Loading using Fetch Join

To solve this, most people use Eager Loading with Fetch Join.
For example, you can rewrite the $orderRepository->findAll(); part as follows:

$orders = $this->orderRepository->createQueryBuilder('o')
    ->leftJoin('o.lineItems', 'li')->addSelect('li')
    ->getQuery()->getResult();

By simply rewriting it this way, it joins the order and line_item tables and fetches them in a single SELECT query, thus preventing the N+1 problem.

Reference: https://www.doctrine-project.org/projects/doctrine-orm/en/current/reference/dql-doctrine-query-language.html#joins

Cases where Fetch Join (Eager Loading) is Difficult

Basically, you should use Eager Loading by Fetch Joining related entities as in the example above, but there are cases where this is difficult:

  • The number of child entities relative to the parent entity is enormous, or JOINing down to grandchild or great-grandchild entities results in a huge number of records.
  • You only actually use a subset of those records, making it wasteful to hydrate all of them into memory.
  • While you can use Criteria to fetch only some records conditionally, you cannot inspect grandchild entities.
  • Even if you can fetch child entities conditionally using Criteria, the N+1 problem still occurs when fetching multiple parent entities unless the child entities are Fetch Joined.
    • For example, you can implement a method using Criteria to fetch only the single LineItem with the highest subtotal for an Order, but if you do not Fetch Join LineItems, the N+1 problem will still occur.

In such cases, many people give up on Fetch Join and write logic to fetch only that specific data in the repository. However, in this article, we aim to return such data as methods of the parent entity, Order.

What is GraphQL's DataLoader?

Setting aside the main topic for a moment, what exactly is GraphQL's DataLoader?

Here is an excerpt from a response by Gemini:

DataLoader in GraphQL is a utility library for solving the "N+1 problem" that occurs during queries to databases or APIs.

In short, it is "a mechanism that collects scattered requests and batches them into a single request after waiting for a brief moment."

1. Problem Solved: The N+1 Problem

In GraphQL, resolvers (data fetching functions) are executed for each field. For example, when fetching "Posts and their Authors (User)," you often end up with inefficient behavior like this:

  1. 1st query: Fetch 10 posts.
  2. 2nd to 11th queries: Query the User table 10 times consecutively based on the "Author ID" of each post.

This is the "N+1 problem" where 1 (the original query) + N (the number of users) queries are executed.

2. Two Key Features of DataLoader

DataLoader improves efficiency through the following two steps:

  • Batching:
    Collects requests for IDs that occur within the same frame (one cycle of the event loop) and queries the database in a batch, such as with an array like [1, 2, 10].
  • Caching:
    IDs retrieved once within the same request (e.g., User ID 1) are cached in memory, and results are returned immediately without accessing the database for subsequent requests.

3. Conceptual Workflow

When using DataLoader, the behavior of resolvers changes as follows:

State Traditional Behavior Using DataLoader
Request Occurrence Issues SQL immediately Queues the request (waits)
Execution Timing Every time Single batch process (WHERE id IN (1, 2, 3...))
Duplicate Data Fetched multiple times Returned from cache

It is a mechanism that also solves the N+1 problem, primarily characterized by batching IDs to fetch data at once and using caches to handle duplicate data.

From the next section, we will implement a feature inspired by this using Doctrine. The goal is to address cases where Fetch Join is suboptimal.

Introducing a DataLoader-like Mechanism to Doctrine

I have placed sample code that introduces a DataLoader-like mechanism to Doctrine in the repository below, so I will explain it by pulling excerpts from there.
https://github.com/kalibora/doctrine-dataloader-sample/tree/main

Accumulating IDs

https://github.com/kalibora/doctrine-dataloader-sample/blob/e568db1bd0c67b2cd7caf5fcb83d5a303249d9ac/src/EntityListener/OrderListener.php#L19-L34

We register a listener for the Doctrine postLoad event, and when an Order entity is loaded, we call $this->resolver->addId(Order::class, $id); to store the ID in the Resolver class.

The setHighestSubtotalLineItemResolver and setLineItemsByAlcoholTypeResolver calls below that inject closures into the Order entity to return values fetched in bulk or retrieved from the cache later. This allows us to call methods like getHighestSubtotalLineItem() or getLineItemsByAlcoholType() on the Order entity to return efficiently fetched values from the DB.

Note: Why the postLoad event?

By using postLoad, we can treat the set of entities loaded in that request as "one batch," meaning they become the target for bulk data fetching.

Bulk Fetching Data

https://github.com/kalibora/doctrine-dataloader-sample/blob/e568db1bd0c67b2cd7caf5fcb83d5a303249d9ac/src/Service/DataLoader/Resolver.php#L87-L92

In $targetIds = $this->targetIdSet->getIds($entity);, we retrieve the list of IDs accumulated earlier. Since $cachedIds contains the IDs of cached values, we take the difference to identify IDs not yet loaded from the DB as $unloadedIds, then use $loadedValues = $loader->load($unloadedIds, $args) to fetch them in bulk based on multiple IDs.
Note that since this process is called from the closures defined in the Order entity earlier, it acts as a lazy call and is executed after the entire list of Order entities has been loaded, resulting in bulk data retrieval.

Each Loader is defined for each field value you want to resolve. For example, the definition of the Loader that loads the line item with the highest subtotal is as follows:

https://github.com/kalibora/doctrine-dataloader-sample/blob/e568db1bd0c67b2cd7caf5fcb83d5a303249d9ac/src/Service/DataLoader/Loader/OrderHighestSubtotalLineItemLoader.php#L31-L34

https://github.com/kalibora/doctrine-dataloader-sample/blob/e568db1bd0c67b2cd7caf5fcb83d5a303249d9ac/src/Repository/LineItemRepository.php#L24-L88

While I am not sure if this is the best example, the point I want to make is that you can use performance-optimized native SQL while still returning values through an intuitive, object-oriented interface as methods of the Order entity.

Retrieving Duplicate Data from Cache

I don't think much explanation is needed here; it simply caches in-memory.

https://github.com/kalibora/doctrine-dataloader-sample/blob/e568db1bd0c67b2cd7caf5fcb83d5a303249d9ac/src/Service/DataLoader/Data/Cache.php#L8-L49

As is the Symfony way, it implements ResetInterface to clear the cache, ensuring compatibility with Symfony Messenger.
https://github.com/kalibora/doctrine-dataloader-sample/blob/e568db1bd0c67b2cd7caf5fcb83d5a303249d9ac/src/Service/DataLoader/Resolver.php#L64-L70

Important Considerations for this Implementation

  • Assumes a single request (Unit of Work).
  • Not intended for serialized entities (due to the use of closures).
  • Requires postLoad to be triggered (cannot be used if an entity is created but not yet saved to the DB).

Summary

I introduced a method where you can fetch values in a GraphQL-like DataLoader fashion—while also utilizing native SQL—in cases where you want to retrieve values from an aggregate root parent entity but Fetch Join (Eager Loading) is too heavy.

Having said all that, if you are using CQRS and define separate read-oriented DTOs (data models) for each use case, you don't necessarily need to struggle this much with Doctrine entities. You can simply create individual DTOs and write/map DQL or SQL suited for them.

That said, if you are not doing CQRS and are primarily using Doctrine entities for your read models, this approach might be useful for you.

Discussion