An on-demand query is a direct request for specific data from a blockchain's current state, executed at the time of the request. Unlike queries against a pre-built index or a cached database, it involves a node or service provider—such as an RPC provider—executing the query logic against the live chain data. This method is essential for fetching real-time, verifiable information like an account's precise native token balance, the current state of a smart contract variable, or the outcome of a simulated transaction. The result is cryptographically verifiable against the chain's consensus, ensuring data integrity.
On-Demand Query
What is an On-Demand Query?
An on-demand query is a request for specific, real-time data from a blockchain or decentralized network, processed at the moment it is requested rather than being pre-indexed.
The primary mechanism for on-demand queries in ecosystems like Ethereum is the JSON-RPC API, with methods such as eth_getBalance or eth_call. These calls are routed to a node, which executes the request against its synchronized copy of the blockchain state. This process is resource-intensive for the node, as it may require traversing the state trie or executing contract code. Consequently, service providers often rate-limit or charge for these queries. The alternative is indexed querying, where data is extracted, transformed, and stored in an optimized database (like PostgreSQL) for fast, complex historical searches, which is the domain of blockchain indexers.
Key use cases for on-demand queries include wallet balance checks, real-time price feeds from decentralized exchanges, and transaction simulation. For example, a DeFi front-end uses an eth_call query to simulate a swap on Uniswap and show the user the expected output before they sign the transaction. The major trade-off is between latency/performance and data freshness. Indexed queries are faster for complex historical analysis but may lag by blocks or minutes; on-demand queries provide the definitive, current state but are slower and more costly for the provider. A robust data architecture often employs both patterns.
How an On-Demand Query Works
An on-demand query is a request for specific, real-time data from a blockchain or decentralized network, processed at the moment it is made rather than relying on pre-indexed historical information.
An on-demand query is a direct, synchronous request to a blockchain node's RPC (Remote Procedure Call) endpoint to retrieve the current state of the ledger. Unlike indexed services that store historical data, this method fetches live data directly from the source by calling functions like eth_getBalance or eth_call. The process involves a user or application sending a structured request containing the method name and parameters, which the node validates and executes against its most recent state to produce a result. This mechanism is fundamental for wallets checking balances, dApps reading smart contract variables, and explorers verifying transaction status.
The technical workflow follows a clear sequence: a client constructs a JSON-RPC request, transmits it to a node, and awaits a response. The node's execution engine processes the query—for example, running a smart contract's view or pure function without consuming gas—and returns the result. Key characteristics include low latency for fresh data and deterministic outputs, where the same query on the same block height yields an identical result. However, performance depends entirely on the node's health and sync status, and complex queries can be resource-intensive for the node operator.
This approach contrasts with indexed queries, which query a pre-processed database of blockchain events. On-demand queries excel for real-time, point-in-time checks where data freshness is critical, but they lack the efficiency for aggregating large datasets or searching historical events. Common use cases include fetching a wallet's native token balance, checking if a transaction is confirmed, or reading a dynamic value from a DeFi protocol's smart contract, such as an exchange rate or a user's staking rewards.
Key Features of On-Demand Queries
On-demand queries provide real-time, ad-hoc access to blockchain data, enabling developers to retrieve specific information without running a full node.
Real-Time Data Access
Unlike pre-indexed data, on-demand queries fetch the latest state directly from a node's RPC endpoint. This is critical for applications requiring immediate data freshness, such as live wallet balances, pending transaction status, or the current block number. The result is not cached historical data but the live state of the chain at the moment of the query.
Ad-Hoc & Flexible
Queries are not predefined; they are constructed and executed as needed. This allows developers to ask arbitrary questions of the blockchain using standard RPC methods like eth_getBalance or eth_call. It provides the ultimate flexibility for debugging, building custom dashboards, or fetching data for one-off analyses that don't justify building a dedicated index.
No Infrastructure Overhead
The primary value proposition is eliminating node operations. Developers bypass the need to sync, maintain, and scale their own archive or full nodes. The query service handles all the underlying infrastructure, connection management, and load balancing, allowing teams to focus on application logic instead of DevOps for data access.
Direct RPC Execution
On-demand queries work by executing standard JSON-RPC calls against high-performance node endpoints. Common methods include:
eth_getBlockByNumber: Retrieve block details.eth_getLogs: Query event logs with filters.eth_call: Execute a read-only function on a smart contract. This provides a familiar interface for any Web3 developer.
Use Case: Real-Time Verification
A prime application is instant verification of on-chain state. For example:
- A DEX verifying a user's token balance before allowing a trade.
- A bridge confirming a transaction has reached sufficient confirmations on the source chain before minting assets on the destination.
- An NFT platform checking the real-time owner of a token for access control.
Contrast with Indexed Data
It's essential to distinguish on-demand queries from indexed queries. Indexed data (from services like The Graph) is pre-processed, structured, and optimized for complex historical searches (e.g., "all trades for this NFT collection last month"). On-demand queries are for immediate, point-in-time reads of the raw chain state, trading query complexity for latency and data freshness.
Examples & Use Cases
On-demand querying enables real-time, ad-hoc data retrieval from blockchain nodes, bypassing the need for pre-indexed data. It's essential for applications requiring the absolute latest state or historical data not covered by standard APIs.
Real-Time Wallet Balance Check
A DeFi dashboard uses an on-demand query to fetch the latest native token and ERC-20 balances for a user's wallet directly from an archive node. This ensures the displayed portfolio value is accurate to the most recent block, crucial for trading decisions. The query typically involves calling the eth_getBalance and eth_call RPC methods.
Smart Contract State Inspection
Before executing a complex transaction, a developer queries the current state variables of a smart contract. For example, checking the exact reserve ratios in a DEX pool or the current interest rate in a lending protocol. This is done via the eth_call RPC method to simulate execution without sending a transaction.
Transaction Receipt & Logs Analysis
An analytics platform performs an on-demand query to retrieve the full receipt and event logs for a specific transaction hash using eth_getTransactionReceipt. This is vital for auditing, debugging failed transactions, or analyzing the specific internal calls and token transfers that occurred.
Historical Block Data Retrieval
A blockchain explorer allows users to look up any past block by number or hash. The query, using eth_getBlockByNumber, fetches all transactions, the miner address, gas used, and timestamp for that block. This provides transparency and enables forensic analysis of past network activity.
Gas Estimation for Transaction Simulation
A wallet application uses eth_estimateGas to simulate a transaction before the user signs it. This on-demand query returns an estimated gas units required, helping users avoid failed transactions due to out-of-gas errors and allowing for accurate fee calculation.
Network Health & Peer Discovery
Node operators and infrastructure providers use low-level queries like net_peerCount and eth_syncing to monitor their node's connection health and synchronization status. This is critical for maintaining reliable access to the blockchain and ensuring data served is up-to-date.
On-Demand vs. Other Query Models
A technical comparison of on-demand query execution against traditional blockchain data access methods.
| Feature / Metric | On-Demand Query | Indexed RPC | Full Node |
|---|---|---|---|
Query Latency | < 1 sec | 2-5 sec | 10-30 sec |
Data Freshness | Real-time (head of chain) | 5-15 block lag | Real-time (head of chain) |
Infrastructure Cost | $10-50/month | $200-500/month | $1000+/month |
Query Flexibility | |||
Historical Data Depth | Full history | Configurable window | Full history |
Developer Setup Complexity | None (API) | Moderate | High |
Data Consistency Guarantees | Strong (cryptographic proofs) | Eventual | Strong (full validation) |
Cross-Chain Query Support |
Cost Structure & Economics
The financial mechanisms governing how blockchain data is accessed, priced, and paid for, including gas fees, query costs, and protocol-level incentives.
Gas Fees
Gas fees are the fundamental transaction cost on EVM-compatible blockchains, paid in the native token (e.g., ETH). They compensate validators for computation and storage. Key components:
- Base Fee: A mandatory, algorithmically set fee burned by the network.
- Priority Fee (Tip): An optional incentive paid to validators for faster transaction inclusion.
- Gas Limit: The maximum computational units a user is willing to pay for.
RPC Provider Pricing Models
Services providing remote procedure call (RPC) access to blockchains use various models:
- Freemium Tier: Limited requests per second (RPS) for free, with paid tiers for higher limits.
- Pay-as-you-go: Charges per request, often with volume discounts (e.g., $0.000001 per request).
- Enterprise/Subscription: Fixed monthly fee for dedicated endpoints, higher rate limits, and guaranteed uptime.
The Graph's Query Fee Model
The Graph uses a decentralized marketplace for subgraph queries. Consumers purchase GRT tokens to pay for queries, which are distributed to Indexers (node operators), Curators (subgraph signalers), and Delegators (stakers). Query costs are determined by:
- Subgraph complexity and indexing cost.
- Market dynamics of Indexer pricing.
- Network usage and demand.
Indexing & Infrastructure Costs
The operational expenses for running blockchain data infrastructure include:
- Hardware: High-performance servers, SSDs, and bandwidth for full nodes and indexers.
- Storage: Long-term archival of historical state and event logs.
- Engineering & Maintenance: DevOps for node synchronization, software updates, and monitoring. These costs are typically baked into the pricing of RPC providers and decentralized indexing services.
MEV & Priority Economics
Maximal Extractable Value (MEV) creates a secondary fee market. Searchers bid via priority fees to have their transactions (e.g., arbitrage, liquidations) included in specific block positions. This drives up gas costs during high-demand periods. Flashbots and other MEV-relay services create private channels for these transactions, impacting the public mempool's economics.
EIP-1559 & Fee Market Reform
EIP-1559 overhauled Ethereum's fee market by introducing:
- Variable Block Size: Blocks expand and contract based on demand.
- Base Fee Burn: The base fee is destroyed (burned), making ETH deflationary.
- Improved UX: Users set a max fee and priority fee, with automatic refunds for unused gas. This creates more predictable fee estimation but does not inherently lower costs during peak congestion.
Security Considerations
On-demand query systems in blockchain analytics present unique security challenges, balancing data accessibility with the protection of sensitive information and system integrity.
API Key Management & Rate Limiting
The primary security layer for on-demand queries is robust API key management. This includes:
- Authentication & Authorization: Verifying user identity and scoping permissions to specific data sets or query types.
- Rate Limiting: Preventing Denial-of-Service (DoS) attacks and ensuring fair resource allocation by capping requests per key.
- Key Rotation & Revocation: Enforcing policies for regular key updates and immediate revocation if a key is compromised.
Query Injection & Input Sanitization
Malicious actors may attempt query injection attacks, similar to SQL injection, by crafting inputs that manipulate the query execution logic. Mitigations include:
- Strict Input Validation: Enforcing schema and type constraints on all user-provided parameters.
- Parameterized Queries: Using predefined query templates where user input is treated as data, not executable code.
- Sandboxed Execution: Running queries in isolated environments with limited system access to prevent data exfiltration or system calls.
Data Privacy & PII Exposure
Blockchain data can contain or be correlated with Personally Identifiable Information (PII). On-demand systems must implement:
- Data Anonymization: Stripping or hashing identifiers (e.g., IP addresses, certain metadata) from query results.
- Differential Privacy: Adding statistical noise to aggregate results to prevent re-identification of individuals from large datasets.
- Compliance Frameworks: Adhering to regulations like GDPR, which may require query auditing and the 'right to be forgotten' for off-chain linked data.
Resource Exhaustion & Cost Controls
Complex on-demand queries can consume excessive computational resources, leading to high operational costs or system instability. Key controls are:
- Compute Budgeting: Assigning a maximum cost (in gas, CPU time, or memory) per query and terminating execution if exceeded.
- Query Complexity Analysis: Estimating resource requirements before execution and rejecting prohibitively expensive requests.
- Billing & Quotas: Implementing usage-based billing and tiered quotas to align user incentives with system capacity.
Result Integrity & Provenance
Users must trust that query results are accurate and derived from the canonical chain state. This requires:
- State Proofs: Providing cryptographic Merkle proofs or zero-knowledge proofs that verify the returned data is part of a specific, validated block.
- Timestamping & Non-Repudiation: Logging queries and their results with tamper-evident timestamps to provide an audit trail.
- Source Attestation: Clearly identifying the data source (e.g., specific node client, archive node version) to account for potential chain reorganizations.
Network & Infrastructure Security
The underlying infrastructure hosting the query engine must be secured against standard attack vectors:
- DDoS Protection: Mitigating volumetric attacks that target API endpoints.
- TLS/SSL Encryption: Ensuring all data in transit is encrypted to prevent eavesdropping or man-in-the-middle attacks.
- Secure Node Access: If the system queries live nodes, those nodes must be secured against unauthorized access and sybil attacks to prevent data poisoning.
Frequently Asked Questions
Common questions about Chainscore's real-time, on-demand data querying capabilities for blockchain analytics.
An on-demand query is a real-time request for specific blockchain data that is not pre-indexed, executed against a live node or a specialized query engine. It works by taking a user's structured request (e.g., a SQL query or GraphQL operation), routing it to a high-performance execution layer, and returning the precise result set without requiring prior data aggregation. This contrasts with pre-computed dashboards, offering flexibility for ad-hoc analysis. For example, querying "the average transaction fee for a specific smart contract over the last hour" requires scanning raw blocks on-demand, which Chainscore executes via distributed node infrastructure to provide sub-second responses.
Get In Touch
today.
Our experts will offer a free quote and a 30min call to discuss your project.