How The Graph Works: A Builder's Guide
The Graph indexing protocol — what it is, how subgraphs work, when to use it vs alternatives, and how to structure your data for frontend consumption.
The Graph is a decentralized protocol for indexing and querying blockchain data. It's how most DeFi and NFT frontends serve historical data without running expensive archive nodes.
The Problem The Graph Solves
Ethereum nodes store the current state of the chain efficiently, but historical queries are slow. 'Show me all transfers of this token in the last 30 days' requires filtering millions of logs — impractical to do in real-time on the frontend. The Graph indexes this data and makes it queryable via GraphQL.
How Subgraphs Work
A subgraph is a definition file that tells The Graph: which contracts to watch, which events to index, and how to transform event data into entities (the data model). Graph nodes process historical events and create the index. Developers query via GraphQL. The Graph's decentralized network of indexers serves production queries; hosted service provides a simpler option for development.
Subgraph Schema Design
Your subgraph's schema defines what data is stored and queryable. Design for your frontend's query patterns — if your UI needs 'show all positions for a user', store positions indexed by user. Avoid storing data you won't query. Use derived fields (calculated from other entities) for aggregate metrics rather than storing them separately.
Writing Mapping Functions
Mappings are AssemblyScript (TypeScript-like) functions that handle contract events. For each event, you load or create entities and update their fields. Keep mappings simple — complex logic in mappings can be hard to debug. Use calls (read current contract state) sparingly — they're expensive and can slow indexing.
When to Use The Graph vs Alternatives
Use The Graph for: complex multi-event queries, historical data aggregation, production frontends that need reliable data. Use eth_getLogs directly for: simple queries, single-event filters, rapid prototyping. Use Envio, Ponder, or a custom indexer for: high-speed requirements, complex business logic in the indexer, cases where decentralization isn't required. Use Alchemy/Infura's enhanced APIs for: simple NFT ownership queries, common data patterns they've pre-indexed.
Syncing Delays
Subgraphs have an indexing lag — new events aren't queryable instantly. For most UX this is fine (2–10 seconds). For real-time balance updates or order book display, supplement with direct RPC calls for the latest state and use The Graph for historical data. Design your frontend to handle this hybrid data model.
Related Guides
Ready to build your Web3 project?
Tell us about your project and get a precise quote.
Get a Project Quote