Persistent collections and store APIs
The SDK provides storage-backed data structures for contract state that is too large or too sparse to load as one serialized value. The current near_sdk::store APIs support lazy access and scalable updates, while the feature-gated near_sdk::collections APIs remain for legacy contracts and storage layouts. This page is a child of Smart contract SDK authoring; read Contract state and initialization for the wider state lifecycle.
Storage-backed data model
The collection APIs adapt Rust-like data access to NEAR's persistent key-value storage. They keep collection metadata in the contract state and keep collection elements under separate storage keys, so a method can touch only the data that it uses. The underlying storage boundary is part of the runtime surface described in Runtime environment and execution context.
Collection state boundary
The contract's top-level state contains the information needed to reopen each collection. The collection's elements remain in storage under keys derived from its namespace and the serialized key or index. This boundary prevents a large map or sequence from being read and written as one block with every contract call.
Store collections use Borsh for their state metadata and element data. They do not provide a general JSON representation of all elements, because materializing a large collection would defeat their storage model. A contract that exposes collection contents should read a bounded page through an iterator and return a normal response type; see Events, JSON, and contract types for the caller-facing data boundary.
References: near-sdk/…/mod.rs• L85-113 near-sdk/…/mod.rs• L78-91 near-sdk/…/mod.rs• L21-30
Storage namespaces
Every collection has a storage prefix that acts as its namespace. The prefix must be unique within the contract state, and it must remain stable when the contract reloads existing data. IntoStorageKey accepts byte prefixes and Borsh-serializable storage-key types; BorshStorageKey is the SDK-supported way to define named prefixes in contract code.
The key scheme is part of the stored-data contract. A changed prefix or key transform does not point to the old entries. Store maps and sets can use the built-in Identity, Sha256, or Keccak256 key transforms where the selected type supports them. Keep the choice stable for deployed state.
References: near-sdk/…/storage_key_impl.rs• L1-8 near-sdk/…/lib.rs• L1491-1521 near-sdk/…/key.rs• L14-22 near-sdk/…/key.rs• L24-76
Collection families
The families differ by the access pattern they make efficient. Choose the smallest family that matches the contract's reads, writes, and iteration needs rather than treating all collections as interchangeable.
Single-value storage
Lazy<T> stores one required value at a named key, while LazyOption<T> stores one optional value and represents None by the absence of a storage entry. A missing entry reloads as None for LazyOption, while reading a missing Lazy value is an error. Both load at most once per in-memory instance and are useful when a value is large or rarely used.
These types fit fields such as infrequently read metadata or large blobs. Lazy::remove deletes its entry and clears its local value, so a later drop or flush does not restore the removed value. Setting LazyOption to None also deletes its entry. These types do not replace ordinary fields when the value is small and used on most calls, because ordinary fields are simpler to load with the rest of the contract state.
References: near-sdk/…/mod.rs• L1-5 near-sdk/…/mod.rs• L67-71 near-sdk/…/mod.rs• L142-151 near-sdk/…/mod.rs• L12-18 near-sdk/…/mod.rs• L80-100
Sequence storage
store::Vector<T> provides a growable, index-based sequence whose values are persisted separately and loaded when accessed. It is the usual choice for ordered records, bounded lists, and paged results. Index access does not require loading all earlier values.
The sequence supports iteration and removal operations that may change order. A contract must not assume that removal preserves order when it uses swap-based removal. Use a stable ordering scheme in the contract when order is part of the product behavior.
References: near-sdk/…/mod.rs• L126-130 near-sdk/…/mod.rs• L1-4 near-sdk/…/mod.rs• L78-91 near-sdk/…/mod.rs• L340-369
Map storage
Maps associate serialized keys with values. The choice is mainly about whether the contract needs to enumerate entries and whether it needs sorted access.
| API | Contract role |
|---|---|
LookupMap | Key lookup, insert, update, and removal without iteration. |
IterableMap | Key-value iteration in arbitrary order, plus keys and values views. |
TreeMap | Key-value iteration and ranges in sorted key order. It is available behind the unstable feature. |
UnorderedMap | Legacy iterable behavior with fast reuse of removed slots. It is deprecated because repeated removals can make iteration costly. |
IterableMap is the general current choice when a map must be listed. LookupMap is a better fit when callers always know the key and enumeration is not required. Use TreeMap only when ordered or range access is a real contract requirement. Store UnorderedMap is retained for compatibility, not as the default for new state.
References: near-sdk/…/mod.rs• L21-30 near-sdk/…/mod.rs• L24-34 near-sdk/…/mod.rs• L25-32 near-sdk/…/mod.rs• L24-40
Set storage
Sets store membership rather than a value for each key. LookupSet supports membership checks and changes without iteration. IterableSet supports arbitrary-order iteration and set operations such as union, intersection, and difference.
Store UnorderedSet is the deprecated iterable form. It favors removal and slot reuse, but many deletions without later inserts can leave iteration work behind. Use IterableSet for new iterable state unless a deployed layout requires the older type.
References: near-sdk/…/mod.rs• L12-21 near-sdk/…/mod.rs• L19-34 near-sdk/…/mod.rs• L17-38
Persistence lifecycle
Store collections separate an in-memory view from the storage view. Reads can fill a cache, and mutations can remain pending until the collection is flushed or dropped. This gives a contract method a coherent local view while avoiding repeated storage writes.
The lifecycle moves data from persistent storage into a local view and sends only changed entries back to storage.
flowchart LR
A[Collection metadata] --> B[Open contract state]
B --> C[Read requested entries]
C --> D[Local view]
D --> E[Mutate entries]
E --> F{Flush or drop}
F --> G[Write changed entries]
G --> H[Persistent storage]
Lazy reads
A collection reads an element when the contract first asks for it. Later access uses the value already loaded by that collection instance. Iterators follow the same rule, so pagination can avoid loading entries outside the requested page.
The lazy behavior applies to store maps, sets, vectors, and single-value wrappers. LookupSet is the notable exception: its membership changes use storage directly rather than a deferred collection cache.
References: near-sdk/…/mod.rs• L16-23 near-sdk/…/index_map.rs• L93-112 near-sdk/…/mod.rs• L153-178 near-sdk/…/mod.rs• L108-142
Deferred writes
Most store collections mark changed entries and write them during flush. The SDK also calls flush from the collection's Drop implementation, so a normal method-local collection is persisted as its lifetime ends. Call flush when another operation must observe the storage changes before the collection is dropped.
Removal writes a deletion for the affected storage entry. A collection can therefore update only changed elements instead of rewriting its full contents. A failed or interrupted operation can leave collection metadata and element data out of sync; the SDK reports this as an inconsistent-state failure rather than silently returning wrong data.
The same deferred-write rule applies to Lazy and LazyOption. Their set operations change the local value first, while flush or drop makes the storage value match it. Lazy::remove deletes its storage entry immediately and clears the cached value, which prevents the later drop flush from resurrecting it. For LazyOption, a None value removes the entry and remains None after the wrapper is reloaded. A collection nested inside another collection must also be flushed directly; flushing only the outer collection does not persist the nested collection's pending element changes. Storage usage measurements likewise see pending writes only after the relevant collection is flushed. For a cross-contract sequence, keep state timing in mind with Promises and cross-contract calls.
References: near-sdk/…/mod.rs• L16-23 near-sdk/…/mod.rs• L63-83 near-sdk/…/mod.rs• L106-115 near-sdk/…/mod.rs• L427-459 near-sdk/…/mod.rs• L124-149 near-sdk/…/mod.rs• L80-100
State round trips
The #[near(contract_state)] contract wrapper reads the contract state before a method and writes it after a mutating method. Store collection metadata survives this round trip, while the collection's pending element changes are flushed as the collection leaves the method's scope. The macro and state boundary are described in Contract interface macros and Contract state and initialization.
A collection instance is therefore not a portable snapshot of all its values. Borsh serialization preserves the metadata needed to reopen the storage-backed structure. Do not use a store collection as a method return value when the caller expects its elements.
References: near-sdk/…/lib.rs• L195-228 near-sdk/…/lib.rs• L1220-1257 near-sdk/…/mod.rs• L88-113
Contract selection
The contract's data access pattern determines the collection family. The following choices cover the main product-level cases without requiring knowledge of the internal storage layout.
Access patterns
| Contract need | Recommended abstraction |
|---|---|
| One large value that is not read on every call | Lazy<T> |
| One optional value with an absent state | LazyOption<T> |
| Membership or key lookup only | LookupSet or LookupMap |
| A sequence with indexed access or pagination | Vector |
| An iterable map or set with frequent removal and iteration | IterableMap or IterableSet |
| Sorted iteration or key ranges | TreeMap with the unstable feature |
| Existing deployed state using an older layout | The matching legacy or deprecated type until a planned migration |
For small, always-used values, a normal contract field can be simpler. For modest collections, a native Rust collection can also be acceptable when its full load cost is small. The store module becomes more valuable as the data grows because a native collection in top-level state is loaded and saved as one serialized value.
References: near-sdk/…/mod.rs• L10-14 near-sdk/…/mod.rs• L63-86 near-sdk/…/mod.rs• L102-136 near-sdk/…/lib.rs• L171-224
Compatibility choices
near_sdk::collections is the older collection module and is exported only with the legacy feature. Its APIs write individual changes directly to storage and use older layouts. The current near_sdk::store module has a closer Rust collection API and adds caching, but equal type names do not guarantee equal serialized metadata or element keys.
Treat a collection type, prefix, key transform, and element serialization as one storage contract. A replacement can need a migration even when the new type has similar methods. In particular, changing between the legacy vector and store::Vector requires re-keying the stored elements because their index suffix formats differ. The legacy vector exposes to_v2 for that migration when the unstable feature is enabled.
References: near-sdk/…/mod.rs• L1-12 near-sdk/…/lib.rs• L1598-1601 near-sdk/…/vector.rs• L58-95 near-sdk/…/mod.rs• L114-127
Change checklist
When these files or sections are changed, remember to consider these:
- A collection prefix or key transform change can hide all existing entries. Check deployed-state compatibility before changing either value.
- A change from a non-iterable collection to an iterable one changes the storage contract and can require a migration. Do not infer compatibility from matching Rust method names.
- A change from legacy
collections::Vectortostore::Vectormust account for the old and new index-key widths. Use the supported migration path instead of reusing the prefix blindly. - A new paginated view must preserve the collection's ordering promise.
IterableMapandIterableSetare arbitrary-order views, whileTreeMapis sorted. - A method that needs storage changes visible before collection drop must call
flush; this matters at boundaries with asynchronous workflows described in Promises and cross-contract calls. - Removing a
Lazyvalue must account for its required-value contract: after removal, later reads fail because the value is absent. UseLazyOptionwhen absence is a valid state. - Treat
LazyOption::Noneas a deleted storage entry when checking reload behavior or migrating state. A missing entry must remain a valid optional state. - When measuring storage usage or flushing a nested collection, flush the collection whose pending entries are being measured or persisted. An outer collection flush does not flush its nested values.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Two collections share a prefix or use a reused derived prefix | One collection can read, replace, or remove another collection's entries | Give every collection a stable, unique BorshStorageKey variant or byte prefix. |
| A contract changes a collection type or key transform without migration | Existing values become unreachable or metadata no longer matches the stored entries | Treat the type, prefix, transform, and serialized element type as a versioned storage contract. |
| A store collection is used as if it were fully serialized state or a JSON return value | The caller receives metadata rather than the collection's elements, or a large load is forced | Return a normal page type and iterate only the requested range. |
A removed required Lazy value is read again | The read fails because Lazy has no value after its storage entry is deleted | Use LazyOption for values that can be absent, or restore the value before reading it. |
| A deprecated unordered collection accumulates removals and is iterated | Gas use can grow with stale slots even when the live set is small | Prefer the iterable replacement for new state, or compact the old collection during a safe maintenance call. |
| A vector or map companion structure becomes inconsistent after an interrupted update | The SDK panics with an inconsistent-state error instead of trusting corrupt indexes | Keep related collection updates in one atomic contract action and do not bypass the collection API. |
| An outer collection is flushed while a nested collection still has pending changes | The nested elements are not persisted, or storage usage under-reports the pending change | Flush the nested collection directly before relying on its persisted state or measuring storage. |
Key files
| File | Why to read it |
|---|---|
| near-sdk/…/mod.rs | Defines the storage-backed model, persistence timing, collection families, and public exports. |
| near-sdk/…/mod.rs | Shows the non-iterable key-value role and the common lazy-cache and flush contract. |
| near-sdk/…/mod.rs | Shows the iterable map role and the relationship between lookup and enumeration. |
| near-sdk/…/mod.rs | Shows iterable membership and set-operation behavior. |
| near-sdk/…/mod.rs | Shows indexed storage, lazy element access, pagination support, and deferred persistence. |
| near-sdk/…/mod.rs | Defines the single-value lazy storage abstraction, required-value semantics, and safe removal behavior. |
| near-sdk/…/mod.rs | Defines optional lazy storage, deletion on None, and reload behavior for an absent value. |
| near-sdk/…/key.rs | Defines the stable key-generation choices used to address stored map and set entries. |
| near-sdk/…/mod.rs | Explains the legacy module and its relationship to the current store APIs. |
| near-sdk/…/vector.rs | Documents the legacy vector layout and the supported path to the current vector type. |
| near-sdk/…/store_performance_tests.rs | Compares the public collection families across insertion, removal, iteration, lookup, and membership workloads. |