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.
All Examples
Hello World
Minimal Flat API example β chain transitions to build and transform a greeting.
#[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.
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
Server-Sent Events for real-time streaming responses to clients.
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)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)Reference E-commerce Order
Complete Saga pipeline with compensation, audit trail, multi-tenancy, and RFC 7807 errors.
// Saga: CreateOrder β ProcessPayment β ReserveInventory β ScheduleShipping
// β (comp) β (comp)
// RefundPayment ReleaseInventoryReference Chat Server
Multi-room WebSocket chat with JWT auth, REST + WS hybrid routing, and message persistence.
Reference Todo API
Complete CRUD application with JWT authentication, Bus dependency injection, HTTP routing, and collection-based testing.
// 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>.