How DataLoader batching works
masterBatching is the primary feature of DataLoader. It coalesces multiple individual .load() calls that occur within a single tick of the event loop into a single call to your batch_load_fn.
To implement batching, subclass DataLoader and provide a batch_load_fn. This function must adhere to two strict constraints:
- The returned list of values must be the same length as the input list of keys.
- The index of each value in the list must correspond exactly to the index of its key in the input list.
If a key has no corresponding value in the backend, you must return None at that index.
from aiodataloader import DataLoader
class UserLoader(DataLoader):
async def batch_load_fn(self, keys):
# keys: [2, 9, 6, 1]
# returns: [{id: 2...}, {id: 9...}, None, {id: 1...}]
return await my_batch_get_users(keys)
user_loader = UserLoader()
# These two calls are coalesced into one batch call
user1_future = user_loader.load(1)
user2_future = user_loader.load(2)
user1 = await user1_future
user2 = await user2_future