Blockchain indexing with The Graph: subgraph design and optimization

We often encounter situations where the frontend makes dozens of `eth_call` and `getLogs` calls on every page load. On mainnet this takes 2–3 seconds, over public RPC it's unreliable, and when aggregation or historical data is needed, direct calls become simply impossible. [The Graph](https://en.wik

Blockchain Development Services

Frequently Asked Questions

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1441
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1301
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    998
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1267
  • image_logo-advance_0.webp
    B2B Advance company logo design
    713
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    1003

We often encounter situations where the frontend makes dozens of eth_call and getLogs calls on every page load. On mainnet this takes 2–3 seconds, over public RPC it's unreliable, and when aggregation or historical data is needed, direct calls become simply impossible. The Graph solves this problem correctly: you write a subgraph once, which indexes contract events, and get a GraphQL API with arbitrary queries in milliseconds. Infrastructure cost savings can reach 90% (up to $2000 per month for a typical DeFi project), and query speed increases tenfold. Below we'll break down how to design and write a subgraph to avoid common mistakes and achieve maximum performance.

How to design a subgraph schema?

A subgraph consists of three components, and it's critical to design the schema based on frontend queries, not based on the event structure.

  • subgraph.yaml — manifest. Describes data sources: which contracts to listen to, starting block (startBlock), which events and functions to handle. Critical: startBlock must be the contract deployment block, not zero — otherwise indexing will take days.
  • schema.graphql — entity types. This is what will be available via GraphQL. Design it based on frontend needs, not based on contract event structure — these are different things.
  • mappings.ts — AssemblyScript handlers. Transform raw events into schema entities.

Schema design

The most common mistake is making the schema a mirror of contract events. If the event is Transfer(address from, address to, uint256 amount), you don't need a TransferEvent entity. Instead, think about queries: "what is the current balance of a user", "top holders", "volume in the last 24 hours".

type Token @entity { id: ID! totalSupply: BigInt! holderCount: Int! } type Account @entity { id: Bytes! balance: BigInt! transfersIn: [Transfer!]! @derivedFrom(field: "to") transfersOut: [Transfer!]! @derivedFrom(field: "from") } type Transfer @entity(immutable: true) { id: Bytes! from: Account! to: Account! amount: BigInt! blockNumber: BigInt! timestamp: BigInt! } 

@entity(immutable: true) for Transfer is an important optimization. Immutable entities are not stored in the undo buffer, making indexing 30–40% faster.

Handlers: step-by-step

AssemblyScript is not full TypeScript — there's no null via ?., no Array.from(), no standard JS methods. This is a frequent source of errors for developers coming from frontend.

  1. Identify the event you are handling (e.g., Transfer).
  2. Load or create an entity using Account.load(address) or new Account(address).
  3. Update fields (balance, references).
  4. Save changes via save().
// Correct loading or creating an entity function getOrCreateAccount(address: Address): Account { let account = Account.load(address) if (account == null) { account = new Account(address) account.balance = BigInt.fromI32(0) } return account as Account } export function handleTransfer(event: TransferEvent): void { let from = getOrCreateAccount(event.params.from) let to = getOrCreateAccount(event.params.to) from.balance = from.balance.minus(event.params.value) to.balance = to.balance.plus(event.params.value) from.save() to.save() // Immutable — create once, never load let transfer = new Transfer( event.transaction.hash.concatI32(event.logIndex.toI32()) ) transfer.from = from.id transfer.to = to.id transfer.amount = event.params.value transfer.blockNumber = event.block.number transfer.timestamp = event.block.timestamp transfer.save() } 

Call handlers and block handlers

In addition to events, The Graph can handle function calls (callHandlers) and each block (blockHandlers). Call handlers are needed when the contract doesn't emit events for required operations — legacy contracts often lack events. Block handlers are used for periodic snapshots (e.g., daily stats). Both significantly slow down indexing, especially block handlers — use them only when necessary.

Handler type Purpose Impact on indexing speed
Event handler Process contract events Minimal (primary type)
Call handler Track function calls Moderate (requires archive node)
Block handler Periodic block processing High (runs on every block)

Why is The Graph faster than direct RPC calls?

Direct RPC calls execute sequentially and load the node. The Graph indexes data once and stores it in an optimized database accessible via GraphQL. Queries execute in milliseconds (typical time 50 to 200 ms), and pagination via first/skip works up to skip: 5000 — for larger datasets use keyset pagination with id_gt. According to The Graph documentation, indexing throughput can reach 1000 events per second on standard hardware. Infrastructure cost savings can reach 90%, as confirmed by experience of large DeFi projects — for example, Uniswap reduced RPC costs by $3000+ per month after switching to a subgraph.

Which hosting to choose: Hosted Service, Decentralized, or self-hosted?

The choice of subgraph deployment option depends on requirements for availability, control, and budget.

Option Availability Control Cost
Hosted Service Basic (no SLA) Limited Free for small projects
Decentralized Network High (decentralized indexers) Medium Requires GRT (token)
Self-hosted Graph Node Full (own infrastructure) Full Infrastructure costs ($1000+/month)

Our team, with ten years of experience in blockchain, has implemented over 20 The Graph integrations. We help you choose the optimal option for your project and avoid common problems.

Typical indexing issues

  • Subgraph fails with "store error" — check non-nullable fields.
  • Indexing stalls on a block — add handling for reverted transactions via receipt.status.
  • Data discrepancy due to reorgs — set minEthereumBlockConfirmations.
  • Excessive gas consumption when writing — use @entity(immutable: true) for immutable data.

What to know about pagination and filtering?

Query type Example Limitation
Pagination first: 100, skip: 0 skip up to 5000
Keyset pagination where: { id_gt: "..." } No limit
Filtering where: { balance_gt: "0" } All operators supported
Sorting orderBy: timestamp, orderDirection: desc Any entity field

Keyset pagination is preferred for large datasets — it's faster and has no skip limit.

Frontend integration

Typical stack: Apollo Client or urql for React applications. The Graph supports subscriptions via WebSocket for real-time updates without polling.

const POSITIONS_QUERY = gql` query UserPositions($account: Bytes!, $skip: Int!) { positions( where: { owner: $account, liquidity_gt: "0" } orderBy: createdAt orderDirection: desc first: 100 skip: $skip ) { id pool { token0 { symbol } token1 { symbol } feeTier } liquidity depositedToken0 depositedToken1 } } ` 

Timelines and what's included

In 2–5 days: schema design tailored to client needs, writing mappings for all events and calls, testing on a fork, deployment to Hosted Service or setting up a self-hosted node, basic integration into existing frontend or providing a GraphQL endpoint. Cost is calculated individually, but savings on RPC queries justify the investment — typical payback occurs within 1–3 months.

Contact us to discuss integrating The Graph into your project. Experience with The Graph and dozens of successful integrations guarantee results. Request a consultation — we'll prepare a custom proposal.