This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-0-8-state-tower-production-standard

Rust Axum 0.8 Type-Safe State Extraction & Resilient Tower Middleware Stack

Enforces compile-time verified sub-state extraction using Axum 0.8's FromRef pattern instead of runtime-panicking Extension extractors. Mandates strictly ordered Tower ServiceBuilder middleware stacks with CatchPanicLayer and custom rejection types to eliminate silent dropouts and unhandled connection terminations.

Prohibited Anti-Pattern: Fragile Runtime Extension Extractors and Unprotected Tower Middleware Panic Crashes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Rust Axum 0.8 Type-Safe State Extraction & Resilient Tower Middleware Stack - Enforces compile-time verified sub-state extraction using Axum 0.8's FromRef pattern instead of runtime-panicking Extension extractors. Mandates strictly ordered Tower ServiceBuilder middleware stacks with CatchPanicLayer and custom rejection types to eliminate silent dropouts and unhandled connection terminations.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-state-tower-production-standard"
---

# Rust Axum 0.8 Type-Safe State Extraction & Resilient Tower Middleware Stack

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Fragile Runtime Extension Extractors and Unprotected Tower Middleware Panic Crashes

## System Constraints
You are a Principal Rust Architect enforcing Axum 0.8 and Tower production invariants. Reject any usage of runtime `axum::extract::Extension` for core application dependencies. Mandate compile-time type safety via `axum::extract::State` combined with `axum::extract::FromRef` for hierarchical sub-states. Enforce robust Tower middleware pipeline composition through `tower::ServiceBuilder`, ensuring that `CatchPanicLayer`, `TraceLayer`, and rate limiters are composed in strictly validated topological order with zero unhandled panics or opaque 500 Internal Server Error fallbacks.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` and implement `axum::extract::FromRef` for modular state slices rather than relying on `axum::extract::Extension`.
- Engineers MUST NOT place `CatchPanicLayer` inside inner service layers; it MUST wrap the boundary of the incoming HTTP stack to intercept panics before connections terminate abnormally.
- Custom extractors MUST define explicit `rejection` types implementing `axum::response::IntoResponse` with standardized JSON error payloads; untyped `Result<T, Infallible>` or raw tuple strings are prohibited.
- Tower middleware stacks MUST be constructed using `tower::ServiceBuilder::new()` to ensure deterministic layer application order (outermost-to-innermost execution semantics).
- Services MUST NEVER unwrap raw panicking futures inside handler logic; fallible operations must propagate through typed `AppError` enums mapped directly to RFC 7807 problem details or standard error envelopes.
- Axum routers using sub-routing (`Router::nest`) MUST propagate state via strictly typed `.with_state()` or composite state types conforming to sub-router `FromRef` constraints.

## Bad vs Good Implementations
### State Extraction & Tower Panic Boundary Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension defers type resolution to runtime, crashing worker tasks if an extension is absent. The absence of CatchPanicLayer terminates HTTP connections abruptly without clean HTTP responses.
```rust
use axum::{routing::get, Extension, Router};
use std::sync::Arc;

#[derive(Clone)]
struct AppState {
    db: Arc<String>,
}

// ANTI-PATTERN: Extension extraction checks state at runtime;
// if omitted in router wiring, this handler panics with a 500 runtime crash.
async fn handler(Extension(db): Extension<Arc<String>>) -> String {
    // ANTI-PATTERN: Direct panic inside handler without boundary isolation
    if db.is_empty() {
        panic!("Critical database connection missing");
    }
    format!("Connected to {}", db)
}

pub fn make_router() -> Router {
    let state = AppState { db: Arc::new("postgres://...".into()) };
    
    // ANTI-PATTERN: Extension added without compiler safety; no panic catch layer
    Router::new()
        .route("/data", get(handler))
        .layer(Extension(state.db))
}
```

#### Production Standard (Correct)
> **Standard**: Sub-state extraction is verified at compile-time via FromRef and State. Tower ServiceBuilder guarantees CatchPanicLayer is at the perimeter, translating panics to structured 500 JSON payloads.
```rust
use axum::{
    extract::{FromRef, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Json,
    Router,
};
use serde_json::json;
use std::sync::Arc;
use tower::ServiceBuilder;
use tower_http::catch_panic::CatchPanicLayer;
use tower_http::trace::TraceLayer;

#[derive(Clone)]
pub struct AppState {
    pub db_pool: Arc<String>,
    pub redis_pool: Arc<String>,
}

// Compile-time decoupled sub-state extraction
impl FromRef<AppState> for Arc<String> {
    fn from_ref(state: &AppState) -> Self {
        state.db_pool.clone()
    }
}

pub enum AppError {
    Internal(String),
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, msg) = match self {
            AppError::Internal(err) => (StatusCode::INTERNAL_SERVER_ERROR, err),
        };
        let body = Json(json!({ "error": msg }));
        (status, body).into_response()
    }
}

// Handler cleanly extracts specific sub-state with compile-time verification
async fn handler(State(db): State<Arc<String>>) -> Result<String, AppError> {
    if db.is_empty() {
        return Err(AppError::Internal("Database unavailable".to_string()));
    }
    Ok(format!("Connected safely to {}", db))
}

fn handle_panic(err: Box<dyn std::any::Any + Send + 'static>) -> Response {
    let details = if let Some(s) = err.downcast_ref::<&str>() {
        s.to_string()
    } else if let Some(s) = err.downcast_ref::<String>() {
        s.clone()
    } else {
        "Unknown internal panic".to_string()
    };
    
    (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "panic": details }))).into_response()
}

pub fn make_router() -> Router {
    let state = AppState {
        db_pool: Arc::new("postgres://cluster".into()),
        redis_pool: Arc::new("redis://cache".into()),
    };

    let middleware_stack = ServiceBuilder::new()
        .layer(CatchPanicLayer::custom(handle_panic))
        .layer(TraceLayer::new_for_http());

    Router::new()
        .route("/data", get(handler))
        .layer(middleware_stack)
        .with_state(state)
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Rust Axum 0.8 Type-Safe State Extraction & Resilient Tower Middleware Stack

Rust Axum 0.8 Type-Safe State Extraction & Resilient Tower Middleware Stack defines an industrial-grade behavioral standard for backend engineering. Enforces compile-time verified sub-state extraction using Axum 0.8's FromRef pattern instead of runtime-panicking Extension extractors. Mandates strictly ordered Tower ServiceBuilder middleware stacks with CatchPanicLayer and custom rejection types to eliminate silent dropouts and unhandled connection terminations. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Fragile Runtime Extension Extractors and Unprotected Tower Middleware Panic Crashes Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftFragile Runtime Extension Extractors and Unprotected Tower Middleware Panic CrashesCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS use `axum

Engineers MUST ALWAYS use `axum::extract::State` and implement `axum::extract::FromRef` for modular state slices rather than relying on `axum::extract::Extension`.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT place `CatchPanicLayer` inside inner service layers

Engineers MUST NOT place `CatchPanicLayer` inside inner service layers; it MUST wrap the boundary of the incoming HTTP stack to intercept panics before connections terminate abnormally.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Custom extractors MUST define explicit `rejection` types implementing `axum

Custom extractors MUST define explicit `rejection` types implementing `axum::response::IntoResponse` with standardized JSON error payloads; untyped `Result<T, Infallible>` or raw tuple strings are prohibited.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Tower middleware stacks MUST be constructed using `tower

Tower middleware stacks MUST be constructed using `tower::ServiceBuilder::new()` to ensure deterministic layer application order (outermost-to-innermost execution semantics).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Services MUST NEVER unwrap raw panicking futures inside handler logic

Services MUST NEVER unwrap raw panicking futures inside handler logic; fallible operations must propagate through typed `AppError` enums mapped directly to RFC 7807 problem details or standard error envelopes.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Axum routers using sub-routing (`Router

Axum routers using sub-routing (`Router::nest`) MUST propagate state via strictly typed `.with_state()` or composite state types conforming to sub-router `FromRef` constraints.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Rust Axum 0.8 Type-Safe State Extraction & Resilient Tower Middleware Stack critical for AI coding assistants?

Enforces compile-time verified sub-state extraction using Axum 0.8's FromRef pattern instead of runtime-panicking Extension extractors. Mandates strictly ordered Tower ServiceBuilder middleware stacks with CatchPanicLayer and custom rejection types to eliminate silent dropouts and unhandled connection terminations. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Fragile Runtime Extension Extractors and Unprotected Tower Middleware Panic Crashes) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Rust