Gas, Performance and ScalabilityIntroductionA smart contract is executed by a replicated network rather than by a single trusted server. Every validating node must be able to verify the same state transition. This design provides strong integrity and censorship resistance, but it makes computation, storage and communication scarce resources. On Ethereum and compatible networks, gas is the accounting mechanism used to price execution and limit resource consumption. Gas optimization is therefore not merely a cost-saving exercise. It is a systems-design discipline involving correctness, security, latency, throughput, user experience and decentralization. A contract that uses less gas but introduces a re-entrancy vulnerability is not optimized. Similarly, a high-throughput solution that depends on a small centralized operator may provide scalability at the expense of availability or trust minimization. This chapter examines gas measurement and optimization, storage and execution design, batching, Layer 2 systems, rollups, sidechains and cross-chain approaches. It also develops a framework for evaluating the scalability trilemma: the practical tension among security, decentralization and performance. Learning ObjectivesBy the end of this chapter, students should be able to: - Explain gas, gas limits, gas prices and transaction fees.
- Measure contract execution and identify major gas-consuming operations.
- Optimize storage, computation and data structures without weakening correctness.
- Compare batching, state channels, sidechains, optimistic rollups and zero-knowledge rollups.
- Evaluate throughput, latency, finality, availability, security and decentralization.
- Select an appropriate scaling architecture for a practical application.
- Recognize governance, regulatory and operational risks in scalable smart-contract systems.
1. Gas as a Resource-Accounting SystemThe Ethereum Virtual Machine (EVM) executes instructions called opcodes. Each opcode has a gas cost, and a transaction supplies a gas limit. Gas is an abstract unit rather than a currency. The fee paid by a user is calculated by multiplying gas consumed by the effective price per unit of gas. Transaction fee = Gas used × Effective gas price Gas used is measured in gas units, while the effective gas price is measured in wei per gas unit. One ether equals 10¹⁸ wei. Under Ethereum’s EIP-1559 fee mechanism, the effective gas price is generally: Effective gas price = Base fee + Priority fee The base fee is determined by protocol rules according to block-space demand and is burned. The priority fee, or tip, is offered to the block proposer. A transaction may specify a maximum fee, but the user normally pays only the effective price up to that maximum. The exact fee treatment depends on the network and transaction type. The gas limit is the maximum gas the transaction is allowed to consume. It is not necessarily the amount consumed. If execution reaches the limit before completion, the transaction fails due to out-of-gas. State changes made during that transaction are reverted, although the gas already consumed is normally not refunded. A transaction can also fail because a contract explicitly reverts, because an assertion fails, or because a called operation fails. Gas performs three important functions: - Metering: it prices computation and state access.
- Termination: it prevents an infinite loop from running forever.
- Resource allocation: it limits the amount of work included in a block.
Gas does not guarantee that a transaction will be included quickly. Inclusion also depends on network congestion, fee bidding, block capacity and transaction ordering. A basic fee exampleSuppose a transaction consumes 85,000 gas. The base fee is 22 gwei and the priority fee is 2 gwei. The effective price is 24 gwei. Fee = 85,000 × 24 gwei = 2,040,000 gwei = 0.00204 ETH This calculation assumes the transaction is included at the stated effective price and does not include a separate refund or application-level charge. 2. Measuring Gas and PerformanceOptimization should begin with measurement rather than intuition. A useful measurement process has four stages: - Define representative workloads.
- Execute them in a controlled development or test environment.
- Record gas use, latency and failure behaviour.
- Compare alternatives using repeatable tests.
A single gas number is often misleading. A function may have different costs for an empty state, a populated state, a first write, a repeated write, a successful call and a reverting call. Measurements should therefore cover normal, boundary and adversarial inputs. Important metrics include: | Metric | Meaning | Typical use |
|---|
| Gas used | Resources consumed by a transaction | Fee estimation and optimization | | Gas limit | Maximum gas permitted | Failure prevention | | Latency | Time from submission to inclusion or finality | User experience | | Throughput | Transactions or state transitions per unit of time | Capacity planning | | Failure rate | Proportion of reverted or rejected transactions | Reliability | | Data availability cost | Cost of publishing transaction or batch data | Rollup economics | | Storage footprint | Persistent state occupied by the contract | Long-term cost and state growth |
Development tools can report gas snapshots, opcode traces and storage accesses. Unit tests should verify state correctness, while integration tests should measure interactions among contracts. Profiling should not replace security review: an apparently cheap change may alter authorization, accounting or upgrade behaviour. Gas estimation and uncertaintyA node’s gas estimate is a simulation based on current state and supplied transaction parameters. It can become inaccurate when: - another transaction changes the state first;
- the function has data-dependent loops;
- an oracle or external call changes its result;
- the transaction is expected to revert under some conditions;
- access-list or network-specific rules differ.
Applications should use a safety margin, but an unnecessarily large gas limit can reduce usability and obscure inefficient design. Estimation is a prediction, not a guarantee. 3. Where Gas Is Spent3.1 StoragePersistent contract storage is expensive because it must be replicated and retained by network participants. A storage write is generally more expensive than reading a value from memory or calldata. Storage is appropriate for information that must survive between transactions, but it should not be used as a general-purpose log or temporary workspace. The following practices are often effective: - Keep only essential state on-chain.
- Use events for historical information that does not need contract-level reading.
- Pack compatible small variables into the same 32-byte storage slot where this does not make code confusing or unsafe.
- Avoid writing a value when it is already equal to the desired value.
- Delete obsolete state when protocol economics and refund rules make this useful.
- Use mappings for keyed access instead of scanning long arrays.
Storage packing is not universally beneficial. Reading or writing one packed field may require a read-modify-write operation. Variables that are frequently updated independently may be cheaper or safer in separate slots. 3.2 Memory and calldataFunction parameters supplied from outside the contract are commonly placed in calldata. Calldata is read-only and is often cheaper than copying data into memory. Memory is temporary and is cleared after execution. It is useful for calculations, arrays and encoded data, but expanding memory increases cost. For external functions, using calldata for read-only reference parameters can avoid unnecessary copying. However, the compiler and ABI rules must be understood; a change should be verified by measurement rather than assumed to be cheaper. 3.3 Computation and loopsA loop whose length depends on user-controlled input creates both cost and denial-of-service risks. If the loop cannot finish within the block gas limit, the function becomes unusable. Safer designs include: - bounded loops;
- pagination;
- pull-based withdrawals;
- incremental processing across multiple transactions;
- off-chain computation with on-chain verification.
Replacing a loop with a mapping may improve lookup cost, but it may also remove ordering or enumeration capabilities. If enumeration is needed, an indexed event or off-chain indexer may be more suitable than a contract-side scan. 3.4 External callsCalls to other contracts introduce gas, failure and security concerns. They may trigger re-entrancy, return unexpected data, consume substantial gas or depend on a changing external state. The checks-effects-interactions pattern remains useful: validate conditions, update internal state, and only then make external interactions. Re-entrancy guards and pull-payment designs may provide additional protection. Low-level calls should check their success result. A gas optimization that suppresses an error can create silent loss of funds or inconsistent accounting. 4. Optimization Without Sacrificing CorrectnessA professional optimization process follows this order: - Specify correctness: define invariants, authorization rules and acceptable failure behaviour.
- Measure a baseline: record gas for representative calls.
- Identify the dominant cost: storage, computation, calldata, external calls or deployment.
- Change one design element: keep comparisons meaningful.
- Run functional, security and property-based tests.
- Re-measure under several states.
- Document the trade-off.
An invariant is a condition that must remain true. For a token contract, examples include conservation of balances, authorized minting and consistency between total supply and account balances. Optimization is acceptable only if these properties continue to hold. Common techniquesUse events appropriately. Events are efficient for communicating historical facts to off-chain systems, but contracts cannot generally query event history as if it were storage. Critical data required for future contract execution must remain in state. Avoid redundant writes. A function should compare a new value with the existing value where doing so reduces unnecessary storage operations and does not introduce a harmful extra read. Choose data structures deliberately. Mappings offer efficient keyed access but do not provide native enumeration. Arrays preserve order but can become expensive to scan. Struct packing can reduce slots, while packed data may complicate upgrades and maintenance. Prefer custom errors where appropriate. Custom errors can reduce deployment and revert-data costs compared with long revert strings, while retaining useful failure information. Optimize deployment separately. Contract bytecode contributes to deployment cost and may affect code-size limits. Libraries, minimal proxies and modular architectures can reduce repeated deployment, but they introduce operational and upgrade dependencies. Do not use unsafe arithmetic shortcuts. Unchecked arithmetic can save gas when bounds have been proven, but it is appropriate only when overflow and underflow are impossible or intentionally handled. The proof should be explicit in the design and tests. 5. Batching and Application-Level ScalingBatching combines several logical operations into one transaction. A batch can reduce repeated transaction overhead and provide atomicity: either all operations succeed or the entire transaction reverts, subject to the contract’s implementation. Examples include: - transferring tokens to many recipients;
- settling multiple trades;
- processing a queue of claims;
- updating multiple records;
- aggregating signatures or approvals.
Batching has limits. The total work must fit within the block gas limit. A batch that always reverts because one item is invalid may provide poor user experience. Designs can choose between all-or-nothing execution and partial success with per-item status reporting. Partial success requires careful accounting and clear event formats. A batch also concentrates risk. One malformed input, malicious recipient or unexpectedly expensive operation can affect every participant. Batches should use bounded sizes, predictable validation and, where needed, resumable processing. 6. The Scalability ProblemA blockchain’s capacity is constrained by execution, data publication, propagation and consensus. A rough average throughput estimate is: Throughput ≈ Block gas capacity ÷ Average gas per transaction ÷ Block interval The units are transactions per second when block gas capacity is measured in gas, average transaction cost in gas per transaction, and block interval in seconds. This is an approximation. It assumes a stable workload and ignores transaction variance, consensus overhead, uncle or reorganization effects, data limits and scheduling inefficiencies. For example, if a network permits 30,000,000 gas per block, the average transaction uses 150,000 gas, and blocks arrive every 12 seconds: Throughput ≈ 30,000,000 ÷ 150,000 ÷ 12 ≈ 16.67 transactions per second This is capacity under the stated workload, not a universal network TPS value. A simple transfer and a complex DeFi transaction consume different amounts of gas. Scalability has several dimensions: - Execution scalability: how much computation can be processed.
- Data scalability: how much transaction data can be published and retained.
- State scalability: how much persistent state nodes must manage.
- Consensus scalability: how many participants can validate without excessive communication.
- User scalability: whether fees, wallets and confirmation times remain usable.
7. Layer 2 and Other Scaling Architectures7.1 Layer 2 networksA Layer 2 (L2) executes transactions away from the base layer while using the base layer for settlement, dispute resolution, data publication or security anchoring. The exact trust model differs by design. Users must understand bridges, sequencers, withdrawal delays and data-availability assumptions. 7.2 State channelsState channels allow participants to exchange signed updates off-chain and settle a final state on-chain. They are efficient for repeated interactions among a known group, such as payments or games. Their limitations include capital or liquidity requirements, participant coordination and reduced suitability for open-ended applications. 7.3 SidechainsA sidechain is a separate blockchain connected to a main chain through a bridge or other mechanism. It may offer lower fees and faster confirmation, but its security may depend on a separate validator set, bridge committee or consensus system. A sidechain is not automatically as secure as the settlement chain. 7.4 Optimistic rollupsAn optimistic rollup executes transactions off-chain and publishes transaction data and a state commitment to a base layer. The result is treated as valid unless challenged during a dispute period. A fraud-proof system allows a challenger to demonstrate an invalid transition. Strengths include broad compatibility and relatively straightforward execution models. Limitations include challenge windows, sequencer dependence, bridge complexity and the need for data availability. 7.5 Zero-knowledge rollupsA zero-knowledge rollup publishes a state commitment and a cryptographic validity proof showing that the claimed state transition follows the protocol rules. “Zero-knowledge” does not necessarily mean that all transaction data is hidden; many systems publish data for availability while using proofs for validity. Strengths include fast cryptographic finality once the proof is accepted and strong validity guarantees. Limitations include proving cost, specialized circuits, implementation complexity, data costs and possible restrictions on supported computation. | Approach | Main security anchor | Typical advantage | Important limitation |
|---|
| Main-chain execution | Base-chain consensus | Simple trust model | High shared demand | | State channel | Participants plus settlement chain | Very low repeated cost | Limited participant model | | Sidechain | Separate validator or consensus set | Flexible capacity | Different security assumptions | | Optimistic rollup | Base chain plus fraud proofs | Compatibility and lower execution cost | Challenge period and availability requirements | | ZK rollup | Base chain plus validity proofs | Strong validity and fast proof-based settlement | Proving and engineering complexity |
8. Cross-Chain Systems and BridgesCross-chain applications transfer messages or representations of assets between independent networks. A bridge must answer three questions: - How is an event on chain A observed?
- How is its authenticity verified on chain B?
- How are replay, double-spending and failure handled?
Common designs use multisignature committees, light-client verification, optimistic verification or cryptographic proofs. A bridge that relies on a small signer group may be efficient but introduces concentration risk. A light-client bridge may reduce trust assumptions but require substantial verification logic and data. Cross-chain systems face distinctive risks: - replaying a valid message on multiple destinations;
- mismatched finality assumptions;
- chain reorganizations;
- token-supply inflation through incorrect minting;
- compromised relayers or validators;
- paused or unavailable destination contracts;
- inconsistent message ordering.
A robust bridge should use domain-separated message hashes, nonces, explicit source and destination identifiers, replay protection, rate limits, emergency controls and independent monitoring. Rate limits reduce maximum loss but do not eliminate the need for sound verification. 9. Evaluating Scalability Trade-offsThe phrase “scalability trilemma” commonly describes tension among decentralization, security and scalability. It is a useful heuristic rather than a strict mathematical law. Increasing throughput by requiring powerful hardware may reduce the number of people able to validate. Reducing validator requirements may increase the risk of collusion or weaken fault tolerance. Moving execution off-chain may improve capacity while adding bridge, sequencer or data-availability dependencies. A practical evaluation should include: | Dimension | Questions |
|---|
| Security | Who can invalidate, censor or steal value? What is the fault threshold? | | Availability | Can users recover or exit if an operator disappears? | | Finality | When is a transaction economically or cryptographically irreversible? | | Decentralization | How many independent entities can validate, sequence or challenge? | | Cost | Who pays execution, data and proof-generation costs? | | Performance | What are throughput, latency and worst-case gas requirements? | | Governance | Who can change contracts, parameters or emergency controls? | | Compliance | Are operators, assets or transactions subject to legal obligations? |
A system should be evaluated under failure, not only normal operation. Questions include: What happens if the sequencer stops? Can users submit transactions directly to the base layer? Can the bridge pause safely? Can data be reconstructed? Are upgrades transparent and subject to a timelock? 10. Applied Case: A Ticketing Platform Moving to an L2BackgroundThis illustrative case concerns a university event-ticketing platform that issues blockchain-based tickets. The original contract stores each ticket, records transfers and checks eligibility on the base chain. During popular events, fees rise and users experience failed purchases. ProblemThe contract uses a loop to mint tickets individually, stores descriptive metadata on-chain and performs several repeated checks for each ticket. A 20-ticket purchase consumes approximately 2,400,000 gas in the measured test state. The contract also risks exceeding the block gas limit for larger purchases. AnalysisThe team identifies three dominant costs: repeated storage writes, metadata storage and per-transaction overhead. It also identifies correctness requirements: each ticket must have a unique identifier, total supply must not exceed the event capacity, unauthorized transfers must fail, and users must be able to withdraw or prove ownership if the operator is unavailable. ApproachThe team adopts four changes: - Store only ownership, event identifier and essential status on-chain; place images and descriptive metadata in content-addressed off-chain storage.
- Use bounded batch minting with an explicit maximum batch size.
- Emit events for ticket creation and transfer so indexers can reconstruct user-facing history.
- Deploy the application on an optimistic rollup while retaining a base-layer escape and settlement path.
The batch function validates the complete request before updating state. It uses a monotonic identifier counter and checks that the final identifier cannot exceed the event’s maximum supply. It rejects duplicate recipient data where duplicates would violate the business rule. The team tests successful purchases, invalid quantities, reverts, re-entrancy attempts, unavailable metadata, sequencer downtime and withdrawal procedures. OutcomeIn the measured workload, the average cost falls from 2,400,000 gas to 620,000 gas for 20 tickets. This is a reduction of: Reduction = (2,400,000 − 620,000) ÷ 2,400,000 × 100% ≈ 74.17% The result is workload-specific and should not be generalized to every network. The L2 further reduces the user’s immediate fee, but the design now depends on rollup data availability, bridge operation and sequencer reliability. The platform therefore publishes an operational policy describing withdrawal times, emergency procedures, upgrade authority and metadata persistence. Learning pointsThe largest improvement came from changing what must be stored and how work is grouped, not from obscure opcode tricks. Measurement was essential, and the team treated security, availability and governance as part of performance engineering. The L2 improved usability but did not remove trust or operational requirements. 11. Governance, Ethics and RegulationScalable systems can affect users who do not understand the underlying trust assumptions. Interfaces should disclose whether an asset is held on the base chain, an L2 or a sidechain; whether withdrawals are delayed; and who controls upgrades or emergency pauses. Centralized sequencers and bridge committees create accountability questions. Operators may be able to censor transactions, reorder them or observe sensitive activity. Fair ordering mechanisms, transparent policies and audit logs can reduce—but not automatically eliminate—these concerns. Regulatory obligations may arise in relation to custody, payments, securities, consumer protection, data protection and sanctions screening. Storing personal data permanently on a public ledger can conflict with privacy and deletion requirements. A sound design minimizes personal data on-chain and uses carefully governed off-chain systems where appropriate. 12. Contemporary Practice and Best PracticesCurrent engineering practice increasingly separates execution, settlement, data availability and user-facing services. Modular systems may allow one component to specialize in execution and another in data publication. This flexibility can improve performance but makes system boundaries and failure assumptions more complex. Best practices include: - establish gas budgets during requirements analysis;
- benchmark realistic and worst-case inputs;
- use bounded work and pagination;
- minimize persistent state while preserving required verifiability;
- test invariants and failure paths;
- document every trust assumption in bridges and L2s;
- monitor sequencer, relayer, proof and data-availability health;
- use multisignature controls and timelocks for sensitive administration;
- publish upgrade, pause and recovery procedures;
- treat compiler, library and network changes as performance and security events;
- avoid claiming “trustless” operation when users depend on privileged operators.
Chapter SummaryGas prices computation and state transition resources in blockchain systems. Transaction fees depend on gas used and the effective gas price, while gas limits bound execution. Storage, memory expansion, loops, external calls and deployment bytecode are important cost centres. Reliable optimization begins with representative measurement and must preserve authorization, accounting and security invariants. Batching can reduce repeated overhead but requires bounded work and clear failure semantics. Scalability must be assessed through execution, data, state, consensus and user dimensions. State channels, sidechains, optimistic rollups and zero-knowledge rollups provide different combinations of capacity, security and complexity. Cross-chain bridges introduce message-verification, replay and availability risks. A professional evaluation considers performance together with finality, decentralization, governance, recovery and regulatory responsibilities. Key TermsGas: Unit used to meter computation and state transitions. Gas limit: Maximum gas a transaction may consume. Gas price: Amount paid per unit of gas. Base fee: Protocol-determined portion of the transaction fee that is generally burned. Priority fee: Tip offered to the block proposer. Calldata: Read-only transaction input data supplied to a contract. Persistent storage: Contract state retained between transactions. Memory: Temporary execution area used during a transaction. Event: Log emitted for off-chain observation and indexing. Batching: Combining multiple logical operations into one transaction. Layer 2: System that executes or processes activity away from a base blockchain while using it for specified security or settlement functions. State channel: Off-chain protocol in which participants exchange signed state updates and settle on-chain. Sidechain: Separate blockchain connected to another chain through a bridge or related mechanism. Rollup: System that executes transactions away from the base layer and publishes commitments and supporting data or proofs. Optimistic rollup: Rollup that assumes a state transition is valid unless successfully challenged. Zero-knowledge rollup: Rollup that uses cryptographic validity proofs for state transitions. Data availability: Ability of relevant transaction data to be obtained and verified when needed. Sequencer: Component that orders transactions in many Layer 2 systems. Bridge: Protocol that transfers assets or messages between blockchain environments. Scalability trilemma: Heuristic describing tensions among scalability, security and decentralization. Review QuestionsShort Answer Questions- What is the relationship between gas used, gas price and transaction fee?
- Why is persistent storage generally more costly than memory?
- State two risks associated with unbounded loops.
- What is the primary difference between an optimistic rollup and a zero-knowledge rollup?
- Why does a sidechain not automatically provide the same security as its connected base chain?
Long Answer Questions- Explain a systematic process for measuring and optimizing gas while preserving contract correctness.
- Compare mappings, arrays, events and off-chain indexing as mechanisms for storing or exposing application data.
- Discuss how batching improves performance and identify its principal security and reliability limitations.
- Compare state channels, sidechains, optimistic rollups and zero-knowledge rollups in terms of security, cost and usability.
- Explain why scalability evaluation must include availability, decentralization, governance and recovery rather than throughput alone.
Analytical / Application Questions- A contract processes 40,000,000 gas per block, with a 10-second block interval. If the average operation uses 200,000 gas, estimate operations per second and explain why the estimate is only approximate.
- Design a bridge message format that prevents replay across source chains, destination chains and repeated nonces. Identify the fields and validation checks required.
- A ticketing application stores all metadata on-chain and mints tickets one at a time. Recommend an optimization and scaling plan, and explain the correctness, availability and governance trade-offs.
Multiple Choice Questions with AnswersQuestion 1A transaction uses 100,000 gas and has an effective gas price of 30 gwei. What is the transaction fee? A. 0.0003 ETH B. 0.003 ETH C. 0.03 ETH D. 3 ETH Correct Answer: B. 0.003 ETH Question 2Which resource is normally retained between transactions and therefore contributes to persistent state growth? A. Memory B. Calldata C. Storage D. The call stack Correct Answer: C. Storage Question 3What is a major danger of an unbounded user-controlled loop? A. It guarantees faster execution B. It may exceed the block gas limit and become unusable C. It automatically compresses storage D. It prevents all external calls Correct Answer: B. It may exceed the block gas limit and become unusable Question 4Which statement best describes batching? A. It combines multiple logical operations into one transaction B. It permanently removes all transaction fees C. It requires every operation to occur on a different chain D. It eliminates the need for validation Correct Answer: A. It combines multiple logical operations into one transaction Question 5An optimistic rollup generally treats a submitted state transition as valid unless what occurs? A. A successful fraud challenge B. A larger block is mined C. A storage slot is deleted D. A user changes wallets Correct Answer: A. A successful fraud challenge Question 6What is a principal advantage of a zero-knowledge rollup? A. It requires no cryptography B. It uses validity proofs to demonstrate correct state transitions C. It always stores all data privately D. It eliminates the need for data availability Correct Answer: B. It uses validity proofs to demonstrate correct state transitions Question 7A network has 30,000,000 gas per block, 12-second blocks, and 150,000 gas per transaction. What is the approximate capacity? A. 1.67 transactions per second B. 16.67 transactions per second C. 180 transactions per second D. 3,600 transactions per second Correct Answer: B. 16.67 transactions per second Question 8Which property is especially important when designing a cross-chain message? A. Replay protection B. Unlimited message repetition C. Ignoring destination-chain identity D. Removing all nonces Correct Answer: A. Replay protection Question 9Why can a sidechain have different security from its base chain? A. It may use a separate validator or consensus set B. It cannot execute smart contracts C. It always has zero transaction fees D. It is necessarily controlled by every base-chain validator Correct Answer: A. It may use a separate validator or consensus set Question 10Which approach best reflects professional gas optimization? A. Optimize first and test later B. Replace all storage with events regardless of requirements C. Measure representative workloads and re-test correctness after changes D. Use unchecked arithmetic in every function Correct Answer: C. Measure representative workloads and re-test correctness after changes
|