Geth snapshot design cuts Ethereum state reads to one database lookup

Geth snapshot design cuts Ethereum state reads to one database lookup

Geth developer Péter Szilágyi outlined how the client’s snapshot structure accelerates Ethereum state reads in a blog post published on 17 July 2020. The optional feature stores accounts and contract storage in a flat key-value format alongside the Merkle Patricia tree used to verify state.

Ethereum state consists of account data, such as balances and nonces, and storage slots belonging to contracts. The Merkle Patricia tree organises that data so changes can be verified without hashing the entire state. Its cost is that accessing an item requires traversing tree nodes stored on disk.

A faster route for reads

A faster route for reads

Szilágyi said a typical account-trie operation at the time touched at least seven or eight internal nodes. Each access could translate into 25 to 50 random disk operations after accounting for LevelDB’s own structure. The overhead multiplies across the state reads and writes made while processing transactions.

Geth’s snapshot provides a separate route for retrieving data already represented in the state tree. It presents a complete view of state at a particular block as a flat key-value store, reducing a lookup to one LevelDB access rather than seven or eight trie lookups. The trade-off is extra work for writes and additional disk use.

The snapshot does not replace the Merkle Patricia tree, which remains necessary for state verification and updates. Instead, it lets the client avoid repeatedly traversing the trie for reads. Szilágyi described the resulting read complexity as falling from O(log n) to O(1), before LevelDB overhead.

Managing recent changes and reorganisations

Managing recent changes and reorganisations

A flat store alone cannot easily undo persistent writes when the chain reorganises. Geth’s design therefore pairs a disk snapshot of an older block with in-memory diff layers that hold changes from subsequent blocks. Reads search from the newest layer backwards, then consult the disk layer if needed.

Those layers also let Geth handle reorganisations shallower than 128 blocks by returning to the diff layer associated with the parent block. They provide access to 128 recent states, although searching through the layers adds memory lookups. A deeper reorganisation requires the snapshot to be discarded and regenerated.

Szilágyi reported that the structure made read-based denial-of-service attacks about an order of magnitude harder and could make eth_call requests about an order of magnitude faster when they were not limited by CPU. After initial sync, building the first mainnet snapshot took around nine to ten hours and required more than 15 GB of additional disk space. The feature remained behind Geth’s --snapshot flag, with memory use and crash recovery still needing refinement.