Sign in

Account closure and realloc

Suggest an edit

Solana 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.

The three steps of closing an account: drain lamports, zero data, overwrite discriminatorThe diagram shows a normal account with lamports and data, then three stacked steps that close it: step 1 transfers all lamports to the recipient, step 2 zeros the data buffer, and step 3 overwrites the discriminator with CLOSED_ACCOUNT_DISCRIMINATOR. Each step lists what happens if it is skipped, such as stranded SOL, readable stale fields, or a revival attack. The three steps of closing an account before: a normal account lamports: 2,039,280 (rent-exempt minimum) data: disc | field1 | field2 | ... (real bytes) step 1: transfer all lamports to recipient lamports: 0 (account is now below rent-exempt) recipient: +2,039,280 if skipped: account stays paid for forever, SOL is stranded step 2: zero the data buffer data: 0x00 0x00 0x00 ... (every byte wiped) old fields are gone, no readable state remains if skipped: stale fields readable if account is funded again step 3: overwrite discriminator with CLOSED_ACCOUNT_DISCRIMINATOR data[0..8]: [255, 255, 255, 255, 255, 255, 255, 255] Anchor will refuse to deserialize this account as anything if skipped: revival attack, caller funds it, original handler runs on stale state

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

rust
#[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 an account with realloc: before (100 bytes) and after (200 bytes)Shows an account before and after realloc: before it is 100 bytes with 50 used and 50 empty, after it is 200 bytes with the same 50 used bytes preserved plus 100 new bytes that are zeroed or left untouched depending on realloc::zero. A third box shows the rent delta the payer covers to keep the bigger account rent-exempt, about 700,000 lamports, and notes that shrinking gives no refund and growth is capped at 10 KB per instruction. Growing an account with realloc before: 100-byte account, 50 bytes used data buffer (100 bytes): used (50 bytes) empty (50 bytes) realloc = 200 after: 200-byte account, original data preserved data buffer (200 bytes): used (50 bytes) empty (50 bytes) new bytes (100 bytes) zeroed if realloc::zero = true old contents: preserved byte-for-byte at the start of the buffer new bytes: zeroed (with realloc::zero = true) or untouched (= false) payer: transfers the rent delta to keep the account exempt the rent delta the payer covers rent_exempt(200 bytes) - rent_exempt(100 bytes) = roughly 700,000 lamports shrinking is the mirror: the account keeps the surplus, no refund happens hard cap: 10 KB growth per instruction, split larger growth across multiple calls

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.

rust
#[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.

Realloc, many small PDAs, or close-and-recreate: three account strategiesThree columns compare ways to handle growing account data: grow one account with realloc, use many small PDAs (marked as the Solana default), or close and recreate the account. Each column lists its approach, good-for cases, tradeoffs, and an example, such as a message board, donations or votes, and a vesting record. Realloc, many PDAs, or close-and-recreate? grow one account approach: realloc as needed good for: - bounded list that fits in 10 KB total - single thread of data per account - predictable growth by fixed chunks tradeoffs: payer covers rent delta each time; 10 KB hard ceiling per instruction. example: message board with a growing post list simple, single home many small PDAs approach: one PDA per item, indexed by seed good for: - unbounded growth - per-user data that scales per donor - close-on-exit refund pattern tradeoffs: discriminator on every account costs 8 bytes; many tx accounts to manage example: donations, votes, orders, positions the Solana default close and recreate approach: close old account, init fresh one good for: - end-of-lifecycle cleanup - reclaiming rent for the user - starting over with a fresh schema tradeoffs: data is gone after close; need 2 tx if user keeps using the program example: withdraw + close vesting record returns rent to user For most "this user has many items" cases, many small PDAs is the right call. Realloc is the exception.

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.