Self-Hosted WebAssembly Component Model: Building Polyglot Microservices with WASI and Kubernetes
Quick Summary (TL;DR)
- The WebAssembly Component Model lets you compose modules written in different languages into a single, well-typed service using WIT (WebAssembly Interface Types) as the contract.
- WASI Preview 2 brings component-based, capability-secure system interfaces (HTTP, filesystem, clocks) that make Wasm a first-class server-side target.
- You build components with
cargo-component, TinyGo, or Jco, compose them withwasm-tools, and run them on Kubernetes via SpinKube (K8s-native) or wasmCloud (distributed app platform).- Wasm components start in milliseconds, run in a sandbox by default, and are far smaller than containers—ideal for polyglot microservices.
The WebAssembly Component Model has quietly become the most credible answer to a decade-old question: how do we run code from many languages in one system without drowning in glue code, containers, and conflicting runtimes? This guide walks you through building a real polyglot microservice—one business logic written in Rust, a data transform in Go, and a JavaScript frontend adapter—then composing and deploying it on Kubernetes with SpinKube or wasmCloud. By the end you’ll have a working mental model, concrete configuration, and a production checklist.
Introduction to the WebAssembly Component Model
What is the Component Model?
At its core, WebAssembly (Wasm) is a portable bytecode format. Historically, each Wasm module was an isolated island: it could import/export raw functions with numeric signatures, but could not pass a string, a list, or a record to another module without manual memory management. The Component Model fixes this by introducing a typed interface layer. A component is a Wasm module wrapped with rich type information describing exactly what it imports and exports—strings, records, variants, lists, resources—using an IDL called WIT.
The result: two components written in different languages can call each other as if they were native libraries, with the runtime handling the ABI marshalling.
flowchart TD
A["WIT Interface (.wit)<br/>typed contract"] --> B["Rust Component<br/>(cargo-component)"]
A --> C["Go Component<br/>(TinyGo)"]
A --> D["JS Component<br/>(Jco)"]
B --> E["wasm-tools compose"]
C --> E
D --> E
E --> F["Single Composed<br/>Component"]
F --> G["WASI Preview 2<br/>Runtime"]
G --> H["Kubernetes<br/>SpinKube / wasmCloud"]
Why Polyglot Microservices?
Polyglot architectures let teams pick the right tool per problem: Rust for CPU-bound transforms, Go for networking, JavaScript for edge-facing adapters. But traditional polyglot microservices pay a heavy tax—each language ships its own container, runtime, and startup cost, and cross-service calls go over the network even when they’re logically one service.
The Component Model removes that tax. Components compose in-process: a Rust function can call a Go function directly, with no HTTP hop, no serialization to JSON, and no container boundary. You keep language diversity while collapsing the operational surface.
WASI Preview 2: The New Standard for System Interfaces
Key Features of WASI Preview 2
WASI (WebAssembly System Interface) is the standard that gives Wasm access to the outside world. Preview 2 is a complete re-architecture built on top of the Component Model, split into modular, versioned interfaces:
| WASI Interface | Purpose | Typical Use |
|---|---|---|
wasi:http | Incoming/outgoing HTTP | Request handlers, API calls |
wasi:filesystem | Sandboxed file access | Config, temp storage |
wasi:clocks | Monotonic/wall clocks | Timeouts, logging |
wasi:io | Streams and polling | Async I/O plumbing |
wasi:sockets | Network sockets | Custom protocols |
wasi:random | Cryptographically secure RNG | Tokens, keys |
Crucially, each interface is capability-based: a component can only use what its host explicitly grants. No ambient authority, no “just open a socket.”
Migrating from Preview 1
Preview 1 exposed a monolithic wasi_snapshot_preview1 module with dozens of flat functions. Preview 2 replaces it with typed, composable interfaces. Migration guidance:
- Runtimes: move to a Preview 2-capable host (Wasmtime 18+, Spin 2.x, wasmCloud 1.x). Most modern toolchains now default to Preview 2 targets.
- Tooling: adopt
wit-bindgen(orcargo-component) so bindings are generated from WIT rather than hand-written. - Behavioral changes:
wasi:httpis now async-first; blocking file I/O is discouraged in favor of streams. Audit any tight loops that relied on Preview 1’s synchronous model.
Building a Polyglot Microservice with Components
Step 1: Define the Component Interface with WIT
Everything starts with the contract. Create wit/world.wit:
package example:[email protected];
interface pricing {
record order { id: string, amount-cents: u64, currency: string }
compute-total: func(order: order) -> u64;
}
interface formatting {
format-currency: func(cents: u64, currency: string) -> string;
}
world orders-service {
import pricing;
import formatting;
export handle: func(raw-json: string) -> string;
}
This world declares a service that imports pricing and formatting logic and exports a single handle function. The Rust, Go, and JS components will each satisfy one piece.
Step 2: Implement Components in Different Languages
Generate bindings and implement each piece. For the Rust pricing component:
// cargo component new pricing --target wasm32-wasi
use bindings::example::orders::pricing::{Order, compute_total};
struct Pricing;
impl bindings::exports::example::orders::pricing::Guest for Pricing {
fn compute_total(order: Order) -> u64 {
order.amount_cents + (order.amount_cents / 10) // +10% tax
}
}
bindings::export!(Pricing with_types_in bindings);
The Go formatting component uses TinyGo’s wit-bindgen output; the JS adapter uses jco. Each compiles to a .wasm component with the same typed interface—no manual ABI code.
Step 3: Compose Components into a Microservice
Compose the three components into one:
wasm-tools compose \
-d pricing.wasm \
-d formatting.wasm \
-o service.wasm \
adapter.wasm
The output service.wasm is a single deployable artifact that satisfies the orders-service world. Internally, calls between components are direct function calls—no network, no JSON.
Deploying to Kubernetes with SpinKube or wasmCloud
SpinKube: Kubernetes-Native WebAssembly
SpinKube is a CNCF sandbox project that runs Spin apps on Kubernetes using a containerd shim (containerd-shim-spin). It registers a new RuntimeClass so Wasm workloads schedule like any pod—no sidecar, no separate control plane.
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders-service
spec:
replicas: 3
selector:
matchLabels: { app: orders-service }
template:
metadata:
labels: { app: orders-service }
spec:
runtimeClassName: wasmtime-spin-v2
containers:
- name: orders
image: ghcr.io/example/orders-service:0.1.0
resources:
requests: { cpu: "50m", memory: "32Mi" }
limits: { cpu: "200m", memory: "64Mi" }
Install the operator once with kubectl apply -f https://github.com/spinframework/spin-operator/releases/latest/download/spin-operator.yaml (or via Helm), and your Wasm pods run alongside traditional containers.
wasmCloud: A Distributed Application Platform
wasmCloud takes a higher-level approach. It runs a lattice of hosts (nodes) and deploys actors (components) that link to capability providers (HTTP servers, KV stores, message brokers). You describe apps in a wadm.yaml manifest and wash handles rollout, scaling, and linking—abstracting away pods entirely.
apiVersion: core.oam.dev/v1beta1
kind: Application
metadata:
name: orders
spec:
components:
- name: orders-service
type: component
properties:
image: ghcr.io/example/orders-service:0.1.0
traits:
- type: spreadscaler
properties: { instances: 3 }
- type: link
properties:
target: httpserver
package: wasmcloud:httpserver
Comparison: SpinKube vs. wasmCloud
| Aspect | SpinKube | wasmCloud |
|---|---|---|
| Abstraction level | Kubernetes-native (pods, RuntimeClass) | Application platform (actors, links) |
| Best for | Teams already deep in K8s | Teams wanting infra-agnostic DX |
| Scheduling | Native K8s scheduler | wasmCloud lattice + wadm |
| Capabilities | Via Spin plugins / host | First-class capability providers |
| Observability | Standard K8s tooling (Prometheus, OTel) | Built-in NATS-based telemetry |
| Learning curve | Low if you know K8s | Moderate (new concepts) |
| Runtime | Spin / Wasmtime | wasmCloud host (Wasmtime-based) |
Best Practices for Production Deployments
Security Considerations
- Lean on capability-based security. Only grant the WASI interfaces a component actually declares. A pricing component needs no filesystem and no sockets—don’t grant them.
- Sign and verify components. Use
cosignto sign.wasmOCI artifacts and enforce signature verification in your admission controller. - Pin runtime versions. Wasmtime and Spin ship security fixes regularly; treat upgrades as you would a container base image.
- Scan dependencies.
cargo audit,govulncheck, andnpm auditapply to your Wasm sources too.
Observability and Debugging
Wasm components don’t have a shell, so debugging shifts left. Use structured logging via wasi:logging, emit OpenTelemetry traces from the runtime host (Spin and wasmCloud both support OTel), and keep wasm-tools print handy to inspect compiled components. For local iteration, spin up or wash dev give hot-reload loops that feel like any modern dev server.
Performance Tuning
- Right-size memory. Wasm components often run in 16–64 MiB; don’t copy container limits blindly.
- Precompile modules. Wasmtime’s ahead-of-time compilation (cranelift) removes JIT warmup—SpinKube does this at image build time.
- Batch in-process calls. Since composed components call each other directly, prefer a few rich calls over many tiny ones to amortize any host-boundary crossings.
- Scale aggressively. With millisecond cold starts, high replica counts are cheap; horizontal scaling beats vertical tuning.
Conclusion
The WebAssembly Component Model, paired with WASI Preview 2, finally delivers on the polyglot promise: write each piece in its native language, compose them with typed contracts, and run them with container-grade orchestration but a fraction of the footprint. SpinKube is the pragmatic choice if your team lives in Kubernetes; wasmCloud shines when you want infrastructure to disappear behind a capability model. Either way, the path is the same—define WIT, implement in your languages of choice, compose, and deploy. Start with one non-critical service, measure cold-start and memory wins, and expand from there.
FAQ
What is the WebAssembly Component Model and why does it matter for microservices? It’s a specification that lets Wasm modules be composed into larger components with well-defined, typed interfaces. For microservices, it enables polyglot applications where each service can be written in a different language yet interoperate seamlessly through standardized interfaces—improving modularity, security, and performance.
How does WASI Preview 2 differ from Preview 1? Preview 2 is a component-based re-architecture with richer, versioned APIs (HTTP, filesystem, clocks) defined via interface types. It offers better composability, stronger capability-based security, and improved performance versus the monolithic, limited Preview 1.
Can I run WebAssembly components on Kubernetes without a specialized runtime? Technically yes, but specialized runtimes like SpinKube or wasmCloud provide optimized scheduling, component-aware networking, and integrated observability. They’re designed for Wasm’s unique characteristics and are the recommended production choice.
What are the main differences between SpinKube and wasmCloud? SpinKube is Kubernetes-native, integrating with the K8s API and ecosystem via a containerd shim—ideal for teams already invested in Kubernetes. wasmCloud is a distributed application platform that abstracts infrastructure and offers a higher-level developer experience with built-in capabilities like messaging and key-value storage.
How do I ensure security when using WebAssembly components? Wasm is sandboxed by default. Enhance security with capability-based WASI grants, signed and verified components, least-privilege principles, updated runtimes, and dependency scanning.