Examples
Learn by example.
Explore categorized examples covering core concepts, HTTP routing, auth, persistence, observability, and protocol adapters. Each card links to the full source in the GitHub repository.
Learning Paths
Follow a guided path from beginner to advanced.
Quick Start
beginnerBuild your first Axon workflow in under 30 minutes.
HTTP Services
intermediateBuild production HTTP APIs with routing, auth, and real-time features.
Advanced Patterns
advancedMaster resilience, persistence, and enterprise patterns.
Authentication & Security
intermediateSecure your APIs with Guard nodes, JWT authentication, and role-based access control.
Official Example Track
This is the official learning order. Start with Hello World, then move through CRUD and workflow examples before the bridge/reference surfaces.
Hello World
Minimal Flat API example — chain transitions to build and transform a greeting.
cargo run -p hello-world
- server startup log
- simple greeting response
#[transition]
async fn greet(input: String) -> Outcome<String, String> {
Outcome::Next(format!("Hello, {input}!"))
}Reference Todo API
Complete CRUD application with JWT authentication, Bus dependency injection, HTTP routing, and collection-based testing.
cargo run -p reference-todo-api
- POST /login
- GET/POST/PUT/DELETE /todos
// Single-transition Axon circuits per endpoint
POST /login -> [login] -> JWT token
GET /todos -> [list_todos] -> Vec<Todo>
POST /todos -> [create_todo] -> Todo
PUT /todos/:id -> [update_todo] -> Todo
DELETE /todos/:id -> [delete_todo] -> { deleted }Order Processing Workflow
Domain-driven workflow: validation, payment, inventory reservation, and shipping.
cargo run -p order-processing-demo
- validation -> inventory -> payment -> shipping flow
- success and failure-path logs
Axon::new("order")
.then(validate_order)
.then(process_payment)
.then(reserve_inventory)
.then(arrange_shipping)Bridge & Reference
Continue from the official track into the admin-style bridge backend and the public-only reference app.
Admin CRUD Demo
Bridge example: JWT login, SQLite-backed admin CRUD, pagination/search, and OpenAPI in one mid-sized backend.
cargo run -p admin-crud-demo
- JWT login
- users CRUD
- OpenAPI JSON
- Swagger UI parity
Ranvier::http()
.post_typed_json_out("/login", login)
.get_json_out("/users", list_users)
.post_typed_json_out("/users", create_user)
.put_typed_json_out("/users/:id", update_user)
.delete_json_out("/users/:id", delete_user)Reference Fullstack Admin
Public-only fullstack reference app with a Ranvier backend, SvelteKit frontend, JWT login, dashboard, and user administration.
cargo run -p reference-fullstack-admin cd examples/reference-fullstack-admin/frontend && npm install && npm run dev
- backend login/dashboard/users surface
- frontend login/dashboard/users surface
Ranvier::http()
.guard(CorsGuard::<AppState>::permissive())
.post_typed_json_out("/login", login)
.get_json_out("/dashboard", dashboard)
.get_json_out("/users", list_users)Reference E-commerce Order
Complete Saga pipeline with compensation, audit trail, multi-tenancy, and RFC 7807 errors.
cargo run -p reference-ecommerce-order
- saga compensation flow
- order reference app surface
// Saga: CreateOrder → ProcessPayment → ReserveInventory → ScheduleShipping
// ↓ (comp) ↓ (comp)
// RefundPayment ReleaseInventoryReference Chat Server
Canonical WebSocket reference: multi-room chat with JWT auth, REST + WS hybrid routing, health/readiness probes, and graceful shutdown.
cargo run -p reference-chat-server
- health/ready/live probes
- unauthenticated websocket auth_failed frame
- authenticated join/history/message websocket flow
Governance & Operability
Separate from the OpenAPI surface, inspect a service that combines structured errors, audit logging, and guard-backed observability in one operability example.
Request Governance Demo
Cross-cutting backend example combining JWT auth, policy checks, audit logging, SQLite persistence, and RFC 7807-style errors.
cargo run -p request-governance-demo
- 403 application/problem+json on insufficient-role approval
- 200 on approver approval
- audit event writes
Ranvier::http()
.post_typed_json_out("/login", login)
.post_typed_json_out("/requests", create_request)
.get_with_error("/requests/:id", get_request, governance_error_response)
.post_with_error("/requests/:id/approve", approve_request, governance_error_response)All Examples
Hello World
Minimal Flat API example — chain transitions to build and transform a greeting.
cargo run -p hello-world
- server startup log
- simple greeting response
#[transition]
async fn greet(input: String) -> Outcome<String, String> {
Outcome::Next(format!("Hello, {input}!"))
}Typed State Tree
Type-safe decision flows using Rust enums with Axon, Transition, and Outcome.
let flow = Axon::new("flow")
.then(validate)
.then(process);Basic Schematic
Axon flow visualization with schematic extraction for debugging and documentation.
Decision Tree Routing
Outcome::Branch for prefix-based path routing with nested decision trees.
Order Processing Workflow
Domain-driven workflow: validation, payment, inventory reservation, and shipping.
cargo run -p order-processing-demo
- validation -> inventory -> payment -> shipping flow
- success and failure-path logs
Axon::new("order")
.then(validate_order)
.then(process_payment)
.then(reserve_inventory)
.then(arrange_shipping)Bus Capability System
Declarative allow/deny access control via @transition bus attributes.
#[transition(bus_allow = "db,cache")]
async fn fetch(input: Req) -> Outcome<Resp, String> { .. }Outcome Variants
All 5 Outcome variants: Next (linear), Fault (error), Branch (conditional), Jump (loop), Emit (side-effect).
// Outcome<T, E> — control flow as data
Outcome::Next(value) // linear progression
Outcome::Fault(err) // error path
Outcome::Branch("name", v) // conditional routing
Outcome::Jump("node", v) // goto / loop
Outcome::Emit(event) // side-effect eventClosure Transitions
Inline closure transitions with then_fn(), Axon::typed(), and post_typed() for lightweight pipelines.
Axon::typed::<GreetRequest, String>("greet")
.then_fn("validate", |req, _bus| {
if req.name.is_empty() {
Outcome::Fault("empty".into())
} else {
Outcome::Next(req.name)
}
})
.then_fn("format", |name, _bus| {
Outcome::Next(json!({"message": format!("Hello, {name}!")}))
})Route Parameters
Type-safe extraction of path, query, and body parameters in HTTP handlers.
Flat API Pattern
@transition and @ranvier_router macros for concise route definitions.
#[ranvier_router]
fn routes() -> Router {
route!(GET "/users" => list_users);
route!(POST "/users" => create_user);
}Session Patterns
Advanced session lifecycle patterns: creation, validation, expiration, and cleanup.
Multipart Upload
File upload handling with multipart/form-data extraction and validation.
WebSocket Ingress
WebSocket connections with event-based messaging and session context.
WebSocket Echo Loop
Bidirectional WebSocket communication with echo loop and connection lifecycle.
SSE Streaming
Canonical SSE request-boundary reference with typed input, guards, and health/readiness probes.
OpenAPI Documentation
Auto-generated OpenAPI/Swagger docs with schema validation via schemars.
Static File Serving
Serve static files and build assets from configurable directories.
SPA Hosting
Single-page application hosting with fallback routing and asset serving.
Typed JSON API
Type-safe JSON endpoints using get_json_out, post_typed_json_out, BusHttpExt, and CorsGuard::permissive().
Ranvier::http()
.get_json_out("/items", list_items_axon)
.post_typed_json_out::<CreateItem, _, _>("/items", create_item_axon)
.delete_json_out("/items/:id", delete_item_axon)Admin CRUD Demo
Bridge example: JWT login, SQLite-backed admin CRUD, pagination/search, and OpenAPI in one mid-sized backend.
cargo run -p admin-crud-demo
- JWT login
- users CRUD
- OpenAPI JSON
- Swagger UI parity
Ranvier::http()
.post_typed_json_out("/login", login)
.get_json_out("/users", list_users)
.post_typed_json_out("/users", create_user)
.put_typed_json_out("/users/:id", update_user)
.delete_json_out("/users/:id", delete_user)Guard Pipeline
HTTP security pipeline using CorsGuard, RateLimitGuard, SecurityHeadersGuard, and IpFilterGuard as visible Transition nodes.
Axon::new("Guarded API")
.then(CorsGuard::new(cors_config))
.then(RateLimitGuard::new(100, 60_000))
.then(SecurityHeadersGuard::new(policy))
.then(IpFilterGuard::allow_list(["127.0.0.1"]))
.then(HelloHandler)JWT Role-Based Auth
IamVerifier implementation with HS256 JWT, IamPolicy::RequireRole, and Axon::with_iam() boundary verification.
let admin_circuit = Axon::new("admin-dashboard")
.with_iam(
IamPolicy::RequireRole("admin".into()),
JwtVerifier,
)
.then(AdminDashboard);Guard Integration
Pipeline-first middleware: 10 Guards (global + per-route), guards![] macro, Tower replacement.
Ranvier::http()
.guard(CorsGuard::<()>::new(cors_config))
.guard(CompressionGuard::<()>::new())
.guard(AuthGuard::<()>::bearer(tokens))
.get("/api/hello", hello_circuit)
.post_with_guards("/api/orders", order_circuit, guards![
TimeoutGuard::<()>::new(Duration::from_secs(30)),
ContentTypeGuard::<()>::json(),
IdempotencyGuard::<()>::ttl_5min(),
])Auth as Transition
Authentication implemented as a composable Transition node with Bus-based context propagation.
Crash Recovery & Persistence
Workflow crash recovery, checkpointing, and compensation hooks.
Axon::new("resilient")
.then(step_a)
.then(step_b)
.with_persistence(store)
.with_compensation(rollback);Redis Integration
Redis for session storage and caching with async ConnectionManager.
SeaORM Integration
Sea ORM for database operations with migrations and active models.
SQLx Database Integration
SQLx pool injected via Bus with Transition-based queries using in-memory SQLite.
let db = DbPool(pool);
let insert_axon = Axon::new("insert-user")
.then(InsertUser);
insert_axon.execute(req, &db, &mut bus).await;Traced Wrapper
Automatic span generation in transitions with Traced wrapper and ConnectionBus.
Synapse Integration
Core Synapse trait for type-safe external service calls (DB, API, messaging).
Production Configuration
ranvier.toml config, environment overrides, profiles, structured logging, and graceful shutdown.
Standard Library
Built-in transitions: FilterNode, SwitchNode, LogNode for pipeline composition.
Multi-Tenancy
Tenant isolation patterns with Bus-injected TenantId and scoped data access.
External Service Call
Wrap HTTP service calls as Transitions with outcome-based error mapping and retry/timeout.
Testing Patterns
Unit and integration testing strategies for Transitions and Axon chains.
Custom Error Types
Domain-specific error enums with thiserror for type-safe error handling.
Outcome Patterns
try_outcome! macro, Outcome::from_result(), and_then/map_fault combinators, Bus::get_cloned(), and json_outcome().
let config = try_outcome!(bus.get_cloned::<AppConfig>(), "AppConfig not in Bus");
let result = Outcome::from_result(service.call().await)
.map_fault(|e| AppError::Service(e.to_string()));Retry & Dead Letter Queue
DLQ retry with exponential backoff, timeout patterns, and circuit breaker.
let axon = Axon::new("payment")
.then(gateway)
.with_dlq_policy(DlqPolicy::RetryThenDlq {
max_attempts: 5,
backoff_ms: 100,
})
.with_dlq_sink(dlq);State Persistence & Recovery
Durable workflow execution with fault recovery, checkpointing, and compensation.
Resilience Patterns
Axon-level resilience: then_with_timeout(), then_with_retry(), and transient failure handling.
let axon = Axon::simple::<String>("resilient-api")
.then_with_retry(flaky_service, 3)
.then_with_timeout(slow_service, Duration::from_secs(5));LLM Content Moderation
3-stage LLM pipeline: content extraction, AI classification, and policy enforcement.
// ExtractContent → ModerateContent → ApplyPolicy
Axon::new("moderate")
.then(extract_content)
.then(moderate_content)
.then(apply_policy)Request Governance Demo
Cross-cutting backend example combining JWT auth, policy checks, audit logging, SQLite persistence, and RFC 7807-style errors.
cargo run -p request-governance-demo
- 403 application/problem+json on insufficient-role approval
- 200 on approver approval
- audit event writes
Ranvier::http()
.post_typed_json_out("/login", login)
.post_typed_json_out("/requests", create_request)
.get_with_error("/requests/:id", get_request, governance_error_response)
.post_with_error("/requests/:id/approve", approve_request, governance_error_response)Reference E-commerce Order
Complete Saga pipeline with compensation, audit trail, multi-tenancy, and RFC 7807 errors.
cargo run -p reference-ecommerce-order
- saga compensation flow
- order reference app surface
// Saga: CreateOrder → ProcessPayment → ReserveInventory → ScheduleShipping
// ↓ (comp) ↓ (comp)
// RefundPayment ReleaseInventoryReference Chat Server
Canonical WebSocket reference: multi-room chat with JWT auth, REST + WS hybrid routing, health/readiness probes, and graceful shutdown.
cargo run -p reference-chat-server
- health/ready/live probes
- unauthenticated websocket auth_failed frame
- authenticated join/history/message websocket flow
Reference Fullstack Admin
Public-only fullstack reference app with a Ranvier backend, SvelteKit frontend, JWT login, dashboard, and user administration.
cargo run -p reference-fullstack-admin cd examples/reference-fullstack-admin/frontend && npm install && npm run dev
- backend login/dashboard/users surface
- frontend login/dashboard/users surface
Ranvier::http()
.guard(CorsGuard::<AppState>::permissive())
.post_typed_json_out("/login", login)
.get_json_out("/dashboard", dashboard)
.get_json_out("/users", list_users)Reference Todo API
Complete CRUD application with JWT authentication, Bus dependency injection, HTTP routing, and collection-based testing.
cargo run -p reference-todo-api
- POST /login
- GET/POST/PUT/DELETE /todos
// Single-transition Axon circuits per endpoint
POST /login -> [login] -> JWT token
GET /todos -> [list_todos] -> Vec<Todo>
POST /todos -> [create_todo] -> Todo
PUT /todos/:id -> [update_todo] -> Todo
DELETE /todos/:id -> [delete_todo] -> { deleted }Saga Compensation
Multi-step compensation chain — when a step fails, completed steps roll back in reverse order.
// Reserve → Charge → Ship (compensate in reverse on failure)
let saga = Axon::<Order, Order, String>::new("OrderSaga")
.then(ReserveInventory)
.then(ChargePayment)
.then(ConfirmShipping);Cascade Screening
Sequential filter pipeline with fail-fast — each screen can reject and short-circuit the chain.
// Sanctions → PEP → Risk Score → Documents
let screening = Axon::<Applicant, Applicant, String>::new("Screening")
.then(SanctionsCheck)
.then(PepCheck)
.then(RiskScoring)
.then(DocumentVerification);LLM Agent Pipeline
Multi-stage typed pipeline — classify intent, select tool, execute, and format response.
// Query → ClassifiedQuery → ToolResult → Response
let pipeline = Axon::<Query, Query, String>::new("AgentPipeline")
.then(ClassifyIntent)
.then(ExecuteTool)
.then(FormatResponse);Sensor Decision Loop
Sensor data flows through threshold evaluation to produce actuator commands.
// SensorReading → EvaluatedReading → ActuatorCommand
let pipeline = Axon::<SensorReading, SensorReading, String>::new("SensorDecision")
.then(EvaluateThresholds)
.then(MakeDecision);Triage Branching
Multi-stage classification using Outcome::Branch to route subjects to named departments.
// Vitals → Severity → Department routing
let triage = Axon::<Patient, Patient, String>::new("PatientTriage")
.then(AssessVitals)
.then(ClassifySeverity)
.then(RouteToDepartment);Eligibility Rule Chain
Sequential independent rules with fail-fast — each rule can reject, rules are reorderable.
// Age → Income → Residency → BenefitCap
let rules = Axon::<Applicant, Applicant, String>::new("Eligibility")
.then(AgeRule)
.then(IncomeRule)
.then(ResidencyRule)
.then(BenefitCapRule);cargo run -p <package>.