DataLoader is a Node.js utility for the data-fetching layer. It batches concurrent loads and memoizes results within a request.
Overview
DataLoader gives applications a consistent API over remote data sources such as databases or web services. It coalesces many individual key lookups into fewer backend round-trips by batching loads that occur in the same event-loop turn, and it caches values for the lifetime of a loader instance.
Each DataLoader is constructed with a batch function that receives an array of keys and returns a promise of values in matching order. Callers use load and loadMany on single keys; the library schedules batch execution and can use custom batch schedulers when default timing is not ideal.
Caching is per-request memoization, not a shared application cache like Redis. Typical usage creates a new DataLoader when an HTTP request begins and discards it when the request ends so different users do not see each other's cached rows. Cache can be cleared after mutations, disabled entirely, or backed by a custom map such as an LRU for long-lived loaders.
The design originated from Facebook's Loader pattern and is widely used with graphql-js services, though it applies to any Node.js code that benefits from batched, cached key-value fetching.
Key features
- Batch coalescing in one event-loop frame
- Per-request memoization cache
- Configurable batch schedule function
- load and loadMany APIs
- Optional cache disable or custom cache map
- Cache clear after mutations
- Error caching per key
- maxBatchSize and batch toggle options
Use cases
- GraphQL resolver N+1 query reduction
- Batched database ID lookups in APIs
- Per-request caching in Express handlers
- Consistent loading across decoupled app modules
- Reference pattern for other language ports