Account closure and realloc
Suggest an editSolana accounts are not garbage-collected. Every byte you allocate stays paid for forever, and the SOL locked for rent-exemption stays locked until someone explicitly reclaims it. Closing an account gives the SOL back and has to make sure nobody can revive the account and use it again. Resizing keeps the account alive but changes how many bytes it holds. Both are operations the default Anchor model does not perform automatically.
An unused account keeps its SOL locked until someone closes it
When you initialize an account, the runtime reserves space on chain and the payer locks SOL to cover the rent-exempt minimum for that size (lamports, rent, and account lifecycle). A typical 100-byte account locks about 1.6 million lamports. A 1 KB account locks roughly 8 million.
If a million users each create a 100-byte record they never come back to, that's about 1,600 SOL locked on the chain forever. The protocol that issued those records is responsible for cleaning up, either by closing accounts proactively or by exposing a close instruction users can call when they're done.
A safe close has three steps
To reclaim the SOL, the owner program drains the account's lamports to a recipient, wipes the data, and marks the account as closed. Anchor's close = recipient constraint performs all three steps for you.
Step 1 returns the rent. Every Solana account holds enough SOL to be rent-exempt, and at close time that SOL is sent to the recipient named in close = recipient. The runtime removes an account only once its balance is zero. Skip this step and the SOL stays locked in an account nobody uses.
Step 2 zeros the data. Even after the lamports are gone, the byte buffer still contains the old struct's contents until the runtime removes the account at the end of the transaction. If anything in the rest of the transaction reads that account's data, it sees the old state.
Step 3 marks the account as closed, and it is the step most commonly missed. The first 8 bytes of every Anchor account are a discriminator, a hash identifying which struct type the bytes represent. After steps 1 and 2, the account's data is all zeros, and the account still exists until the end of the transaction. Anyone can transfer lamports to any pubkey, so a later instruction in the same transaction can fund the account back to rent-exempt, and the runtime then keeps it alive. The program now owns a live account full of zeros at the old address. An instruction that takes such an account for a fresh one can initialize it again with the attacker's values. To rule this out, Anchor writes a special "closed" discriminator of all 0xFF bytes. The account is no longer all zeros, so it does not pass for a fresh one, and any later attempt to deserialize it as its original type fails.
This is called the revival attack. Early Anchor versions would close an account without writing the closed-account discriminator, which left this path open.
Using the close constraint
#[derive(Accounts)]
pub struct CloseDonorRecord<'info> {
#[account(
mut,
close = donor,
seeds = [b"donor", donor.key().as_ref()],
bump = donor_record.bump,
has_one = donor,
)]
pub donor_record: Account<'info, DonorRecord>,
#[account(mut)]
pub donor: Signer<'info>,
}
pub fn close_donor_record(_ctx: Context<CloseDonorRecord>) -> Result<()> {
// The close constraint does all the work.
// Logic here would run before close, if you needed any.
Ok(())
}close = donor sends the rent SOL back to the donor's wallet, and has_one = donor enforces that the signer is the same donor whose pubkey is stored on the record, so a stranger cannot close someone else's account. If you need to do work before the close, such as recording an event, checking invariants, or returning leftover token balances from a vault PDA, put it in the handler body before Ok(()). The close happens after the handler returns.
Where the rent goes
The program chooses who receives the rent of a closed account, and three patterns are common.
Refund to the user is the default for accounts a user created and no longer needs, such as a donation record after the user has withdrawn or a subscription account after the subscription expired. The user paid for the account at init and gets the SOL back on close.
Refund to the protocol is for accounts the protocol manages on the user's behalf. Sometimes a protocol pays the rent up front to subsidize UX, and on close the rent goes back to the treasury rather than to the user. The user pays nothing either way.
Refund to the caller pays for cleanup. If anyone can call the close instruction once some condition is met, say an expired auction or a fully matched order, and the rent SOL goes to the caller, bots will call your close function for the reclaimed rent and you don't have to run the cleanup yourself. This only works when the account is safe to close from any caller: the result must not depend on who sends the transaction, so the condition has to be checked inside the close instruction itself. The Solana PRO course calls this the untrusted executor pattern. In Helium's tuktuk scheduler, once a task's condition is met, any bot can run the task, take its prepaid reward and close the account.
Realloc resizes an account in place
Sometimes an account exists and works, but the data inside it needs more room. Realloc resizes the buffer in place, without forcing you to close and recreate.
Growing pays the rent delta, and shrinking does not refund it. The account keeps any surplus lamports it had before, which means a 200-byte account shrunk to 100 bytes still holds the 200-byte rent-exempt minimum. If you want the SOL back, you close the account.
#[derive(Accounts)]
#[instruction(new_size: usize)]
pub struct GrowList<'info> {
#[account(
mut,
realloc = 8 + new_size,
realloc::payer = payer,
realloc::zero = true,
seeds = [b"list", list.owner.as_ref()],
bump = list.bump,
)]
pub list: Account<'info, MessageList>,
#[account(mut)]
pub payer: Signer<'info>,
pub system_program: Program<'info, System>,
}realloc = NEW_SIZE sets the new total byte count, discriminator included. realloc::payer names the signer who covers the rent delta when growing. realloc::zero = true tells the runtime to zero the new bytes. Set it to false only when you're going to overwrite those bytes anyway in the same instruction, and you want the small CU saving.
The hard ceiling on a single realloc operation is 10 KB of growth per instruction. If you need an account to grow by 50 KB, you need five separate instructions, each adding up to 10 KB. The cap exists to keep transaction execution from doing unbounded work in one shot. For most use cases, growing by 1 KB or 2 KB per call is plenty.
Realloc, many PDAs, or close-and-recreate?
In the Donor Tiers Vault from the first milestone there's no upper bound on donations a single donor might make, so a donor's donations do not fit in one fixed-size account. There are three ways to store data like that.
Grow one account with realloc if the data grows in lockstep with one entity and the bound is known and small. A message board where each board has up to a few hundred posts, capped at maybe 8 KB total, is fine to grow with realloc, and so is a position-history log that tops out at 1 KB. The payer covers the rent delta on every growth, and anything that could plausibly need more than 10 KB total or might want to grow past the cap in one transaction needs a different design.
Give each item its own PDA if the data grows because more entities show up: more donations, more orders, more positions. Growth is unbounded and each item can be closed for a refund when it is done. The price is a rent deposit on every item. Even an account that holds only its 8-byte discriminator locks about 0.001 SOL, because the rent formula adds 128 bytes of overhead to every account. A transaction also has to pass more accounts. The Donor Tiers Vault does this. Each donation gets its own PDA and the donor record stays small. Nothing ever needs to realloc, because each new donation is a fresh account at its own address. A Vec<Donation> inside one account per donor would either need a low cap that rejects more than N donations, or grow forever via realloc.
Close and recreate if the data has an explicit end of life: the subscription expired, the vault drained, the position closed. The rent comes back, but the data is gone after the close, and a user who keeps using the program needs a second transaction to create the account again.
Make this choice before v1. The accounts your program releases at v1 determine its operating cost from then on, and a layout chosen carelessly has to be migrated later.