Dataloading and batching
Strawberry's DataLoader API lets async GraphQL resolvers request related data without causing one database or service call per resolver. It groups pending key requests into one batch, shares results through a cache, and returns each result to the resolver that requested it.
DataLoader role
DataLoader is an async boundary between a resolver and a batch-capable data source. A resolver calls load for one key or load_many for several keys. The loader calls its batch function with the pending keys and resolves the returned values back to the waiting resolvers.
This pattern changes the cost of a nested query. Instead of each parent object loading its related record alone, many resolver calls can share one batch request. The resolver still works with one value at a time, while the data source receives a request that it can handle efficiently.
The API is async. Resolvers that use it must await the returned value or use it with another async coordination method. See GraphQL execution for the place of resolver execution in the wider operation flow.
Batch request lifecycle
The loader collects loads that are pending in the current async turn. It then sends their keys to the batch function and maps the returned values to the waiting loads.
The following diagram shows how several field resolvers can share one request while keeping separate results in the GraphQL response.
sequenceDiagram
participant O as GraphQL operation
participant R as Field resolvers
participant L as DataLoader
participant S as Data source
O->>R: Resolve related fields
R->>L: load(key A)
R->>L: load(key B)
L->>S: One batch request [A, B]
S-->>L: Results [value A, value B]
L-->>R: Resolve value A and value B
R-->>O: Build response fields
References: strawberry/dataloader.py• L106-181 docs/…/dataloaders.md• L21-87 tests/…/test_dataloaders.py• L22-45
Request-scoped loading
Loader lifetime
Batching and caching only work across calls that share the same loader instance. In a GraphQL server, create that instance as part of the request context so its pending work and cache belong to one operation. A loader created at module or application scope can keep values for the life of the server and can expose data from one request to another.
The context can hold more than one loader when different keys need different data sources or cache rules. Resolvers read the loader from the context and keep the data access choice close to the field that needs it.
References: docs/…/dataloaders.md• L382-430 docs/…/dataloaders.md• L241-311
Resolver access
A resolver normally receives the loader through strawberry.Info and awaits load for its key. This keeps the resolver focused on the field value. The batch function owns the work needed to fetch those values from a database or another service.
This separation also lets several resolvers use the same loader during one operation. The GraphQL executor can therefore turn many field-level requests into one data-source request without changing the shape of the schema.
References: docs/…/dataloaders.md• L313-380 tests/…/test_dataloaders.py• L22-45 tests/…/test_dataloaders.py• L41-56
Batch result contract
Key and result alignment
The batch function must return one item for every input key and keep the same order. The item at position n is the result for the key at position n. This contract lets the loader deliver results to the correct resolver even when the data source uses a single query for the whole batch.
load_many keeps the same order as its input keys. It is useful when one resolver already has a group of related keys. A batch function must still return a result for every key, including a missing record represented by a per-key exception.
References: strawberry/dataloader.py• L180-181 strawberry/dataloader.py• L251-287 tests/test_dataloaders.py• L117-129 docs/…/dataloaders.md• L83-87
Error propagation
The batch function can return an exception value in the position for one failed key. The matching load then raises that exception, while successful keys in the same batch can still resolve. This supports partial results when one related record is missing or invalid.
If the batch function itself raises, the loader gives that error to every non-cancelled load in the batch. A wrong result count is also a batch error because the loader cannot safely map the values to keys. GraphQL then applies its normal field error and nullability rules to the resolver failures.
References: strawberry/dataloader.py• L269-293 docs/…/dataloaders.md• L90-127 tests/test_dataloaders.py• L74-129
Cache behavior
Per-key cache
The loader cache is enabled by default and is keyed by the value passed to load. It stores the pending result as well as the completed result. As a result, concurrent calls for the same key share one awaitable, and later calls in the same loader lifetime do not call the batch function again.
Set cache=False when repeated loads must reach the data source. With caching disabled, repeated keys can appear more than once in the same batch. The cache is an optimization and a consistency boundary, so its lifetime must match the freshness of the data that it represents.
References: strawberry/dataloader.py• L135-155 strawberry/dataloader.py• L163-178 tests/test_dataloaders.py• L132-193
Cache keys and invalidation
Use cache_key_fn when different input objects represent the same record or when a key is made from more than one value. The function must produce a hashable value, and the application must ensure that equivalent records do not produce conflicting keys.
Use clear for one key, clear_many for a group, or clear_all when a data change makes the current cache unsafe. A direct database read can also seed the loader with prime or prime_many. Priming avoids a later load for data already fetched and does not replace an existing cached value unless force=True is used.
References: strawberry/dataloader.py• L183-220 docs/…/dataloaders.md• L129-185 docs/…/dataloaders.md• L187-239
Custom cache policy
Applications can provide a custom cache through cache_map when the default in-memory cache is not suitable. The custom cache must support get, set, delete, and clear operations. This allows the application to choose a different storage policy, but it does not remove the need to control loader lifetime and key consistency.
References: strawberry/dataloader.py• L68-103 strawberry/dataloader.py• L149-154 docs/…/dataloaders.md• L241-311
Asynchronous loading patterns
Concurrent loads
Issue independent loads before awaiting their results when they should share a batch. asyncio.gather and load_many express this intent clearly. If a resolver awaits one load before it starts the next, the first load can dispatch before the second exists, so the calls may use separate batches.
The loader can split a large request with max_batch_size. Each group still follows the same key and result alignment contract, and the caller receives the results in its original order.
References: strawberry/dataloader.py• L180-181 strawberry/dataloader.py• L223-248 docs/…/dataloaders.md• L60-87 tests/test_dataloaders.py• L36-71
Cancellation
Each load waits on an async future. If a caller cancels its future, the loader does not write a result to that cancelled future. If all loads in a batch are cancelled before the data source work starts, the loader skips the batch. If only some are cancelled, it still fetches data for the remaining callers.
This behavior limits wasted database or service work when a client disconnects or a request times out. It also keeps the remaining resolver calls usable when one caller no longer needs its result.
References: strawberry/dataloader.py• L49-62 strawberry/dataloader.py• L261-293 tests/test_dataloaders.py• L319-547
Change checklist
When these files or sections are changed, remember to consider these:
- A batch function change must preserve one result per key and the input order. A silent mismatch changes which resolver receives each value.
- A change to loader construction must preserve request isolation. Moving a loader outside request context changes both cache lifetime and data visibility.
- A change to key types or cache-key rules must update clear and prime calls. Otherwise invalidation or preloaded data can target a different cache entry.
- A resolver change from concurrent loads to sequential awaits can remove batching even when the schema result stays the same.
- A change to per-key error values versus batch-level exceptions changes whether one field or all pending fields fail.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| The batch function returns fewer or more values than keys | The complete batch fails because results cannot be mapped safely | Return one value or exception for each key in the same order |
| The batch function raises an exception | Every non-cancelled load in that batch receives the exception | Return per-key exception values when only some keys fail |
| A long-lived loader is shared by requests | Cached values can become stale or cross request boundaries | Create loaders in the GraphQL request context |
| A cache key function maps distinct records to one key | One record can receive another record's cached value | Make the derived key uniquely identify the requested data |
| A resolver awaits each independent load before starting the next | Loads dispatch in separate batches and the N+1 pattern can remain | Start independent loads together or use load_many |
Key files
| File | Why to read it |
|---|---|
| strawberry/dataloader.py | Defines the DataLoader contract for batching, async results, caching, priming, invalidation, and cancellation. |
| docs/…/dataloaders.md | Shows the intended GraphQL usage, request-context lifetime, error model, and cache choices. |
| tests/…/test_dataloaders.py | Demonstrates that sibling GraphQL fields can share one loader batch. |
| tests/…/test_dataloaders.py | Shows the same pattern against a database-backed async GraphQL view. |
docs/graphql-execution.md | Explains the broader operation and resolver execution flow in which batching takes place. |
docs/operation-execution.md | Provides related context for how a GraphQL operation reaches its field resolvers. |
docs/subscriptions-and-streaming.md | Covers the related async and long-lived execution concerns for subscriptions and streams. |