Inter-Canister Calls on ICP: Designing Multi-Canister Apps Without Creating a Distributed Mess
Thomas ·
In my previous guide, Persistent Data on ICP: A Production-Safe Motoko Guide to Upgrades and Schema Changes , I treated a single Motoko actor as the application's persistent database. That model works surprisingly far, but eventually there are good reasons to split an application across multiple canisters: isolation, independent upgrades, ownership boundaries, storage limits, or simply preventing one backend from becoming responsible for everything. The important part is recognizing what happens when you cross that boundary. Calling another canister is not equivalent to calling another function. It is asynchronous distributed messaging, and the moment you write await , assumptions about atomicity, failure, latency and even what your own state looks like become different. This guide builds a small two-canister Motoko application and then deliberately explores the failure cases that tend to appear only after an ICP application becomes complicated. The architecture We will build two canisters: 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 profile │ │ inter-canister call ▼ reputation profile owns usernames and user-facing profile state. reputation owns reputation scores. Keeping those domains separate gives us a useful architecture property: the reputation implementation can later be replaced or independently upgraded without turning the profile canister into a monolith. That does not mean every type of data deserves its own canister. Inter-canister boundaries have costs, so separation should buy you something. ICP's own current architecture guidance describes canister-per-service as appropriate when responsibilities need separation or a canister begins approaching compute, memory or storage limits. Cross-subnet distribution can also provide horizontal scaling because different subnets execute independently. Use the current toolchain At the time of writing, Mops lists: 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" as the current release. Install the tooling if necessary: 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 Then: 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 inter-canister-example cd inter-canister-example mops init mops add core@2.6.1 mops toolchain use moc latest The current Motoko compiler line has also moved considerably beyond many tutorials still circulating online. The official repository currently identifies Motoko 1.8.2 as its latest release. Create the reputation canister Create: 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/reputation/main.mo with: 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" ; import Nat "mo:core/Nat" ; import Principal "mo:core/Principal" ; persistent actor Reputation { let scores = Map . empty < Principal , Nat >(); public query func getScore (user : Principal ) : async Nat { switch ( Map . get (scores, Principal . compare , user)) { case (?score) score; case null 0 ; }; }; public func addPoints (user : Principal , points : Nat ) : async Nat { let current = switch ( Map . get (scores, Principal . compare , user)) { case (?score) score; case null 0 ; }; let updated = current + points; Map . add (scores, Principal . compare , user, updated); updated; }; }; There is nothing unusual here. It is an independently deployable canister with its own persistent state. profile will not possess a magical reference into scores . It must send a message to reputation and wait for a response. Create the profile canister Create: 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/profile/main.mo Initially: 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" ; import Principal "mo:core/Principal" ; import Result "mo:core/Result" ; import Runtime "mo:core/Runtime" ; persistent actor Profile { type Reputation = actor { getScore : ( Principal ) -> async Nat ; addPoints : ( Principal , Nat ) -> async Nat ; }; let usernames = Map . empty < Principal , Text >(); func reputationCanister () : Result . Result < Reputation , Text > { let ?canisterId = Runtime . envVar <system>( "PUBLIC_CANISTER_ID:reputation" ) else { return # err ( "Reputation canister ID is not configured" ); }; # ok ( actor (canisterId) : Reputation ); }; public shared ({ caller }) func setUsername (username : Text ) : async () { Map . add (usernames, Principal . compare , caller, username); }; public query func getUsername (user : Principal ) : async ? Text { Map . get (usernames, Principal . compare , user); }; }; The interesting part is how the second canister is discovered. Spoiler Stop hardcoding canister IDs Older examples frequently contain something like: 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 let reputation = actor ( "rrkah-fqaaa-aaaaa-aaaaq-cai" ) : Reputation ; That works technically, but it is usually the wrong architecture for application canisters. Your local canister ID is not necessarily your staging ID, and neither is necessarily your production ID. The modern icp deployment system solves this directly. During deployment, icp deploy creates or resolves all project canisters and injects environment variables using: 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_CANISTER_ID :<canister-name> So our profile canister receives: 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_CANISTER_ID :reputation automatically. DFINITY's current guidance specifically recommends this environment-variable approach and notes that the older Motoko canister:name import mechanism is being redesigned for icp-cli compatibility. That is why the example uses: 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 Runtime . envVar <system>( "PUBLIC_CANISTER_ID:reputation" ) instead of copying a principal into source code. This is a small tooling improvement that becomes a major operational improvement once you maintain local, test and production environments. Configure the project Your mops.toml needs both canisters: 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" [canisters.profile] main = "src/profile/main.mo" [canisters.reputation] main = "src/reputation/main.mo" Then define both in icp.yaml using the current Motoko recipe. The important architectural point is that both canisters belong to the same deployment environment. When you 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 icp deploy icp resolves their IDs before installing the Wasm, allowing each canister to receive the other's ID. If you later add another canister, deploy the project rather than only one existing canister so the relevant environment variables are refreshed. The current documentation explicitly notes this behavior. Make the first inter-canister call Add this to Profile : 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 func getReputation (user : Principal ) : async Result . Result < Nat , Text > { let # ok (reputation) = reputationCanister () else { return # err ( "Reputation service unavailable" ); }; try { let score = await reputation. getScore (user); # ok (score); } catch (error) { # err ( "Reputation call failed" ); }; }; The critical line is: 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 let score = await reputation. getScore (user); It looks almost like a normal function call. Your canister sends a message and suspends this execution while another canister processes it. That distinction explains most inter-canister bugs. await is an atomicity boundary Consider this code: 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 var totalPointsAwarded : Nat = 0 ; public func award (user : Principal , points : Nat ) : async () { totalPointsAwarded += points; await reputation. addPoints (user, points); // continue working... }; A developer coming from a conventional backend might mentally model this as one transaction: 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 increment local value call reputation continue commit everything That's not how ICP executes it. The state changes before the await are committed before execution suspends. Motoko's language reference is explicit: state changes and message sends occurring before the await become committed and irrevocable when the computation suspends. So imagine: 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 totalPointsAwarded += points; await reputation. addPoints (user, points); and the reputation call fails. Your local increment has already happened. You now have: 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 profile.totalPointsAwarded = +10 reputation score = unchanged There is no automatic distributed rollback. This is one of the most important facts to understand before building a multi-canister ICP application. A trap after await does not save you This is also dangerous: 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 totalPointsAwarded += points; await reputation. addPoints (user, points); assert false ; The trap after the await does not rewind the state mutation performed before the call. ICP's security documentation describes these as separate message executions. A callback trap rolls back the callback's changes, but mutations committed before the await remain. If your design requires atomic changes across multiple canisters, you need a protocol for that. You do not get an ACID transaction merely because both pieces of code are written in Motoko. Design state transitions, not distributed transactions A better architecture is often to represent work explicitly. 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 type AwardState = { #pending; #completed; #failed : Text ; }; type Award = { id : Nat ; user : Prin