Sign in

Zero-copy accounts

Suggest an edit

Anchor's default Account<'info, T> deserializes the entire account into a Rust struct on the stack at the start of every handler, then serializes the struct back to the account at the end. For small accounts this is fine. For large accounts it is the bottleneck: the struct does not fit on the stack, compute units go to copying bytes, and code size grows from monomorphization. With zero-copy you point a struct at the raw bytes and work in place.

The default copies the whole account on every call

On Ethereum a contract reads and writes its storage one 32-byte word at a time and pays gas only for the words it touches. A Solana program receives each account as one buffer of bytes, and Anchor's default is to copy all of it.

The default Anchor account treatment is a value type. When the handler runs, the framework reads the account's bytes, deserializes them into a freshly constructed T, and gives you a &mut T pointing at that struct. The struct lives on the stack, or on the heap if you wrap it in Box. At the end of the handler, the struct is serialized back into the account's data buffer.

This is convenient, and it gets expensive in three ways when the struct gets large.

The stack has a hard limit. Each Solana instruction handler runs with a stack frame around 4 KB. A T that's 5 KB or 10 KB can't physically fit. The program won't even compile in some cases, and when it does compile, it can stack overflow at runtime. The error message is unhelpful and the cause is non-obvious.

Compute units burn on the copy. Every byte deserialized and re-serialized costs CU. For a small account that's a few dozen CU you don't notice. For a 50 KB account it's tens of thousands of CU on every call, for nothing more than copying bytes you already have.

Code size grows from monomorphization. The serializer is generic. Every type Anchor sees produces another copy of the deserialize and serialize code in your binary. Ten different large account types make your program binary substantially larger, which costs deploy SOL and CU on every load.

For accounts under a kilobyte or two, none of this matters. It starts to matter above a few kilobytes.

Zero-copy gives the handler a pointer into the account's bytes

Zero-copy turns the account from a value type into a reference type. You don't get a copy of the data, you get a pointer into the data. Reads and writes happen against the original buffer, and there is no deserialize-then-serialize round trip.

Account<T> copy path vs AccountLoader<T> zero-copy pathTwo side-by-side flows show how an account becomes a Rust struct. Account<T> deserializes the on-chain bytes into a copied struct in the handler, then serializes it back, for two copies per call; AccountLoader<T> casts a pointer straight into the same buffer, so reads and writes hit the account data directly, for zero copies per call. How an account becomes a Rust struct Account<'info, T> (default) on chain: disc | field1 | field2 | ... raw bytes in the account deserialize, copy in handler: T { field1, field2, ... } owned struct on stack a copy of the bytes serialize, write on chain: disc | field1' | field2' | ... copy written back at end two copies per call AccountLoader<'info, T> (zero-copy) on chain: disc | field1 | field2 | ... raw bytes in the account cast pointer no copy in handler: RefMut<T> → the bytes view over account data writes hit the buffer directly drop guard on chain: already updated, no extra write zero copies per call Default deserializes onto the stack. Zero-copy hands you a pointer into the same buffer.

The price is a fixed layout

The runtime cannot cast a byte buffer to any Rust struct and trust the result. The cast only works if the struct's in-memory layout is identical to the on-chain byte layout. That means a known field order, no padding the compiler might insert, and no field that points to memory outside the struct. Such a struct is called Plain Old Data, or Pod.

Anchor expresses this through #[account(zero_copy)], which requires the bytemuck::Pod and bytemuck::Zeroable traits and enforces them at compile time. #[repr(C)] on the struct keeps the compiler from reordering fields. Every field has to be fixed-size and itself Pod: primitive integers, Pubkey, fixed-size arrays of Pod types, other #[repr(C)] structs of Pod fields. Vec, String, HashMap, references and enums with a payload do not compile. Neither does bool, because only bit patterns 0 and 1 are valid for it and Pod requires every bit pattern to be valid, so you store a u8 instead.

A zero-copy struct looks like this next to a regular one. The regular Config can hold a String because Anchor's serializer can handle it:

rust
// Regular account, fine for small/medium sizes
#[account]
pub struct Config {
    pub admin: Pubkey,
    pub name: String,        // OK here, expensive in zero-copy world
    pub fee_bps: u16,
}

// Zero-copy account, fixed layout
#[account(zero_copy)]
#[repr(C)]
pub struct OrderBook {
    pub market: Pubkey,
    pub head: u32,
    pub tail: u32,
    pub orders: [Order; 1000],   // fixed-size array, fine
}

#[zero_copy]
#[repr(C)]
pub struct Order {
    pub owner: Pubkey,
    pub price: u64,
    pub size: u64,
}

You can't have a dynamically-sized message field or a Vec of orders that grows. Every collection has a fixed capacity that you commit to up front, and you manage the count yourself with a head, tail, or len field.

Zero-copy fits large accounts on a hot path

An account that wants zero-copy is big, holds mostly fixed-shape data, and is touched often, in performance-sensitive paths: an order book, a match buffer, a large bitmap for an allowlist, a large array of positions in a perps protocol, a ring buffer for time series.

An account that does not want zero-copy is the opposite: small, with variable-length text or metadata fields where a String is natural, and modified rarely. The Config account in any program almost always stays on Account<T> because it's small and the convenience of having String fields is worth more than the copy cost on the rare update.

In code

Zero-copy accounts are reached through AccountLoader<'info, T>, not Account<'info, T>. The loader hands out borrows of the account's bytes through three methods.

Three ways to open a zero-copy account: load_init, load, load_mutCompares AccountLoader's three methods: load_init() runs once to create the account and returns exclusive write access, load() gives shared read-only access, and load_mut() gives exclusive write access. A bottom panel states the borrow rule: only one load_mut() can be active at a time, enforced at runtime by RefCell. Three ways to open a zero-copy account load_init() when: once, in the instruction that creates the account returns: RefMut<T> (exclusive write access) does: writes the discriminator, zeros the buffer, hands you the slab required for the first access. load() and load_mut() fail before this runs. load() when: you only need to read returns: Ref<T> (shared read access) borrows: many at once is fine cheap, read-only access load_mut() when: you need to write returns: RefMut<T> (exclusive write) borrows: only one at a time writes go straight to the bytes the borrow checker rule A second load_mut() on the same account while the first is alive panics at runtime. Limit the scope of the RefMut: take it, do the work, drop it, then anyone else can borrow. CPI calls that touch the same account need the borrow dropped before they fire. Three entry points. Rust's borrow rules apply, enforced at runtime by RefCell.

load() returns a Ref<T> and load_mut() returns a RefMut<T>. Each is a borrow that is released when the variable goes out of scope. Multiple read borrows can coexist. Write borrows are exclusive: only one load_mut() can be live for a given account at a time.

If you call a CPI while a RefMut is alive, and the called program tries to touch the same account, the runtime panics. The fix is to drop the borrow before the CPI:

rust
{
    let mut book = ctx.accounts.order_book.load_mut()?;
    book.orders[idx].size = new_size;
    // book is dropped at the end of this block
}
some_cpi_call(ctx.accounts.order_book.to_account_info(), ...)?;

Scope the RefMut to the smallest region that needs write access, and drop it before any CPI.

Box as the middle ground

If your account is too big for the stack but you don't want the Pod constraints, Box<Account<'info, T>> is the right answer. It uses the same serialization as the default, with the same String and Vec support, but the deserialized struct lives on the heap instead of the stack. The copy still happens on every call, so the CU cost stays, but for an account in the 2 KB to 8 KB range that is not in your hottest path that cost is manageable.

rust
#[derive(Accounts)]
pub struct UpdatePositions<'info> {
    #[account(mut, has_one = user)]
    pub state: Box<Account<'info, UserState>>,
    pub user: Signer<'info>,
}

Everything else, including the body of the handler, is unchanged. state.positions[0].size = new_size; works the same way it would for Account<'info, UserState>.

This is the option most programs reach for first when they hit a stack overflow. If Box<Account<T>> still gives unacceptable CU costs, then it's time to migrate to zero-copy and live with the Pod constraints.

Choosing between Account, Box, and zero-copy

Config, UserState, and OrderBook: Account<T>, Box<Account<T>>, or AccountLoader<T> by sizeThree columns compare accounts by size and Solana strategy: Config (120 bytes) uses the default Account<T>, UserState (~6 KB, 64 position slots) uses heap-allocated Box<Account<T>>, and OrderBook (48 KB, 1000 order slots) uses zero-copy AccountLoader<T> for large CU savings. Each column lists the account's fields and the reason for its strategy, and a footer notes that account size and call frequency drive the decision. Three accounts, three strategies Config size: 120 bytes fields: admin: Pubkey fee_bps: u16 paused: bool vault: Pubkey use: Account<T> the default why: tiny, copy cost is negligible. no reason to complicate. stays simple UserState size: ~6 KB fields: user: Pubkey positions: array of 64 slots where each slot is ~96 bytes use: Box<Account<T>> heap-allocated why: copy still cheap, but stack won't hold the struct. Box moves it to the heap. avoids stack overflow OrderBook size: 48 KB fields: market: Pubkey orders: array of 1000 slots where each slot is 48 bytes use: AccountLoader<T> zero-copy why: too large to copy on every call. work against the bytes in place. order-of-magnitude CU savings The size of the account is the first input. The hot-path call frequency is the second.

For 90% of accounts you'll write, the default Account<'info, T> is correct and you never think about this. The order is default → Box → zero-copy, and you only move to the next step when measurements force you to.

When you do reach for zero-copy, the struct's memory layout is your contract with the on-chain bytes, and you don't get to change it after deployment without a careful migration.