A Ruby gem providing a generic lazy batching mechanism to avoid N+1 database queries and HTTP requests.
BatchLoader is a Ruby gem that provides a generic lazy batching mechanism to eliminate N+1 query problems. It allows developers to defer data loading operations—such as database queries or HTTP requests—and batch them together automatically, reducing the number of round trips and improving application performance. It is particularly useful in scenarios like GraphQL resolvers or RESTful APIs where multiple independent data requests are made.
Ruby developers building applications with N+1 query issues, especially those using GraphQL (with graphql-ruby) or REST APIs where data associations lead to multiple database or HTTP requests. It's also valuable for teams at scale, as evidenced by adoption at companies like GitLab and Netflix.
Developers choose BatchLoader because it's a lightweight, dependency-free solution that integrates naturally with Ruby's lazy evaluation patterns. Unlike alternatives, it doesn't force Promise-based async patterns or require sharing batching logic through variables, offering a simpler, more Ruby-idiomatic approach to batching.
:zap: Powerful tool for avoiding N+1 DB or HTTP queries
Open-Awesome is built by the community, for the community. Submit a project, suggest an awesome list, or help improve the catalog on GitHub.
Uses Ruby's Enumerable#lazy to defer data loading until necessary, then batches multiple requests into a single query, directly solving N+1 issues as shown in the basic example with User.where.
Works with any data source—databases, HTTP APIs, or custom logic—making it versatile beyond ORM-specific solutions, illustrated by the RESTful API example with HttpClient.
Caches loaded values by default within the same execution context, reducing redundant requests; the README demonstrates this with repeated calls to user_lazy(1) skipping extra queries.
Built for multi-threaded environments, allowing safe concurrent use, such as in the RESTful API example with the parallel gem for HTTP requests.
Requires manual middleware setup (BatchLoader::Middleware) for HTTP request caching and careful cache clearing, which can be error-prone and add overhead in web applications.
The default replace_methods: true can slow initialization when instances have many methods, forcing developers to use method_missing with performance trade-offs, as admitted in the Replacing methods section.
Does not enforce input order in batch results, unlike alternatives like graphql-batch, which may complicate scenarios where maintaining sequence is critical, as noted in the Alternatives section.