Install
$ agentstack add skill-dfinity-icskills-multi-canister ✓ scanned · ✓ verified — works with Claude Code, Cursor, and more.
Security review
✓ PassedNo issues found. Passed automated security review. · v0.1.0 How review works →
- ✓ Prompt-injection patterns
- ✓ Secret / credential exfiltration
- ✓ Dangerous shell & filesystem operations
- ✓ Untrusted network calls
- ✓ Known-malicious package signatures
What it can access
- ✓ Network access No
- ✓ Filesystem access No
- ✓ Shell / process execution No
- ✓ Environment & secrets No
- ✓ Dynamic code execution No
From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.
About
Multi-Canister Architecture
What This Is
Splitting an IC application across multiple canisters for scaling, separation of concerns, or independent upgrade cycles. Each canister has its own state, cycle balance, and upgrade path. Canisters communicate via async inter-canister calls.
Prerequisites
- For Motoko:
mopspackage manager,core = "2.0.0"in mops.toml - For Rust:
ic-cdk >= 0.19,candid,serde,ic-stable-structures
How It Works
A caller canister makes a call to a callee canister: the method name, arguments (payload) and attached cycles are packed into a canister request message, which is delivered to the callee after the caller blocks on await; the callee executes the request and produces a response; this is packed into a canister response message and delivered to the caller; the caller awakes fron the await and continues execution (executes the canister response message). The system may produce a reject response message if e.g. the callee is not found or some resource limit was reached.
Calls may be unbounded wait (caller MUST wait until the callee produces a response) or bounded wait (caller MAY get a SYS_UNKNOWN response instead of the actual response after the call timeout expires or if the subnet runs low on resources). Request delivery is best-effort: the system may decide to reject any request instead of delivering it. Unbounded wait response (including reject response) delivery is guaranteed: the caller will always learn the outcome of the call. Bounded wait response delivery is best-effort: the caller may receive a system-generated SYS_UNKNOWN reject response (unknown outcome) instead of the actual response if the call timed out or some system resource was exhausted, whether or not the request was delivered to the callee.
When to Use Multi-Canister
| Reason | Threshold | |---|---| | Storage limits | Each canister: up to hundreds of GB stable memory + 4GB heap. If your data could exceed heap limits or benefit from partitioning, split storage across canisters. | | Scalable compute | Canisters are single-threaded actors. Sharding load across multiple canisters, potentially across multiple subnets, can significantly improve throughput. | | Separation of concerns | Auth service, content service, payment service as independent units. | | Independent upgrades | Upgrade the payments canister without touching the user canister. | | Access control | Different controllers for different canisters (e.g., DAO controls one, team controls another). |
When NOT to use: Simple apps with ();
// Register a new user public shared ({ caller }) func register(username : Text) : async Result.Result { if (Principal.isAnonymous(caller)) { return #err(#Unauthorized); }; switch (Map.get(users, Principal.compare, caller)) { case (?_existing) { #err(#AlreadyExists) }; case null { let profile : UserProfile = { id = caller; username; created = Time.now(); }; Map.add(users, Principal.compare, caller, profile); #ok(profile) }; } };
// Check if a user exists (called by other canisters) public shared query func isValidUser(userId : Principal) : async Bool { switch (Map.get(users, Principal.compare, userId)) { case (?_) { true }; case null { false }; } };
// Get user profile public shared query func getUser(userId : Principal) : async ?UserProfile { Map.get(users, Principal.compare, userId) };
// Get all users public query func getUsers() : async [UserProfile] { Array.fromIter(Map.values(users)) }; };
#### src/content_service/main.mo — Content Canister (calls User Service)
```motoko
import Map "mo:core/Map";
import Nat "mo:core/Nat";
import Array "mo:core/Array";
import Time "mo:core/Time";
import Result "mo:core/Result";
import Runtime "mo:core/Runtime";
import Error "mo:core/Error";
import Principal "mo:core/Principal";
import Types "../shared/Types";
// Import the other canister — name must match icp.yaml canister key
import UserService "canister:user_service";
persistent actor {
type Post = Types.Post;
let posts = Map.empty();
var postCounter : Nat = 0;
// Create a post — validates user via inter-canister call
public shared ({ caller }) func createPost(title : Text, body : Text) : async Result.Result {
let originalCaller = caller;
if (Principal.isAnonymous(originalCaller)) {
return #err(#Unauthorized);
};
// Inter-canister call to user_service
let isValid = try {
await UserService.isValidUser(originalCaller)
} catch (e : Error.Error) {
Runtime.trap("User service unavailable: " # Error.message(e));
};
if (not isValid) {
return #err(#Unauthorized);
};
let id = postCounter;
let post : Post = {
id;
author = originalCaller;
title;
body;
created = Time.now();
};
Map.add(posts, Nat.compare, id, post);
postCounter += 1;
#ok(post)
};
// Get all posts
public query func getPosts() : async [Post] {
Array.fromIter(Map.values(posts))
};
// Get posts by author — with enriched user data
public func getPostsWithAuthor(authorId : Principal) : async {
user : ?Types.UserProfile;
posts : [Post];
} {
let userProfile = try {
await UserService.getUser(authorId)
} catch (_e : Error.Error) { null };
let authorPosts = Array.filter(
Array.fromIter(Map.values(posts)),
func(p : Post) : Bool { p.author == authorId }
);
{ user = userProfile; posts = authorPosts }
};
// Delete a post — only the author can delete
public shared ({ caller }) func deletePost(id : Nat) : async Result.Result {
let originalCaller = caller;
switch (Map.get(posts, Nat.compare, id)) {
case (?post) {
if (post.author != originalCaller) {
return #err(#Unauthorized);
};
ignore Map.delete(posts, Nat.compare, id);
#ok(())
};
case null { #err(#NotFound) };
}
};
};
Production Readiness: Content Service
The content service examples above are intentionally kept simple to demonstrate multi-canister communication patterns. They lack several things that would be needed for production use:
- Input validation. The
usernameparameter inregisteraccepts any string — including empty strings or strings up to the 2MB message size limit. Validate length (e.g., 1–64 characters), enforce allowed character sets, and add a uniqueness constraint via a reverse lookup map to prevent impersonation. - User enumeration and pagination on
getUsers. UsinggetUsers, it's possible for everyone to enumerate all users on the platform, which may not be desirable. Furthermore, thegetUsersendpoint returns all user profiles in a single response. As the user base grows, this will hit the 2MB response size limit and trap, bricking the endpoint. Add pagination (offset/limit parameters). The same applies togetPosts.
Rust
Project Structure (Rust)
my-project/
icp.yaml
Cargo.toml # workspace
src/
user_service/
Cargo.toml
src/lib.rs
content_service/
Cargo.toml
src/lib.rs
Cargo.toml (workspace root)
[workspace]
members = [
"src/user_service",
"src/content_service",
]
icp.yaml (Rust)
canisters:
- name: user_service
recipe:
type: "@dfinity/rust@v3.2.0"
configuration:
package: user_service
candid: src/user_service/user_service.did
- name: content_service
recipe:
type: "@dfinity/rust@v3.2.0"
configuration:
package: content_service
candid: src/content_service/content_service.did
src/user_service/Cargo.toml
[package]
name = "user_service"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
ic-cdk = "0.19"
candid = "0.10"
serde = { version = "1", features = ["derive"] }
ic-stable-structures = "0.7"
src/user_service/src/lib.rs
use candid::{CandidType, Deserialize, Principal};
use ic_cdk::{init, post_upgrade, query, update};
use ic_stable_structures::memory_manager::{MemoryId, MemoryManager, VirtualMemory};
use ic_stable_structures::{DefaultMemoryImpl, StableBTreeMap};
use std::cell::RefCell;
type Memory = VirtualMemory;
#[derive(CandidType, Deserialize, Clone, Debug)]
struct UserProfile {
id: Principal,
username: String,
created: i64,
}
// Stable storage
thread_local! {
static MEMORY_MANAGER: RefCell> =
RefCell::new(MemoryManager::init(DefaultMemoryImpl::default()));
static USERS: RefCell, Vec, Memory>> = RefCell::new(
StableBTreeMap::init(
MEMORY_MANAGER.with(|m| m.borrow().get(MemoryId::new(0)))
)
);
}
fn principal_to_key(p: &Principal) -> Vec {
p.as_slice().to_vec()
}
fn serialize_profile(profile: &UserProfile) -> Vec {
candid::encode_one(profile).unwrap()
}
fn deserialize_profile(bytes: &[u8]) -> UserProfile {
candid::decode_one(bytes).unwrap()
}
#[init]
fn init() {}
#[post_upgrade]
fn post_upgrade() {}
#[update]
fn register(username: String) -> Result {
let caller = ic_cdk::api::msg_caller();
if caller == Principal::anonymous() {
return Err("Unauthorized".to_string());
}
let key = principal_to_key(&caller);
USERS.with(|users| {
if users.borrow().contains_key(&key) {
return Err("Already exists".to_string());
}
let profile = UserProfile {
id: caller,
username,
created: ic_cdk::api::time() as i64,
};
let bytes = serialize_profile(&profile);
users.borrow_mut().insert(key, bytes);
Ok(profile)
})
}
#[query]
fn is_valid_user(user_id: Principal) -> bool {
let key = principal_to_key(&user_id);
USERS.with(|users| users.borrow().contains_key(&key))
}
#[query]
fn get_user(user_id: Principal) -> Option {
let key = principal_to_key(&user_id);
USERS.with(|users| {
users.borrow().get(&key).map(|bytes| deserialize_profile(&bytes))
})
}
ic_cdk::export_candid!();
src/content_service/Cargo.toml
[package]
name = "content_service"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
ic-cdk = "0.19"
candid = "0.10"
serde = { version = "1", features = ["derive"] }
ic-stable-structures = "0.7"
src/content_service/src/lib.rs
use candid::{CandidType, Deserialize, Principal};
use ic_cdk::call::Call;
use ic_cdk::{init, post_upgrade, query, update};
use ic_stable_structures::memory_manager::{MemoryId, MemoryManager, VirtualMemory};
use ic_stable_structures::{DefaultMemoryImpl, StableBTreeMap, StableCell};
use std::cell::RefCell;
type Memory = VirtualMemory;
#[derive(CandidType, Deserialize, Clone, Debug)]
struct Post {
id: u64,
author: Principal,
title: String,
body: String,
created: i64,
}
#[derive(CandidType, Deserialize, Clone, Debug)]
struct UserProfile {
id: Principal,
username: String,
created: i64,
}
// Stable storage -- survives canister upgrades
thread_local! {
static MEMORY_MANAGER: RefCell> =
RefCell::new(MemoryManager::init(DefaultMemoryImpl::default()));
// Posts keyed by id (u64 as big-endian bytes) -> candid-encoded Post
static POSTS: RefCell, Vec, Memory>> = RefCell::new(
StableBTreeMap::init(
MEMORY_MANAGER.with(|m| m.borrow().get(MemoryId::new(0)))
)
);
// Post counter in stable memory
static POST_COUNTER: RefCell> = RefCell::new(
StableCell::init(
MEMORY_MANAGER.with(|m| m.borrow().get(MemoryId::new(1))),
0u64,
)
);
// Store the user_service canister ID (set during init, re-set on upgrade)
static USER_SERVICE_ID: RefCell> = RefCell::new(None);
}
fn post_id_to_key(id: u64) -> Vec {
id.to_be_bytes().to_vec()
}
fn serialize_post(post: &Post) -> Vec {
candid::encode_one(post).unwrap()
}
fn deserialize_post(bytes: &[u8]) -> Post {
candid::decode_one(bytes).unwrap()
}
#[init]
fn init(user_service_id: Principal) {
USER_SERVICE_ID.with(|id| *id.borrow_mut() = Some(user_service_id));
}
#[post_upgrade]
fn post_upgrade(user_service_id: Principal) {
// Re-set the user_service ID (not stored in stable memory for simplicity,
// since it is always passed as an init/upgrade argument)
init(user_service_id);
}
fn get_user_service_id() -> Principal {
USER_SERVICE_ID.with(|id| {
id.borrow().expect("user_service canister ID not set")
})
}
// Defensive: capture caller before any await
#[update]
async fn create_post(title: String, body: String) -> Result {
// Capture caller before the await as defensive practice
let original_caller = ic_cdk::api::msg_caller();
if original_caller == Principal::anonymous() {
return Err("Unauthorized".to_string());
}
// Inter-canister call to user_service
let user_service = get_user_service_id();
let (is_valid,): (bool,) = Call::unbounded_wait(user_service, "is_valid_user")
.with_arg(original_caller)
.await
.map_err(|e| format!("User service call failed: {:?}", e))?
.candid_tuple()
.map_err(|e| format!("Failed to decode response: {:?}", e))?;
if !is_valid {
return Err("User not registered".to_string());
}
let id = POST_COUNTER.with(|counter| {
let mut counter = counter.borrow_mut();
let id = *counter.get();
counter.set(id + 1);
id
});
let post = Post {
id,
author: original_caller, // Use captured caller
title,
body,
created: ic_cdk::api::time() as i64,
};
POSTS.with(|posts| {
posts.borrow_mut().insert(post_id_to_key(id), serialize_post(&post));
});
Ok(post)
}
#[query]
fn get_posts() -> Vec {
POSTS.with(|posts| {
posts.borrow().iter()
.map(|entry| deserialize_post(&entry.value()))
.collect()
})
}
// Cross-canister enrichment: get posts with author profile
#[update]
async fn get_posts_with_author(author_id: Principal) -> (Option, Vec) {
let user_service = get_user_service_id();
// Call user_service for profile data
let user_profile: Option =
match Call::unbounded_wait(user_service, "get_user")
.with_arg(author_id)
.await
{
Ok(response) => response.candid_tuple::,)>()
.map(|(profile,)| profile)
.unwrap_or(None),
Err(_) => None, // Handle gracefully if user service is down
};
let author_posts = POSTS.with(|posts| {
posts.borrow().iter()
.map(|entry| deserialize_post(&entry.value()))
.filter(|p| p.author == author_id)
.collect()
});
(user_profile, author_posts)
}
#[update]
async fn delete_post(id: u64) -> Result {
let original_caller = ic_cdk::api::msg_caller();
POSTS.with(|posts| {
let mut posts = posts.borrow_mut();
let key = post_id_to_key(id);
match posts.get(&key) {
Some(bytes) => {
let post = deserialize_post(&bytes);
if post.author != original_caller {
return Err("Unauthorized".to_string());
}
posts.remove(&key);
Ok(())
}
None => Err("Not found".to_string()),
}
})
}
ic_cdk::export_candid!();
Canister Factory Pattern
A canister that creates other canisters dynamically. Useful for per-user canisters, sharding, or dynamic scaling.
Motoko Factory
import Principal "mo:core/Principal";
import Map "mo:core/Map";
import Array "mo:core/Array";
import Runtime "mo:core/Runtime";
persistent actor Self {
type CanisterSettings = {
controlle
…
## Source & license
This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.
- **Author:** [dfinity](https://github.com/dfinity)
- **Source:** [dfinity/icskills](https://github.com/dfinity/icskills)
- **License:** Apache-2.0
- **Homepage:** https://skills.internetcomputer.org
Install and usage instructions live in the source repository linked above.
Reviews
No reviews yet — be the first.
Write a review
Versions
- v0.1.0 Imported from the upstream source.