Context & Why
Letting third parties run custom code inside your backend is always nerve-wracking. A few years ago, our team needed to support custom webhook transformers for enterprise clients. We initially considered dynamic linking via .so and .dll files, then tested embedded Lua interpreters. Both approaches caused headaches in staging.
Shared C and Rust libraries share the host process’s address space. One null-pointer dereference or out-of-bounds write does not just crash the plugin—it takes down your entire multi-tenant API server.
Worse, a compromised dynamic library can read host environment variables, probe 127.0.0.1, or scan /etc/passwd. Script runtimes like Python or Lua avoid raw memory corruption, but they add 20–40 MB of baseline memory overhead per worker, introduce 15ms garbage collection pauses, and require brittle FFI glue code.
WebAssembly handles isolation at the architectural level. Originally built for web browsers, Wasm compiles down to a compact binary instruction format executed inside a deterministic, stack-based sandbox. Pairing Rust with Wasmtime—the Bytecode Alliance’s standalone runtime written in Rust—lets you run untrusted code in-process at near-native speed, usually within 10% to 20% of bare-metal C.
Isolation is absolute by default. A Wasm module lives inside a sandboxed linear memory array. It cannot read host stack frames, forge pointers outside its allocated memory chunk, or trigger a single operating system syscall unless you explicitly link a host function to it. If a customer-uploaded plugin hits an infinite loop or runs out of bounds, your host process simply logs the trap and keeps serving traffic.
Installation
You need a working Rust toolchain (Rust 1.75+ recommended). We will build two separate crates in a single workspace: an isolated guest plugin compiled to WebAssembly, and a host runner that instantiates and monitors the sandbox.
1. Add the WebAssembly Compilation Target
Rust compiles directly to bare-metal WebAssembly via the wasm32-unknown-unknown target. Install it through rustup:
rustup target add wasm32-unknown-unknown
2. Scaffold the Workspace
Generate a root workspace folder containing two crates: plugin_host (the binary runner) and guest_plugin (the compiled Wasm module).
mkdir wasm-plugin-demo && cd wasm-plugin-demo
cargo new --bin plugin_host
cargo new --lib guest_plugin
Create a root Cargo.toml to connect both projects:
[workspace]
members = [
"plugin_host",
"guest_plugin",
]
resolver = "2"
3. Install Dependencies
Open plugin_host/Cargo.toml and pull in Wasmtime along with Anyhow for straightforward error reporting:
[package]
name = "plugin_host"
version = "0.1.0"
edition = "2021"
[dependencies]
wasmtime = "21.0"
anyhow = "1.0"
Next, configure guest_plugin/Cargo.toml. Set the crate type to cdylib so Cargo produces an unadorned, standalone dynamic library stripped of Rust-specific runtime metadata:
[package]
name = "guest_plugin"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
Configuration
Now we define the interface boundary between our host application and the sandboxed guest module.
1. Implement the Guest Plugin
Open guest_plugin/src/lib.rs. We will expose two deterministic functions: an invoice discount calculator and an access level validator. The #[no_mangle] attribute and extern "C" calling convention ensure the compiler leaves the function symbols intact for the host linker:
#[no_mangle]
pub extern "C" fn calculate_discount(order_amount: f64, tier: i32) -> f64 {
if order_amount <= 0.0 {
return 0.0;
}
match tier {
1 => order_amount * 0.05, // 5% discount
2 => order_amount * 0.10, // 10% discount
3 => order_amount * 0.20, // 20% discount
_ => 0.0,
}
}
#[no_mangle]
pub extern "C" fn is_authorized(role_id: i32) -> i32 {
// 1 for allow, 0 for deny
match role_id {
100..=105 => 1,
_ => 0,
}
}
Build the release binary for the Wasm target:
cargo build -p guest_plugin --target wasm32-unknown-unknown --release
Cargo writes the compiled 1.8 KB binary to target/wasm32-unknown-unknown/release/guest_plugin.wasm.
2. Build the Sandboxed Host
Never run untrusted guest code without boundaries. An unmetered module can lock up a CPU core with loop {} or allocate memory until the Linux kernel fires an Out-Of-Memory (OOM) kill on your server. Wasmtime solves CPU abuse through fuel consumption, which injects instruction counters during JIT compilation.
Add the following execution logic to plugin_host/src/main.rs:
use anyhow::{Context, Result};
use wasmtime::{Config, Engine, Instance, Module, Store, TypedFunc};
struct HostState {
invocations: u32,
}
fn main() -> Result<()> {
// 1. Enable fuel consumption in the JIT compiler config
let mut config = Config::new();
config.consume_fuel(true);
let engine = Engine::new(&config)
.context("Failed to initialize Wasmtime engine")?;
// 2. Load the precompiled guest bytecode
let wasm_bytes = std::fs::read("target/wasm32-unknown-unknown/release/guest_plugin.wasm")
.context("Missing compiled .wasm binary. Run 'cargo build -p guest_plugin' first.")?;
let module = Module::new(&engine, &wasm_bytes)
.context("Failed to validate and compile WebAssembly module")?;
// 3. Initialize the store with guest context and an execution budget
let initial_fuel = 20_000;
let mut store = Store::new(&engine, HostState { invocations: 0 });
store.set_fuel(initial_fuel)?;
// 4. Instantiate the module inside our sandbox
let instance = Instance::new(&mut store, &module, &[])
.context("Failed to instantiate guest module")?;
println!("[Host] Sandbox initialized with {} units of fuel.", initial_fuel);
// 5. Bind exported functions to typed Rust signatures
let calculate_discount: TypedFunc<(f64, i32), f64> = instance
.get_typed_func(&mut store, "calculate_discount")?;
let is_authorized: TypedFunc<i32, i32> = instance
.get_typed_func(&mut store, "is_authorized")?;
// 6. Invoke calculations
let order_value = 1_500.0;
let user_tier = 3;
let discount = calculate_discount.call(&mut store, (order_value, user_tier))?;
let auth_status = is_authorized.call(&mut store, 102)?;
println!("[Host] Order: ${:.2} | Tier {} => Discount: ${:.2}", order_value, user_tier, discount);
println!("[Host] Role check (102): {}", if auth_status == 1 { "Approved" } else { "Denied" });
// Check fuel consumed
let remaining = store.get_fuel()?;
println!("[Host] Fuel remaining: {} (Used: {})", remaining, initial_fuel - remaining);
Ok(())
}
Verification & Fault Injection
A resilient sandbox needs active verification. We must confirm that valid calls return expected outputs, instruction counters drop reliably, and hostile loops trap cleanly without freezing the main process.
1. Test Normal Invocations
Run the host from the project root:
cargo run -p plugin_host
Wasmtime executes both calls in under 50 microseconds:
[Host] Sandbox initialized with 20000 units of fuel.
[Host] Order: $1500.00 | Tier 3 => Discount: $300.00
[Host] Role check (102): Approved
[Host] Fuel remaining: 19894 (Used: 106)
Both function calls consumed only 106 units of fuel total. Arithmetic operations and basic branching in Wasm cost roughly 1 unit of fuel per instruction.
2. Simulate an Infinite Loop
What happens when a plugin author writes an accidental infinite loop? Let’s test the boundary. Add an untamed loop to guest_plugin/src/lib.rs:
#[no_mangle]
pub extern "C" fn runaway_loop() {
let mut _counter: u64 = 0;
loop {
_counter = _counter.wrapping_add(1);
}
}
Recompile the guest crate:
cargo build -p guest_plugin --target wasm32-unknown-unknown --release
In plugin_host/src/main.rs, allocate a strict budget of 5,000 fuel units and trigger the runaway function:
store.set_fuel(5_000)?;
let bad_func: TypedFunc<(), ()> = instance.get_typed_func(&mut store, "runaway_loop")?;
match bad_func.call(&mut store, ()) {
Ok(_) => println!("Unexpected completion!"),
Err(trap) => println!("[Trap Caught] Plugin terminated safely: {}", trap),
}
Run the host application again:
[Trap Caught] Plugin terminated safely: all fuel consumed by WebAssembly
Execution halted instantly. The guest burned through its 5,000-instruction quota, triggered an out-of-fuel trap, and returned control to Rust in less than 2 milliseconds. The host thread never hung.
Production Best Practices
- Reset fuel per request: Never share accumulated fuel counters between calls. Call
store.set_fuel(budget)immediately before dispatching each plugin invocation. For lightweight data parsing, 10,000 to 50,000 fuel units is usually plenty. - Set memory limits: Combine fuel metering with
wasmtime::StoreLimitsBuilderto cap maximum linear memory (for example, limiting modules to 4 MB). This stops allocation attacks before they stress the OS page table. - Treat traps as expected results: Trapped executions bubble up as
wasmtime::Traperrors insideanyhow::Error. Intercept them at the API layer, increment a Prometheus error metric, and return a clean422 Unprocessable Entityresponse to the user. - Keep parameter signatures primitive: Start with raw 32-bit and 64-bit integers and floats. If you need to exchange strings or JSON payloads, use byte slices inside guest memory or adopt the WebAssembly Component Model with
wit-bindgen.

