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. testing-patterns4. custom-error-types5. routing-demo

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-api

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. auth-jwt-role3. session-pattern

All Examples

Hello World

core Beginner

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

~5 min
#[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
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> { .. }

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

Server-Sent Events for real-time streaming responses to clients.

~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

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);

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

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

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

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)

Reference E-commerce Order

core Advanced

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

~40 min
// Saga: CreateOrder → ProcessPayment → ReserveInventory → ScheduleShipping
//          ↓ (comp)          ↓ (comp)
//      RefundPayment    ReleaseInventory

Reference Chat Server

core Advanced

Multi-room WebSocket chat with JWT auth, REST + WS hybrid routing, and message persistence.

~35 min

Reference Todo API

core Intermediate

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

~30 min
// 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 }
All examples live under ranvier/examples in the GitHub repository. Clone and run with cargo run -p <package>.