Hacker News new | ask | show | jobs
by lipanski 2055 days ago
In my experience, automatic eager loading is the most elegant solution to this problem. For ActiveRecord, I'd recommend Goliloader [1] (which is a gem similar to ar_lazy_preload but with emphasis on doing that automatically) while for Sequel, you can enable the TacticalEagerLoading plugin [2].

These tools don't require explicit `includes`or `preload` calls. They can infer the tables that need to be eager loaded through usage (e.g. if you iterate through users and every iteration requests the user's posts, the first iteration will eager load all posts for all those users). This fits really well with GraphQL because different clients might trigger requests for different associations. Automatic eager loading allows you to optimize for all those different cases without writing a single line of code.

The other solutions are either way too explicit or might be eager loading too much. Things like graphql-batch don't even feel like ActiveRecord any more (and for a good reason - it's a different kind of abstraction, meant to batch all sorts of things, including HTTP requests).

There are more caveats when it comes to eager loading, mainly there are many things that can break eager loading. I recently wrote a blog post [3] about dealing with those issues.

[1] https://github.com/salsify/goldiloader

[2] https://sequel.jeremyevans.net/rdoc-plugins/classes/Sequel/P...

[3] https://lipanski.com/posts/activerecord-eager-loading

2 comments

Great post! By the way, the reason why ar_lazy_preload exists is that neither me nor anyone else around me heard about goldiloader at the moment when ar_lazy_preload was created
Came here to also recommend Goldiloader, but your comment and especially your blogpost summarizes it just fine.

We‘re using Goldiloader in a medium sized Rails application with zero problems so far.