Smart Contracts

Chapter 9
Gas, Performance and Scalability

Diploma in Blockchain
Smart Contracts   •   Diploma

Gas, Performance and Scalability

Introduction

A 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 Objectives

By the end of this chapter, students should be able to:

  1. Explain gas, gas limits, gas prices and transaction fees.
  2. Measure contract execution and identify major gas-consuming operations.
  3. Optimize storage, computation and data structures without weakening correctness.
  4. Compare batching, state channels, sidechains, optimistic rollups and zero-knowledge rollups.
  5. Evaluate throughput, latency, finality, availability, security and decentralization.
  6. Select an appropriate scaling architecture for a practical application.
  7. Recognize governance, regulatory and operational risks in scalable smart-contract systems.

1. Gas as a Resource-Accounting System

The 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 example

Suppose 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 Performance

Optimization should begin with measurement rather than intuition. A useful measurement process has four stages:

  1. Define representative workloads.
  2. Execute them in a controlled development or test environment.
  3. Record gas use, latency and failure behaviour.
  4. 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:

MetricMeaningTypical use
Gas usedResources consumed by a transactionFee estimation and optimization
Gas limitMaximum gas permittedFailure prevention
LatencyTime from submission to inclusion or finalityUser experience
ThroughputTransactions or state transitions per unit of timeCapacity planning
Failure rateProportion of reverted or rejected transactionsReliability
Data availability costCost of publishing transaction or batch dataRollup economics
Storage footprintPersistent state occupied by the contractLong-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 uncertainty

A 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 Spent

3.1 Storage

Persistent 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 calldata

Function 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 loops

A 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 calls

Calls 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 Correctness

A professional optimization process follows this order:

  1. Specify correctness: define invariants, authorization rules and acceptable failure behaviour.
  2. Measure a baseline: record gas for representative calls.
  3. Identify the dominant cost: storage, computation, calldata, external calls or deployment.
  4. Change one design element: keep comparisons meaningful.
  5. Run functional, security and property-based tests.
  6. Re-measure under several states.
  7. 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 techniques

Use 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 Scaling

Batching 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 Problem

A 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 Architectures

7.1 Layer 2 networks

A 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 channels

State 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 Sidechains

A 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 rollups

An 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 rollups

A 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.

ApproachMain security anchorTypical advantageImportant limitation
Main-chain executionBase-chain consensusSimple trust modelHigh shared demand
State channelParticipants plus settlement chainVery low repeated costLimited participant model
SidechainSeparate validator or consensus setFlexible capacityDifferent security assumptions
Optimistic rollupBase chain plus fraud proofsCompatibility and lower execution costChallenge period and availability requirements
ZK rollupBase chain plus validity proofsStrong validity and fast proof-based settlementProving and engineering complexity

8. Cross-Chain Systems and Bridges

Cross-chain applications transfer messages or representations of assets between independent networks. A bridge must answer three questions:

  1. How is an event on chain A observed?
  2. How is its authenticity verified on chain B?
  3. 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-offs

The 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:

DimensionQuestions
SecurityWho can invalidate, censor or steal value? What is the fault threshold?
AvailabilityCan users recover or exit if an operator disappears?
FinalityWhen is a transaction economically or cryptographically irreversible?
DecentralizationHow many independent entities can validate, sequence or challenge?
CostWho pays execution, data and proof-generation costs?
PerformanceWhat are throughput, latency and worst-case gas requirements?
GovernanceWho can change contracts, parameters or emergency controls?
ComplianceAre 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 L2

Background

This 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.

Problem

The 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.

Analysis

The 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.

Approach

The team adopts four changes:

  1. Store only ownership, event identifier and essential status on-chain; place images and descriptive metadata in content-addressed off-chain storage.
  2. Use bounded batch minting with an explicit maximum batch size.
  3. Emit events for ticket creation and transfer so indexers can reconstruct user-facing history.
  4. 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.

Outcome

In 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 points

The 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 Regulation

Scalable 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 Practices

Current 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 Summary

Gas 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 Terms

Gas: 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 Questions

Short Answer Questions

  1. What is the relationship between gas used, gas price and transaction fee?
  2. Why is persistent storage generally more costly than memory?
  3. State two risks associated with unbounded loops.
  4. What is the primary difference between an optimistic rollup and a zero-knowledge rollup?
  5. Why does a sidechain not automatically provide the same security as its connected base chain?

Long Answer Questions

  1. Explain a systematic process for measuring and optimizing gas while preserving contract correctness.
  2. Compare mappings, arrays, events and off-chain indexing as mechanisms for storing or exposing application data.
  3. Discuss how batching improves performance and identify its principal security and reliability limitations.
  4. Compare state channels, sidechains, optimistic rollups and zero-knowledge rollups in terms of security, cost and usability.
  5. Explain why scalability evaluation must include availability, decentralization, governance and recovery rather than throughput alone.

Analytical / Application Questions

  1. 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.
  2. Design a bridge message format that prevents replay across source chains, destination chains and repeated nonces. Identify the fields and validation checks required.
  3. 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 Answers

Question 1

A 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 2

Which 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 3

What 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 4

Which 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 5

An 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 6

What 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 7

A 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 8

Which 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 9

Why 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 10

Which 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

Smart Contracts
Chapter 9 of 14