Skip to content

Investigate single query related entity loading and orderings #29171

Description

@roji

When loading related entities in single query mode, our query pipeline currently injects orderings which make all related rows be grouped together. Our shaper relies on this ordering for assigning the related dependents to their correct principal. This issue is about investigating removing those orderings, and using client-side dictionary (or identity) lookups to find the principal instead.

  • Orderings generally impact query planning in a significant way, and require the database to do a lot of work. We've received quite a few user reports about these orderings; we still need to investigate this thoroughly, but it makes sense that the orderings would regress perf significantly in various scenarios.
  • In general, we should strive to remove as much load from the database, even at the cost of running slower at the client, since the database tier is far harder to scale than the application tier. The orderings effectively do the opposite, pushing more work down to the database.
  • One argument in favor of ordering is that it allows EF to stream the results, since all rows related to a principal are grouped together. If we remove the orderings, EF can't return a single principal before it consumes all rows, since there may be another dependent row at the end.
  • However, orderings prevent the database from streaming results back; we're basically pushing the buffering back to the server, increasing memory requirements there (as above, we should be doing the opposite and unloading the database).
  • This also negatively affects the latency of results, as the database starts sending rows back later. Removing the orderings would allow the database to return rows earlier, which is important.
  • We've raised the possibility of using identity resolution as a substitute for the orderings (but only if the queries are identified as buffering in some way). Depending on the perf impact, I think we should consider always doing this, either for AsTracking and NoTrackingWithIdentity, or possibly even for AsNoTracking (which makes it pretty much the same as NoTrackingWithIdentity). Note that we need to investigate why NoTrackingWithIdentity isn't efficient at the moment (#28579).
  • We may want to do the same for final GroupBy, which also injects orderings (#19929).

Thanks @NinoFloris for the conversation around this.

Issues on this:

  • #19571: previous issue where removing the orderings was discussed.
  • #20076: discussed distinguishing between buffering and streaming queries, and proposes removing tracking only for queries which are both buffering and tracking (via identity resolution).
  • #19828: issue for removing only the last ordering (done)

Activity

  1. ajcvickers commented on Sep 21, 2022

    @ajcvickers
    Contributor

    We've raised the possibility of using identity resolution as a substitute for the orderings (but only if the queries are identified as buffering in some way). Depending on the perf impact, I think we should consider always doing this, in any case. This would effectively mean that NoTracking queries become NoTrackingWithIdentity.

    One of the uses for AsNoTracking is to stream a result set that won't fit in memory. We shouldn't prevent this, even if it becomes opt-in.

  2. roji commented on Sep 21, 2022

    @roji
    MemberAuthor

    I'm wondering if it makes sense to allow users to stream huge results in EF, when doing so forces the database to buffer those same results (which is what the orderings do)... We're basically just pushing the buffering (=huge memory requirements) onto the database, no?

    It's true that databases may have ways to better deal with this, e.g. use disk space as temporary storage while ordering the results. I certainly wouldn't want this to be anything close to a default behavior though, as perf there probably becomes truly disasterous.

    I wonder if for the huge resultset scenario - which hopefully should be rare - it might not be better for users to deal with this by breaking their single LINQ query into two, separately processing principals and dependents. I'd certainly want to at least aggressively guide users towards considering this, rather than just slapping AsNoTracking to make things "just work", at the relatively hidden cost of increasing database memory usage (and CPU).

    In any case, we definitely need to carefully consider what we do here, as changes here may be "breaking" (in the sense that client memory requirements may suddenly change in a very significant way).

    (added needs-design)

  3. ajcvickers commented on Sep 21, 2022

    @ajcvickers
    Contributor

    If a no-tracking query against a single table without ordering still streams efficiently, then that might be enough.

  4. roji commented on Sep 21, 2022

    @roji
    MemberAuthor

    Yeah, there's indeed no reason to buffer anywhere if only a single table is involved.

  5. roji commented on Sep 21, 2022

    @roji
    MemberAuthor

    One possible pattern to efficiently stream with relationships is the following (or some variation):

    var posts = ctx.Posts
        .Select(p => new
        {
            Post = new Post { Id = p.Id, Title = p.Title },
            Blog = new Blog { Id = p.Blog.Id, Name = p.Blog.Name }
        })
        .ToList();

    The point is to avoid the fixup; Assuming single query is used, each row contains all the information needed to materialize a result, and so should be able to stream. That could be acceptable as a user workaround for streaming huge result set scenario with relationships.

  6. added this to the Backlog milestone on Sep 21, 2022
  7. roji commented on Oct 17, 2022

    @roji
    MemberAuthor

    A couple more notes on this...

    First, when you have a single collection include, (Blogs.Include(b => b.Posts), an ORDER BY on the principal ID probably has little overhead, since there's an index (the primary). However, if you add another nested include (Blogs.Include(b => b.Posts).ThenInclude(p => p.Comments)), we have the second ordering on the Post ID. At this point an index cannot be used any more, and so removing the ordering becomes quite important.

    Second, we think it's still important to support streaming (as opposed to buffering) for when results are huge. We should keep in mind that it's not great to achieve this at the expense of forcing the database to buffer, by adding orderings. Possibilities here include:

    • Reversing the query, starting from the dependent, and avoiding navigation fixup (see Investigate single query related entity loading and orderings #29171 (comment)).
    • Switch tracking queries to the new mode (without orderings), and leave no-tracking as the streaming mode.
      • This requires us to maintain both techniques (more complexity), and makes no-tracking even more problematic from a perf standpoint.
      • Since using the state manager imposes overhead, for cases where tracking isn't needed, AsNoTrackingWithIdentity becomes the new "best perf" option, as least for single query.
      • We'd have to make sure AsNoTrackingWithIdentity it performs well (see Look into the performance of AsNoTrackingWithIdentity #28579), and educate people to use it. Many people just use AsNoTracking "to make stuff faster".
  8. 33 remaining items

  9. roji commented on Feb 26, 2025

    @roji
    MemberAuthor

    @Webreaper you cannot strip the orderings from the query, since EF (currently) depends on them in order to properly materialize the results (i.e. the rows are expected to come back in the appropriate ordering, and if they don't you'll get bad results).

    One workaround you can use is to avoid Include() altogether, but rather use Join(), at which point you're expressing the SQL query more directly and won't get the extra orderings:

    _ = await context.Blogs
        .Join(context.Posts, b => b.Id, p => p.BlogId, (b, p) => new { b, p })
        .ToListAsync();
  10. Webreaper commented on Feb 26, 2025

    @Webreaper

    Thanks, that's really useful. I don't think I've ever actually used EFCore's Join directly before - we can look into it.

    For now we've mitigated it by sort of hard-coding our own split query. So we do:

    var resultIds = await context.Things
                                 .Include( ... )
                                 .ThenInclude( ... )
                                 .Where( ... )
                                 .OrderBy( ... )
                                 .Select( x => x.Id )
                                 .ToListAsync();
    
    var actualResults = await GetTheThingsFromIDs( resultIds );
    

    Because there's only a single column of IDs in the resultset, EF doesn't add any extraneous ORDER BY clauses, and we were already hitting the DB twice anyway (for unrelated reasons) so this isn't any less efficient, and seems to run much faster.

    I'd ask you to please prioritise getting this fixed as a priorty in EF 10; it's already been bumped for 7, 8 and 9, and it seems critical enough to be something that shouldn't be a 4-year fix. I'd bet money this exact issue is the cause of a lot of people who claim "EF performance is rubbish" - but in this case it's justified.

  11. added theissue type on Jun 15, 2025
  12. bachratyg commented on Jul 16, 2025

    @bachratyg

    Don't forget #22435
    While removing the orderby may allow the db to stream data back, cartesian explosion will still flood the network.

  13. roji commented on Jul 16, 2025

    @roji
    MemberAuthor

    While removing the orderby may allow the db to stream data back

    FWIW the main problem with the orderby is less to allow the DB to stream the results and more to allow it to generate a more efficient query plan (but #22435 is still relevant regardless).

  14. modified the milestones: Backlog, 10.0.2 on Nov 25, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions