Why this distinction matters

Every byte written to storage is expensive and permanent. Every event emitted is cheaper, but it is not readable by other contracts and cannot be used as on-chain state. Choosing the wrong mechanism can lead to unnecessary gas costs, awkward contract design, or brittle off-chain integrations.

A useful mental model is:

  • Storage is for authoritative contract state.
  • Events are for durable, queryable history.
  • Neither should be used for secrets or privacy-sensitive data.

If your contract needs to make a decision in a future transaction, the data must be in storage. If the data is only needed for analytics, notifications, or UI updates, an event is usually the better choice.


Storage and events solve different problems

MechanismOn-chain readable by contractsQueryable by off-chain systemsGas costBest for
StorageYesYes, via RPC readsHighCurrent balances, ownership, configuration
Event logsNoYes, via indexers and RPC filtersLowerHistory, audits, notifications, activity feeds

A common mistake is storing data “just in case.” If the contract never needs to read it later, storage is usually wasteful. Another mistake is relying on events for critical logic. Events are not part of contract state and cannot be accessed by Solidity code after they are emitted.


When to store data

Use storage when the contract must enforce rules based on the value later.

Typical examples include:

  • token balances
  • ownership records
  • whitelist or role membership
  • protocol configuration
  • escrow balances
  • order status
  • nonces used for replay protection

Example: state that must persist

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract Escrow {
    address public immutable payer;
    address public immutable payee;
    uint256 public amount;
    bool public released;

    constructor(address _payee) payable {
        payer = msg.sender;
        payee = _payee;
        amount = msg.value;
    }

    function release() external {
        require(msg.sender == payer, "not payer");
        require(!released, "already released");

        released = true;
        (bool ok, ) = payee.call{value: amount}("");
        require(ok, "transfer failed");
    }
}

Here, released must be stored because the contract needs to prevent double release. An event alone would not be enough, because the next call must inspect the current state.


When to emit events

Use events when the data is useful for off-chain consumers but not needed for future contract execution.

Typical examples include:

  • deposits and withdrawals
  • role changes
  • order creation and cancellation
  • governance votes
  • metadata updates
  • bridge messages
  • user activity feeds

Events are especially valuable when you want a lightweight audit trail. Indexers such as The Graph, custom ETL jobs, or backend services can subscribe to logs and build application-specific views without forcing the contract to store redundant data.

Example: event-driven observability

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract Vault {
    mapping(address => uint256) public balances;

    event Deposited(address indexed account, uint256 amount, uint256 newBalance);
    event Withdrawn(address indexed account, uint256 amount, uint256 newBalance);

    function deposit() external payable {
        balances[msg.sender] += msg.value;
        emit Deposited(msg.sender, msg.value, balances[msg.sender]);
    }

    function withdraw(uint256 amount) external {
        require(balances[msg.sender] >= amount, "insufficient balance");

        balances[msg.sender] -= amount;
        emit Withdrawn(msg.sender, amount, balances[msg.sender]);

        (bool ok, ) = msg.sender.call{value: amount}("");
        require(ok, "transfer failed");
    }
}

The contract still stores balances because it must enforce withdrawals. But the events make it easy for a frontend to show a transaction history and current balance changes without repeatedly diffing raw storage.


Design rule: store the minimum needed for correctness

A good optimization strategy is to store only the data required for future validation, and emit the rest.

For example, suppose a marketplace wants to record orders. You might be tempted to store full order details on-chain:

  • seller
  • buyer
  • item metadata
  • price
  • timestamp
  • status
  • shipping notes

In many cases, only a subset is needed on-chain:

  • seller
  • price
  • status
  • order nonce

The rest can be emitted in an event and indexed off-chain.

Practical pattern

  • Store identifiers and state transitions.
  • Emit descriptive metadata in events.
  • Avoid duplicating the same information in both places unless there is a clear reason.

This reduces gas costs and keeps storage layout simpler.


Indexed topics: make events searchable

Events can include up to three indexed parameters in addition to the event signature topic. Indexed fields are stored in topics, which makes them efficient to filter by RPC clients and indexers.

Use indexed for values you expect to search frequently:

  • user addresses
  • token IDs
  • order IDs
  • proposal IDs
  • asset addresses

Example: searchable event design

event OrderCreated(
    uint256 indexed orderId,
    address indexed seller,
    address indexed asset,
    uint256 price
);

This lets off-chain systems query by orderId, seller, or asset efficiently. The tradeoff is that indexed values are less convenient to decode as plain data in some contexts, so only index fields that are genuinely useful for filtering.

Rule of thumb

Field typeIndex it?Reason
Address used in lookupsYesCommon filter key
Unique ID used in UI routesYesEasy retrieval
Large string or bytes metadataUsually noExpensive and rarely filterable
Numeric status codeSometimesUseful if it drives analytics

Avoid using events as a source of truth

Events are not accessible to Solidity code. A contract cannot ask, “Did this event happen?” or “What was the last emitted value?” If your logic depends on a value, it must be stored.

This matters in several scenarios:

  • Access control: you cannot grant permissions by emitting an event.
  • Accounting: you cannot compute balances from logs inside the contract.
  • Replay protection: you cannot rely on event history to block repeated signatures or actions.
  • State transitions: the contract must store the current phase or status.

If you need a value for both on-chain logic and off-chain visibility, store it and emit it. That is often the right compromise.


A hybrid pattern: store state, emit snapshots

The most common production pattern is to store the minimum state and emit a rich event snapshot whenever that state changes.

Example: governance proposal lifecycle

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract Governance {
    enum ProposalStatus { None, Active, Passed, Rejected }

    struct Proposal {
        address proposer;
        uint64 startBlock;
        uint64 endBlock;
        ProposalStatus status;
    }

    mapping(uint256 => Proposal) public proposals;

    event ProposalCreated(
        uint256 indexed proposalId,
        address indexed proposer,
        uint64 startBlock,
        uint64 endBlock
    );

    event ProposalStatusChanged(
        uint256 indexed proposalId,
        ProposalStatus previousStatus,
        ProposalStatus newStatus
    );

    function createProposal(uint256 proposalId, uint64 votingPeriod) external {
        require(proposals[proposalId].status == ProposalStatus.None, "exists");

        uint64 start = uint64(block.number);
        uint64 end = start + votingPeriod;

        proposals[proposalId] = Proposal({
            proposer: msg.sender,
            startBlock: start,
            endBlock: end,
            status: ProposalStatus.Active
        });

        emit ProposalCreated(proposalId, msg.sender, start, end);
    }

    function setStatus(uint256 proposalId, ProposalStatus newStatus) external {
        Proposal storage p = proposals[proposalId];
        require(p.status != ProposalStatus.None, "missing");

        ProposalStatus old = p.status;
        p.status = newStatus;

        emit ProposalStatusChanged(proposalId, old, newStatus);
    }
}

The storage mapping ensures the contract can enforce lifecycle rules. The events allow an indexer or frontend to reconstruct the proposal timeline without repeatedly reading storage.


Gas and design tradeoffs

Storing data is expensive because every new storage slot costs significant gas. Updating existing slots is cheaper, but still more expensive than emitting logs. Events are generally the better choice for append-only history.

However, events are not free. Large event payloads increase transaction cost, and excessive logging can make indexing and client processing more complex.

Practical tradeoffs

  • Use storage for mutable state that affects future execution.
  • Use events for append-only history and UI updates.
  • Avoid logging huge blobs of data unless there is a strong operational reason.
  • Prefer compact types such as uint64 or uint128 when they fit the domain.
  • Do not duplicate the same large payload in both storage and events unless necessary.

A good question to ask is: “If I removed this data from storage, would the contract still be correct?” If yes, emit it instead.


Common anti-patterns

1. Storing data only for analytics

If the data is never used by the contract, storing it is usually wasteful. Emit an event instead.

2. Emitting data that must be enforced later

If future logic depends on it, storing only an event is incorrect. The contract will not be able to read it back.

3. Duplicating large metadata in both places

This increases gas and makes upgrades harder. Store a compact identifier and emit the full descriptive payload if needed.

4. Treating events as privacy-preserving

Events are public. Anyone can read them from the chain. Do not emit secrets, private keys, or sensitive business data.

5. Over-indexing every field

Index only what you need for filtering. Too many indexed fields reduce flexibility and can make event schemas harder to evolve.


Best practices for production contracts

  • Keep authoritative state in storage.
  • Emit events for every meaningful state transition.
  • Index the fields that off-chain systems will query most often.
  • Use events to support UX, analytics, and monitoring.
  • Keep event schemas stable once external systems depend on them.
  • Document which storage variables are required for correctness and which events are informational.
  • Review whether each new storage slot is truly necessary.

A useful development habit is to design the event schema alongside the storage schema. That prevents later refactors where the contract state is correct but the off-chain observability is poor, or vice versa.


A simple decision checklist

Before adding a variable, ask:

  1. Does the contract need this value to make future decisions?
  2. Must other contracts be able to read it?
  3. Is it only needed for dashboards, alerts, or analytics?
  4. Can it be derived from other stored values?
  5. Would an event be enough?

If the answer to 1 or 2 is yes, store it. If the answer is mainly 3, emit it. If the value is derivable, consider not storing it at all.


Conclusion

In Solidity, storage and events are complementary tools, not interchangeable ones. Storage gives your contract durable, enforceable state. Events give the outside world a reliable history of what happened. The best designs use storage sparingly and events intentionally, with each piece of data placed where it provides the most value.

When you separate correctness from observability, your contracts become cheaper, easier to index, and simpler to integrate with real-world applications.

Learn more with useful resources