:zap: Powerful tool for avoiding N+1 DB or HTTP queries
:zap: Powerful tool for avoiding N+1 DB or HTTP queries
This gem provides a generic lazy batching mechanism to avoid N+1 DB queries, HTTP queries, etc.
Developers from these companies use BatchLoader:
loader).Let's have a look at the code with N+1 queries:
…The naive approach would be to preload dependent objects on the top level:
…But the problem here is that load_posts now depends on the child association and knows that it has to preload data for future use. And it'll do it every time, even if it's not necessary. Can we do better? Sure!
With BatchLoader we can rewrite the code above:
…As we can see, batching is isolated and described right in a place where it's needed.
In general, BatchLoader returns a lazy object. Each lazy object knows which data it needs to load and how to batch the query. As soon as you need to use the lazy objects, they will be automatically loaded once without N+1 queries.
So, when we call BatchLoader.for we pass an item (user_id) which should be collected and used for batching later. For the batch method, we pass a block which will use all the collected items (user_ids):
BatchLoader.for(post.user_id).batch do |user_ids, loader| ... end
Inside the block we execute a batch query for our items (User.where). After that, all we have to do is to call loader by passing an item which was used in BatchLoader.for method (user_id) and the loaded object itself (user):
BatchLoader.for(post.user_id).batch do |user_ids, loader| User.where(id: user_ids).each { |user| loader.call(user.id, user) } end
When we call any method on the lazy object, it'll be automatically loaded through batching for all instantiated BatchLoaders:
puts users # => SELECT * FROM users WHERE id IN (1, 2, 3)
For more information, see the Implementation details section.
Now imagine we have a regular Rails app with N+1 HTTP requests:
# app/models/post.rb
class Post
puts user_lazy(1) # no request
# => Usually, it's just enough to clear the cache between HTTP requests in the app. To do so, simply add the middleware:
use BatchLoader::MiddlewareTo drop the cache manually you can run:
puts user_lazy(1) # SELECT * FROM users WHERE id IN (1)
puts user_lazy(1) # no request
BatchLoader::Executor.clear_current
puts user_lazy(1) # SELECT * FROM users WHERE id IN (1)In some rare cases it's useful to disable caching for BatchLoader. For example, in tests or after data mutations:
def user_lazy(id)
BatchLoader.for(id).batch(cache: false) do |ids, loader|
# ...
end
end
puts user_lazy(1) # SELECT * FROM users WHERE id IN (1)
puts user_lazy(1) # SELECT * FROM users WHERE id IN (1)If you set cache: false, it's likely you also want replace_methods: false (see below section).
By default, BatchLoader replaces methods on its instance by calling #define_method after batching to copy methods from the loaded value.
This consumes some time but allows to speed up any future method calls on the instance.
In some cases, when there are a lot of instances with a huge number of defined methods, this initial process of replacing the methods can be slow.
You may consider avoiding the "up front payment" and "pay as you go" with #method_missing by disabling the method replacement:
BatchLoader.for(id).batch(replace_methods: false) do |ids, loader|
# ...
endAdd this line to your application's Gemfile:
gem 'batch-loader'And then execute:
$ bundleOr install it yourself as:
$ gem install batch-loaderBatchLoader.for(item).batch(
default_value: default_value,
cache: cache,
replace_methods: replace_methods,
key: key
) do |items, loader, args|
# ...
end| Argument Key | Default | Description |
|---|---|---|
item |
- | Item which will be collected and used for batching. |
default_value |
nil |
Value returned by default after batching. |
cache |
true |
Set false to disable caching between the same executions. |
replace_methods |
true |
Set false to use #method_missing instead of replacing the methods after batching. |
key |
nil |
Pass custom key to uniquely identify the batch block. |
items |
- | List of collected items for batching. |
loader |
- | Lambda which should be called to load values loaded in batch. |
args |
{default_value: nil, cache: true, replace_methods: true, key: nil} |
Arguments passed to the batch method. |
These gems are built by using BatchLoader:
BatchLoader in other programming languages:
See the slides [37-42].
After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.
Bug reports and pull requests are welcome on GitHub at https://github.com/exAspArk/batch-loader. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.
There are some other Ruby implementations for batching such as:
However, batch-loader has some differences:
batch method.nil values for the missing ones. Instead, it provides the loader lambda which simply maps an item to the loaded object.The gem is available as open source under the terms of the MIT License.
Everyone interacting in the Batch::Loader project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.
No open issues yet, or sync has not completed.