AsyncDataloader
will run GraphQL::Dataloader::Source#fetch
calls in parallel, so that external service calls (like database queries or network calls) don’t have to wait in a queue.
To use AsyncDataloader
, hook it up in your schema instead of GraphQL::Dataloader
:
- use GraphQL::Dataloader
+ use GraphQL::Dataloader::AsyncDataloader
Also, add the async
gem to your project, for example:
bundle add async
Now, GraphQL::Dataloader::AsyncDataloader
will create Async::Task
instances instead of plain Fiber
s and the async
gem will manage parallelism.
For a demonstration of this behavior, see: https://github.com/rmosolgo/rails-graphql-async-demo
You can also implement manual parallelism using dataloader.yield
.
For Rails, you’ll need Rails 7.1, which properly supports fiber-based concurrency, and you’ll also want to configure Rails to use Fibers for isolation:
class Application < Rails::Application
# ...
config.active_support.isolation_level = :fiber
end
You can also manually implement parallelism with Dataloader. See the Dataloader Parallelism guide for details.