Zero-copy accounts
Suggest an editAnchor'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.
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:
// 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.
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:
{
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.
#[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
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.