โ†
Previous Module
Contract Upgrade Proxy

โšก Query Optimization: Pagination & Batching

Master GraphQL query patterns for fast data retrieval

Query blockchain data efficiently with The Graph

โšก 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
โ† Subgraph Development