A canister's data survives an upgrade when it is kept the way its language expects: automatically in a Motoko persistent actor, and in stable structures in Rust.
Two kinds of memory
- Heap (Wasm) memory: the program's working memory, up to 4 GB for 32-bit Wasm and 6 GB for 64-bit Wasm.
- Stable memory: memory kept across upgrades, which can grow to hundreds of GB within the subnet's storage.
On a cloud engine, every node holds a full copy, so all your canisters share the memory and storage of one node of the engine's class.
Motoko
- In a
persistent actor, everyletandvarsurvives upgrades automatically (enhanced orthogonal persistence). Nostablekeyword and no upgrade hooks are needed; onlytransientdeclarations reset. - The runtime checks the new code against the existing data. An incompatible change, such as changing the type of a stored record (even adding an optional field), is rejected before it takes effect: the canister keeps running the old version with its data intact. Add a migration and deploy again.
mops checkwith the stable-compatibility check configured catches this before you deploy.
Rust
- Ordinary heap data (a
thread_local!RefCell, statics) is wiped on every upgrade. - Keep data in
ic-stable-structures(StableBTreeMap,StableCell,StableLog), which read and write stable memory directly. Give each structure its ownMemoryIdand never reuse one. - Don't serialize large data in
pre_upgrade: upgrade hooks have an instruction limit, and a hook that traps can leave the canister unable to upgrade at all. - Define both
#[init]and#[post_upgrade].
Before a risky upgrade
- Upgrade, never reinstall: a reinstall wipes all state.
- Before a risky upgrade, have one of the canister's controllers take a snapshot of it, so you can roll back. The console has no snapshot control today: a controller takes it outside the console, for example with the icp CLI.