โ
Previous Module
Contract Upgrade Proxy
โก Query Optimization: Pagination & Batching
Master GraphQL query patterns for fast data retrieval
Query blockchain data efficiently with The Graph
Your Progress
0 / 5 completedโก Writing Efficient GraphQL Queries
Bad queries kill performance. Fetching all entities without pagination? Your query times out. Nested arrays? N+1 problem slows everything down. No filters? Wasted bandwidth. GraphQL's flexibility is dangerousโyou can write queries that fetch gigabytes of data. Learn pagination, filtering, sorting, and field selection to keep queries fast. Rule of thumb: If a query takes >500ms, it's too slow. Optimize or users will leave.
๐ฎ Interactive: Query Optimizer
Compare unoptimized vs optimized queries. Toggle strategy and adjust page size to see performance impact. Watch query time change in real-time.
โ Unoptimized Query
{
transfers {
id
token {
id
name
symbol
decimals
totalSupply
transfers {
id
from
to
amount
timestamp
}
}
from
to
amount
timestamp
blockNumber
}
}Performanceโ ๏ธ
Query Time:0ms
โ ๏ธ Issues
- โขNo first/skip pagination - returns ALL transfers (could be millions)
- โขNested transfers in token - causes N+1 queries
- โขNo orderBy - results in random order
- โขNo where filter - fetches unnecessary data
- โขFetches all fields even if unused
๐ Optimization Techniques
1. Pagination (first/skip): Never fetch all entities. Use
first: 100 to limit results. Combine with skip for pagination. The Graph max is 1,000 per query.2. Filtering (where): Reduce data at source.
where: { amount_gt: "1000000" } filters server-side. Supports _gt, _lt, _in, _contains, _starts_with.3. Sorting (orderBy/orderDirection):
orderBy: timestamp, orderDirection: desc for latest-first. Indexed fields sort faster.4. Field Selection: Only request fields you need. Don't fetch
token.transfers if unused. Saves bandwidth and time.โ ๏ธ Common Pitfalls
N+1 Queries
Fetching nested arrays (token.transfers) causes multiple queries. Avoid or use separate queries.
No Pagination
Queries without first/skip can fetch millions of records. Always paginate or query times out.
Over-fetching
Requesting all fields when you need 3. Wastes bandwidth. Be selective.
String Filters
_contains on non-indexed fields is slow. Use indexed fields for filtering.
๐ก Performance Targets
<100ms: ExcellentList queries with pagination
100-300ms: GoodFiltered/sorted queries
300-500ms: AcceptableComplex aggregations
>500ms: Too slowNeeds optimization