Persistent Data on ICP: A Production-Safe Motoko Guide to Upgrades and Schema Changes

·

Hello, IC developers. I got tired of not seeing much useful information in this subforum, so I spent some time to build a guide on persistent storage. A canister that works perfectly until its first upgrade is not a production-ready canister. Persistent state is therefore one of the first ICP concepts worth understanding properly. The good news is that modern Motoko makes persistence substantially easier than it used to be. You generally do not need to serialize your entire application into stable memory manually, and new projects should not be built around preupgrade and postupgrade hooks. Motoko's enhanced orthogonal persistence allows normal actor state to survive an upgrade directly. This guide builds a small notes canister, stores real structured data, upgrades the canister without losing anything, and then performs a schema migration that changes every existing record. What actually persists? An ICP canister has memory associated with its execution, but you should not think of persistence like a conventional server writing files to a disk. With modern Motoko, a persistent actor participates in orthogonal persistence. Actor state that has a stable type can be retained automatically between versions of the Wasm module. That means this: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff persistent actor { var counter : Nat = 0 ; }; is persistent state. You do not need: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff stable var counter : Nat = 0 ; for a new persistent actor, and you should not build a new architecture around manually copying everything during preupgrade(). The distinction becomes important when you intentionally have temporary state. A cache, for example, may be useful while a particular version of the canister is running but completely safe to reconstruct after an upgrade. That can be marked explicitly : Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff transient var cache = Map.empty< Text , Text >(); Persistent is the default inside a persistent actor . transient means that value belongs to the current execution rather than the long-term application state. Install the current toolchain You will need Node.js 22 or newer for the current ICP CLI tooling. Install the ICP CLI, the Wasm utility used by the official recipes, and Mops: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff npm install -g @icp-sdk/icp-cli @icp-sdk/ic-wasm ic-mops Create a project: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff mkdir persistent-notes cd persistent-notes mops init Choose a normal project rather than a package when prompted. Now let Mops install and pin the latest stable Motoko compiler available to it: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff mops toolchain use moc latest Install the Motoko core library: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff mops add core@2.6.1 At the time this guide was written, core 2.6.1 is the current release. Pinning package versions makes the project reproducible rather than silently changing behavior when dependencies update. Create this structure: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff persistent-notes/ ├── icp.yaml ├── mops.toml └── src/ └── backend/ ├── main.mo └── migrations/ Configure Mops Your mops.toml should contain the compiler version that mops toolchain use moc latest selected, along with the dependency and backend definition. Conceptually it will look like this: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff [ dependencies ] core = "2.6.1" [ toolchain ] moc = "<version pinned by mops>" [ canisters.backend ] main = "src/backend/main.mo" [ canisters.backend.migrations ] chain = "src/backend/migrations" check-limit = 1 [ canisters.backend.check-stable ] path = "deployed/backend.most" Do not replace the compiler version Mops selected with whatever happens to be shown in somebody else's tutorial. The migration configuration deserves attention. We are setting this project up correctly from the beginning instead of waiting until a breaking state change happens in production. Mops will generate a .most file when the canister is built. That file describes the stable state shape of the canister and can be used to verify that a future version is actually compatible with the deployed one. Initialize the deployment baseline: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff mops deployed init Configure the ICP CLI Create icp.yaml : Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff canisters: - name: backend recipe: type: "@dfinity/motoko@v5.0.0" There is no Motoko source path inside icp.yaml . The current Motoko recipe delegates compilation to Mops, so the source entry point belongs in mops.toml . The name must match in both places: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff name: backend and: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff [canisters.backend] Otherwise the recipe will ask Mops to build a canister that Mops doesn't know exists. Version 1: our persistent notes database We will store notes in Map.Map . Unlike many in-memory map implementations developers may be familiar with, the current mo:core/Map type is stable and is explicitly designed to participate in Motoko's persistence model. Create src/backend/main.mo : Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff import Iter "mo:core/Iter" ; import Map "mo:core/Map" ; import Nat "mo:core/Nat" ; persistent actor Notes { public type Note = { id : Nat ; title : Text ; body : Text ; }; let notes : Map.Map< Nat , Note>; var nextId : Nat ; public func createNote (title : Text , body : Text ) : async Note { let note : Note = { id = nextId; title; body; }; Map.add(notes, Nat .compare, nextId, note); nextId += 1 ; note; }; public query func getNote (id : Nat ) : async ?Note { Map.get(notes, Nat .compare, id); }; public query func getNotes () : async [Note] { Iter.toArray(Map.vals(notes)); }; public query func count () : async Nat { Map.size(notes); }; }; You may notice that notes and nextId do not have initial values. Because this project uses a managed enhanced migration chain, initial persistent state comes from the first migration. This gives us one consistent mechanism for both initial installation and every future incompatible schema change. Create your first migration in src/backend/migrations/ . Migration filenames are timestamps because their lexical order defines their execution order. For example: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff src/backend/migrations/20260822_220000.mo The exact timestamp does not matter as long as it is a valid UTC timestamp and sorts after earlier migrations. Put this inside: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff import Map "mo:core/Map" ; module { type Note = { id : Nat ; title : Text ; body : Text ; }; type OldActor = {}; type NewActor = { notes : Map.Map< Nat , Note>; var nextId : Nat ; }; public func migration (_old : OldActor) : NewActor { { notes = Map.empty< Nat , Note>(); var nextId = 0 ; }; }; }; This file describes the transition from an empty canister to version 1 of our application state. That separation may look unnecessary for a tiny example, but it becomes extremely useful once a real production canister has years of state history behind it. Check before you build Run: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff mops check --fix This is one of the commands I would run frequently. It type-checks the Motoko project and, because we configured a deployed stable-state baseline, verifies the upgrade relationship as well. Then build: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff mops build Mops produces three particularly useful artifacts for the backend: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff backend.wasm backend.did backend.most The Wasm is the actual canister program. The .did file describes its Candid API. The .most file describes its stable Motoko state. That third file is easy to overlook, but it is one of the most useful safeguards in a stateful ICP project. Deploy locally Start the project-local ICP network: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff icp network start -d icp deploy The current icp CLI performs the build, deployment and synchronization pipeline. For an existing canister, the normal deployment path performs an upgrade rather than reinstalling it. Note: Do not casually use: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff icp deploy --mode reinstall A reinstall is intentionally destructive and clears state. Create two notes and read them: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff icp canister call backend createNote '("First note", "This should survive an upgrade.")' icp canister call backend createNote '("Second note", "Persistent state is application state.")' icp canister call backend getNotes '()' You should receive both records. Prove that an upgrade does not erase it Make a harmless code change. For example, add: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff public query func version() : async Text { "1.0.1"; }; Deploy and get the notes: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff mops check --fix mops build icp deploy icp canister call backend getNotes '()' The 2 notes should still exist. Deploying new Wasm does not inherently mean resetting application state. With enhanced orthogonal persistence, the new Motoko program resumes with compatible persistent state from the old program. That's one of the biggest innovations of ICP. The harder problem: your data model changes Data models change with time as sites get more