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

beginner

Build your first Axon workflow in under 30 minutes.

1. hello-world2. typed-state-tree3. outcome-variants4. testing-patterns5. custom-error-types6. routing-demo7. closure-transition

HTTP Services

intermediate

Build production HTTP APIs with routing, auth, and real-time features.

1. routing-params2. flat-api3. session-pattern4. multipart-upload5. websocket6. sse-streaming7. openapi8. reference-todo-api9. admin-crud

Advanced Patterns

advanced

Master resilience, persistence, and enterprise patterns.

1. order-processing2. retry-dlq3. state-persistence4. multitenancy5. llm-content-moderation6. reference-ecommerce-order

Authentication & Security

intermediate

Secure your APIs with Guard nodes, JWT authentication, and role-based access control.

1. guard-demo2. guard-integration3. auth-jwt-role4. auth-transition5. session-pattern

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

core Beginner

Minimal Flat API example — chain transitions to build and transform a greeting.

~5 min
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

core Intermediate

Complete CRUD application with JWT authentication, Bus dependency injection, HTTP routing, and collection-based testing.

~30 min
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

core Intermediate

Domain-driven workflow: validation, payment, inventory reservation, and shipping.

~20 min
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

core Intermediate

Bridge example: JWT login, SQLite-backed admin CRUD, pagination/search, and OpenAPI in one mid-sized backend.

~35 min
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

core Advanced

Public-only fullstack reference app with a Ranvier backend, SvelteKit frontend, JWT login, dashboard, and user administration.

~40 min
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

core Advanced

Complete Saga pipeline with compensation, audit trail, multi-tenancy, and RFC 7807 errors.

~40 min
cargo run -p reference-ecommerce-order
  • saga compensation flow
  • order reference app surface
// Saga: CreateOrder → ProcessPayment → ReserveInventory → ScheduleShipping
//          ↓ (comp)          ↓ (comp)
//      RefundPayment    ReleaseInventory

Reference Chat Server

core Advanced

Canonical WebSocket reference: multi-room chat with JWT auth, REST + WS hybrid routing, health/readiness probes, and graceful shutdown.

~35 min
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

core Advanced

Cross-cutting backend example combining JWT auth, policy checks, audit logging, SQLite persistence, and RFC 7807-style errors.

~30 min
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

Tier
Category
Pattern
Domain

Hello World

core Beginner

Minimal Flat API example — chain transitions to build and transform a greeting.

~5 min
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

core Beginner

Type-safe decision flows using Rust enums with Axon, Transition, and Outcome.

~10 min
let flow = Axon::new("flow")
    .then(validate)
    .then(process);

Basic Schematic

core Beginner

Axon flow visualization with schematic extraction for debugging and documentation.

~10 min

Decision Tree Routing

core Intermediate

Outcome::Branch for prefix-based path routing with nested decision trees.

~15 min

Order Processing Workflow

core Intermediate

Domain-driven workflow: validation, payment, inventory reservation, and shipping.

~20 min
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

core Intermediate

Declarative allow/deny access control via @transition bus attributes.

~15 min
#[transition(bus_allow = "db,cache")]
async fn fetch(input: Req) -> Outcome<Resp, String> { .. }

Outcome Variants

core Beginner

All 5 Outcome variants: Next (linear), Fault (error), Branch (conditional), Jump (loop), Emit (side-effect).

~15 min
// 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 event

Closure Transitions

core Beginner

Inline closure transitions with then_fn(), Axon::typed(), and post_typed() for lightweight pipelines.

~10 min
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

core Beginner

Type-safe extraction of path, query, and body parameters in HTTP handlers.

~10 min

Flat API Pattern

core Beginner

@transition and @ranvier_router macros for concise route definitions.

~10 min
#[ranvier_router]
fn routes() -> Router {
    route!(GET "/users" => list_users);
    route!(POST "/users" => create_user);
}

Session Patterns

core Intermediate

Advanced session lifecycle patterns: creation, validation, expiration, and cleanup.

~15 min

Multipart Upload

core Intermediate

File upload handling with multipart/form-data extraction and validation.

~15 min

WebSocket Ingress

core Intermediate

WebSocket connections with event-based messaging and session context.

~20 min

WebSocket Echo Loop

core Intermediate

Bidirectional WebSocket communication with echo loop and connection lifecycle.

~15 min

SSE Streaming

core Intermediate

Canonical SSE request-boundary reference with typed input, guards, and health/readiness probes.

~15 min

OpenAPI Documentation

core Intermediate

Auto-generated OpenAPI/Swagger docs with schema validation via schemars.

~20 min

Static File Serving

core Beginner

Serve static files and build assets from configurable directories.

~10 min

SPA Hosting

core Beginner

Single-page application hosting with fallback routing and asset serving.

~10 min

Typed JSON API

core Intermediate

Type-safe JSON endpoints using get_json_out, post_typed_json_out, BusHttpExt, and CorsGuard::permissive().

~20 min
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

core Intermediate

Bridge example: JWT login, SQLite-backed admin CRUD, pagination/search, and OpenAPI in one mid-sized backend.

~35 min
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

core Intermediate

HTTP security pipeline using CorsGuard, RateLimitGuard, SecurityHeadersGuard, and IpFilterGuard as visible Transition nodes.

~15 min
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

core Intermediate

IamVerifier implementation with HS256 JWT, IamPolicy::RequireRole, and Axon::with_iam() boundary verification.

~20 min
let admin_circuit = Axon::new("admin-dashboard")
    .with_iam(
        IamPolicy::RequireRole("admin".into()),
        JwtVerifier,
    )
    .then(AdminDashboard);

Guard Integration

core Intermediate

Pipeline-first middleware: 10 Guards (global + per-route), guards![] macro, Tower replacement.

~25 min
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

core Intermediate

Authentication implemented as a composable Transition node with Bus-based context propagation.

~20 min

Crash Recovery & Persistence

core Intermediate

Workflow crash recovery, checkpointing, and compensation hooks.

~20 min
Axon::new("resilient")
    .then(step_a)
    .then(step_b)
    .with_persistence(store)
    .with_compensation(rollback);

Redis Integration

core Intermediate

Redis for session storage and caching with async ConnectionManager.

~20 min

SeaORM Integration

core Intermediate

Sea ORM for database operations with migrations and active models.

~25 min

SQLx Database Integration

core Intermediate

SQLx pool injected via Bus with Transition-based queries using in-memory SQLite.

~20 min
let db = DbPool(pool);
let insert_axon = Axon::new("insert-user")
    .then(InsertUser);
insert_axon.execute(req, &db, &mut bus).await;

Traced Wrapper

core Intermediate

Automatic span generation in transitions with Traced wrapper and ConnectionBus.

~20 min

Synapse Integration

core Intermediate

Core Synapse trait for type-safe external service calls (DB, API, messaging).

~20 min

Production Configuration

core Intermediate

ranvier.toml config, environment overrides, profiles, structured logging, and graceful shutdown.

~15 min

Standard Library

core Intermediate

Built-in transitions: FilterNode, SwitchNode, LogNode for pipeline composition.

~15 min

Multi-Tenancy

core Intermediate

Tenant isolation patterns with Bus-injected TenantId and scoped data access.

~20 min

External Service Call

core Intermediate

Wrap HTTP service calls as Transitions with outcome-based error mapping and retry/timeout.

~15 min

Testing Patterns

core Beginner

Unit and integration testing strategies for Transitions and Axon chains.

~15 min

Custom Error Types

core Beginner

Domain-specific error enums with thiserror for type-safe error handling.

~15 min

Outcome Patterns

core Intermediate

try_outcome! macro, Outcome::from_result(), and_then/map_fault combinators, Bus::get_cloned(), and json_outcome().

~20 min
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

core Intermediate

DLQ retry with exponential backoff, timeout patterns, and circuit breaker.

~25 min
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

core Intermediate

Durable workflow execution with fault recovery, checkpointing, and compensation.

~25 min

Resilience Patterns

core Intermediate

Axon-level resilience: then_with_timeout(), then_with_retry(), and transient failure handling.

~20 min
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

core Intermediate

3-stage LLM pipeline: content extraction, AI classification, and policy enforcement.

~25 min
// ExtractContent → ModerateContent → ApplyPolicy
Axon::new("moderate")
    .then(extract_content)
    .then(moderate_content)
    .then(apply_policy)

Request Governance Demo

core Advanced

Cross-cutting backend example combining JWT auth, policy checks, audit logging, SQLite persistence, and RFC 7807-style errors.

~30 min
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

core Advanced

Complete Saga pipeline with compensation, audit trail, multi-tenancy, and RFC 7807 errors.

~40 min
cargo run -p reference-ecommerce-order
  • saga compensation flow
  • order reference app surface
// Saga: CreateOrder → ProcessPayment → ReserveInventory → ScheduleShipping
//          ↓ (comp)          ↓ (comp)
//      RefundPayment    ReleaseInventory

Reference Chat Server

core Advanced

Canonical WebSocket reference: multi-room chat with JWT auth, REST + WS hybrid routing, health/readiness probes, and graceful shutdown.

~35 min
cargo run -p reference-chat-server
  • health/ready/live probes
  • unauthenticated websocket auth_failed frame
  • authenticated join/history/message websocket flow

Reference Fullstack Admin

core Advanced

Public-only fullstack reference app with a Ranvier backend, SvelteKit frontend, JWT login, dashboard, and user administration.

~40 min
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

core Intermediate

Complete CRUD application with JWT authentication, Bus dependency injection, HTTP routing, and collection-based testing.

~30 min
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

core Intermediate

Multi-step compensation chain — when a step fails, completed steps roll back in reverse order.

~20 min
// Reserve → Charge → Ship (compensate in reverse on failure)
let saga = Axon::<Order, Order, String>::new("OrderSaga")
    .then(ReserveInventory)
    .then(ChargePayment)
    .then(ConfirmShipping);

Cascade Screening

core Intermediate

Sequential filter pipeline with fail-fast — each screen can reject and short-circuit the chain.

~20 min
// Sanctions → PEP → Risk Score → Documents
let screening = Axon::<Applicant, Applicant, String>::new("Screening")
    .then(SanctionsCheck)
    .then(PepCheck)
    .then(RiskScoring)
    .then(DocumentVerification);

LLM Agent Pipeline

core Intermediate

Multi-stage typed pipeline — classify intent, select tool, execute, and format response.

~20 min
// Query → ClassifiedQuery → ToolResult → Response
let pipeline = Axon::<Query, Query, String>::new("AgentPipeline")
    .then(ClassifyIntent)
    .then(ExecuteTool)
    .then(FormatResponse);

Sensor Decision Loop

core Intermediate

Sensor data flows through threshold evaluation to produce actuator commands.

~20 min
// SensorReading → EvaluatedReading → ActuatorCommand
let pipeline = Axon::<SensorReading, SensorReading, String>::new("SensorDecision")
    .then(EvaluateThresholds)
    .then(MakeDecision);

Triage Branching

core Intermediate

Multi-stage classification using Outcome::Branch to route subjects to named departments.

~20 min
// Vitals → Severity → Department routing
let triage = Axon::<Patient, Patient, String>::new("PatientTriage")
    .then(AssessVitals)
    .then(ClassifySeverity)
    .then(RouteToDepartment);

Eligibility Rule Chain

core Intermediate

Sequential independent rules with fail-fast — each rule can reject, rules are reorderable.

~20 min
// Age → Income → Residency → BenefitCap
let rules = Axon::<Applicant, Applicant, String>::new("Eligibility")
    .then(AgeRule)
    .then(IncomeRule)
    .then(ResidencyRule)
    .then(BenefitCapRule);
All examples live under ranvier/examples in the GitHub repository. Clone and run with cargo run -p <package>.