A common issue with graphql servers is how the resolvers query their datasource.
his issue results in a large number of unneccessary database queries or http requests.
Say you were wanting to list a bunch of cults people were in
```graphql
query {
persons {
id
name
cult {
id
name
}
}
}
```
What would be executed by a SQL database would be:
```sql
SELECT id, name, cult_id FROM persons;
SELECT id, name FROM cults WHERE id = 1;
SELECT id, name FROM cults WHERE id = 1;
SELECT id, name FROM cults WHERE id = 1;
SELECT id, name FROM cults WHERE id = 1;
SELECT id, name FROM cults WHERE id = 2;
SELECT id, name FROM cults WHERE id = 2;
SELECT id, name FROM cults WHERE id = 2;
# ...
```
Once the list of users has been returned, a separate query is run to find the cult of each user.
You can see how this could quickly become a problem.
A common solution to this is to introduce a **dataloader**.
This can be done with Juniper using the crate [cksac/dataloader-rs](https://github.com/cksac/dataloader-rs), which has two types of dataloaders; cached and non-cached. This example will explore the non-cached option.
Once created, a dataloader has the functions `.load()` and `.load_many()`.
When called these return a Future.
In the above example `cult_loader.load(id: i32)` returns `Future<Cult>`. If we had used `cult_loader.load_may(Vec<i32>)` it would have returned `Future<Vec<Cult>>`.
### Where do I create my dataloaders?
**Dataloaders** should be created per-request to avoid risk of bugs where one user is able to load cached/batched data from another user/ outside of its authenticated scope.
Creating dataloaders within individual resolvers will prevent batching from occurring and will nullify the benefits of the dataloader.
For example:
_When you declare your context_
```rust, ignore
use juniper;
#[derive(Clone)]
pub struct Context {
pub cult_loader: CultLoader,
}
impl juniper::Context for Context {}
impl Context {
pub fn new(cult_loader: CultLoader) -> Self {
Self {
cult_loader
}
}
}
```
_Your handler for GraphQL (Note: instantiating context here keeps it per-request)_