Glossary

Subgraph

A subgraph is a custom data indexing schema that maps blockchain events into a queryable API using The Graph protocol.

Key Takeaways

  • A subgraph is an open-source indexing definition that tells The Graph protocol which smart contract events to watch and how to transform raw on-chain data into structured, queryable entities served via a GraphQL API.
  • Subgraphs solve the blockchain data access problem: blockchains store data in formats optimized for consensus, not queries. Without indexing, even simple lookups (like fetching a user's token balances) require scanning millions of blocks.
  • The Graph's decentralized network uses tokenomics (the GRT token) to coordinate indexers, curators, and delegators, replacing centralized blockchain indexer backends with a permissionless data marketplace.

What Is a Subgraph?

A subgraph is a custom data indexing schema built on The Graph protocol. It defines which smart contract events to listen for, how to transform those events into structured entities, and how to expose those entities through a GraphQL API. Think of it as a specialized database view over blockchain data: developers declare the shape of data they need, and The Graph handles ingestion, indexing, and serving.

The problem subgraphs solve is fundamental. Blockchains are append-only ledgers optimized for verifying transactions, not answering queries. A decentralized application that needs to display a user's NFT collection, trading history, or governance votes cannot efficiently scan every block in the chain. Subgraphs create a pre-indexed, queryable layer on top of raw chain data, giving dApps the fast reads they need without sacrificing decentralization.

The Graph protocol has served over 1.27 trillion queries across more than 75,000 projects, supporting 60+ blockchain networks including Ethereum, Arbitrum, Base, Polygon, Solana, and others. Following the sunset of its centralized hosted service in June 2024, all subgraph hosting runs on The Graph's decentralized network of independent indexer nodes.

How It Works

Every subgraph consists of three core files that together define a complete indexing pipeline:

  1. A GraphQL schema (schema.graphql) that defines the entity types and their fields
  2. A manifest (subgraph.yaml) that specifies which contracts, events, and networks to index
  3. AssemblyScript mappings (mapping.ts) that contain handler functions to transform event data into entities

Defining the Schema

The schema declares entity types using standard GraphQL syntax. Each entity must have an id field and can reference other entities to create relationships. For example, a DEX subgraph might define:

type Pool @entity {
  id: Bytes!
  token0: Token!
  token1: Token!
  totalValueLocked: BigDecimal!
  createdAt: BigInt!
}

type Swap @entity {
  id: Bytes!
  pool: Pool!
  sender: Bytes!
  amountIn: BigDecimal!
  amountOut: BigDecimal!
  timestamp: BigInt!
}

The Subgraph Manifest

The manifest (subgraph.yaml) maps smart contract events to handler functions. It specifies the contract address, the ABI, the network, and which block to start indexing from:

specVersion: 1.3.0
schema:
  file: ./schema.graphql
dataSources:
  - kind: ethereum/contract
    name: UniswapV3Pool
    network: mainnet
    source:
      address: "0x1F98431c8aD98523631AE4a59f267346ea31F984"
      abi: Factory
      startBlock: 12369621
    mapping:
      kind: ethereum/events
      apiVersion: 0.0.7
      language: wasm/assemblyscript
      entities:
        - Pool
        - Swap
      eventHandlers:
        - event: PoolCreated(indexed address,indexed address,indexed uint24,int24,address)
          handler: handlePoolCreated
        - event: Swap(indexed address,indexed address,int256,int256,uint160,uint128,int24)
          handler: handleSwap
      file: ./src/mapping.ts

Three handler types are available: event handlers (most common, triggered by contract event emissions), call handlers (triggered by function calls, requires tracing), and block handlers (run after every block or at intervals).

Writing Mappings

Mappings are written in AssemblyScript, a TypeScript subset that compiles to WebAssembly. They receive typed event parameters, create or load entities, populate fields, and call .save() to persist:

import { PoolCreated } from "../generated/Factory/Factory"
import { Pool } from "../generated/schema"

export function handlePoolCreated(event: PoolCreated): void {
  let pool = new Pool(event.params.pool)
  pool.token0 = event.params.token0
  pool.token1 = event.params.token1
  pool.totalValueLocked = BigDecimal.zero()
  pool.createdAt = event.block.timestamp
  pool.save()
}

Running graph codegen auto-generates type-safe classes from the contract ABIs and GraphQL schema. After building with graph build, the subgraph deploys to The Graph's network via Subgraph Studio.

Querying the Subgraph

Once deployed and indexed, the subgraph exposes a GraphQL endpoint. dApps query it like any GraphQL API:

query {
  pools(first: 10, orderBy: totalValueLocked, orderDirection: desc) {
    id
    token0 { symbol }
    token1 { symbol }
    totalValueLocked
  }
  swaps(where: { sender: "0xabc..." }, first: 5) {
    amountIn
    amountOut
    timestamp
  }
}

This query, which would require scanning millions of blocks if run directly against an RPC endpoint, returns in milliseconds from the indexed subgraph.

The Decentralized Network

The Graph operates as a decentralized protocol with four participant roles, coordinated through the GRT token:

  • Indexers: node operators who stake a minimum of 100,000 GRT to index subgraph data and serve queries. They earn indexing rewards (from protocol inflation at roughly 3% annually) plus query fees paid by consumers.
  • Curators: participants who signal GRT on subgraphs they consider valuable. Signaling indicates indexing demand and helps indexers prioritize which subgraphs to index. Curators earn a share of query fees from the subgraphs they signal on.
  • Delegators: GRT holders who stake their tokens with indexers without running infrastructure themselves. They share in the indexer's rewards proportionally.
  • Consumers: developers and dApps that pay query fees in GRT to access subgraph data.

The protocol includes burning mechanisms: a 1% curation tax, a 0.5% delegation tax, 1% of query fees burned, and portions of slashed indexer stakes. These burns offset the inflationary issuance used for indexing rewards.

Use Cases

DeFi Dashboards and Analytics

DeFi protocols rely heavily on subgraphs for front-end data. Uniswap, Aave, Compound, and hundreds of other protocols use subgraphs to power their interfaces: displaying pool statistics, TVL metrics, user positions, transaction histories, and liquidity pool analytics. Without subgraphs, each protocol would need to build and maintain its own indexing infrastructure.

NFT Marketplaces

NFT platforms use subgraphs to index ownership transfers, metadata, listings, bids, and sales across ERC-721 and ERC-1155 contracts. A marketplace querying token ownership directly from an RPC node would be impractically slow: subgraphs pre-index this data into instantly queryable formats.

Governance and DAOs

DAO governance interfaces use subgraphs to track proposals, votes, delegation changes, and execution status. Platforms like Snapshot and Tally index governance token events through subgraphs to render voting dashboards and participation analytics.

Cross-Chain Data Aggregation

With support for 60+ networks, subgraphs enable applications that aggregate data across multiple chains. A portfolio tracker might deploy separate subgraphs on Ethereum, Arbitrum, and Base, then combine results in the frontend to show a unified view of user positions across layer 2 networks.

Subgraphs vs. Centralized Indexing

Centralized alternatives to The Graph exist and serve specific use cases:

ApproachStrengthsTradeoffs
The Graph (subgraphs)Decentralized, censorship-resistant, shared infrastructureAssemblyScript learning curve, GRT query costs
Goldsky / Alchemy SubgraphsManaged hosting, Graph-compatible, faster iterationCentralized, vendor lock-in risk
Moralis / CovalentPre-built APIs, no custom indexing neededLess flexible, not customizable per contract
Custom backend (PostgreSQL + event listener)Full control, any language, any schemaHigh maintenance, single point of failure, must handle reorgs
Envio HyperIndexTypeScript-based, significantly faster indexingSmaller ecosystem, newer project

For teams building on Bitcoin rather than EVM chains, the indexing landscape differs significantly. Bitcoin's UTXO model does not emit smart contract events. Instead, Bitcoin applications use specialized blockchain indexers like Electrum server implementations (Electrs, Fulcrum) or Blockstream's Esplora, which index the chain by address and script hash. These serve a similar purpose to subgraphs: they make blockchain data queryable without requiring every client to scan the full chain. Learn more about Bitcoin indexing infrastructure in our Electrum server architecture deep dive.

Risks and Considerations

Indexing Latency

Subgraphs are not real-time. After a new block is produced, the indexer must process it, execute mapping handlers, and update its store. This introduces seconds to minutes of lag between on-chain events and queryable data. Applications requiring instant state (like a trading interface showing the current price) may need to supplement subgraph data with direct RPC calls.

Chain Reorganization Handling

When a chain reorganization occurs, the indexer must revert entities back to their state before the reorg and reprocess the new canonical blocks. Subgraphs handle this automatically, but applications should be aware that recently indexed data may change if a reorg occurs on the underlying chain.

Centralization Concerns

While The Graph's network is decentralized in design, the practical distribution of indexing capacity matters. If a small number of indexers handle the majority of queries for popular subgraphs, the system's censorship resistance depends on those operators remaining honest and available. The curation and staking mechanisms aim to distribute this load, but economic concentration remains a risk.

Data Correctness

A subgraph is only as correct as its mapping code. Bugs in handler logic can produce inaccurate indexed data, and consumers may not realize the data is wrong. Unlike querying a node directly (which returns canonical chain state), subgraph data is a developer-defined transformation of that state. Auditing subgraph mappings is as important as auditing the smart contracts they index.

Cost and Economics

Query fees on the decentralized network are paid in GRT. For high-traffic applications, these costs can be significant. Developers must weigh the decentralization benefits against the cost of managed alternatives. The Graph's pricing model continues to evolve: an x402 USDC-based payment gateway is planned for 2026, which would let developers and AI agents pay per query using stablecoins.

Why It Matters

Subgraphs are the data access layer for much of the decentralized web. Without efficient indexing, dApps would either be unusably slow (querying nodes directly) or dependent on centralized backends that defeat the purpose of building on-chain. The Graph's subgraph model provides a middle path: structured, fast data access backed by a decentralized network of indexers rather than a single company's servers.

For the broader blockchain data stack, subgraphs sit between raw node access (via RPC endpoints) and block explorer APIs. RPC endpoints give real-time but unstructured access. Block explorers offer structured data but with limited customization. Subgraphs let developers define exactly the data model they need, making them the preferred infrastructure for complex dApp frontends and analytics platforms.

As blockchain ecosystems expand across multiple chains and layers, the ability to index and query data consistently becomes increasingly critical. Whether through The Graph's subgraph protocol or alternative indexing solutions, the pattern of separating data ingestion from data querying is now a standard part of Web3 application architecture.

This glossary entry is for informational purposes only and does not constitute financial or investment advice. Always do your own research before using any protocol or technology.