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

Axum 0.8 Type-Safe State Subtyping, Fallback Layers, and Safe Extractor Composition

Enforces strict type safety and panic-free request lifecycle management for Rust Axum 0.8 and Tower ecosystems. Dictates compositional sub-state extraction via FromRef, prevents router-level runtime type mismatches, and mandates centralized, catch-panic Tower layer topologies. Guarantees that router nesting, middleware stacking, and custom extractors never cause runtime unhandled panics or silent state dropouts.

Prohibited Anti-Pattern: Global Monolithic State Coupling with Unhandled Layer Panics and Untyped Extension Leaks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Type-Safe State Subtyping, Fallback Layers, and Safe Extractor Composition - Enforces strict type safety and panic-free request lifecycle management for Rust Axum 0.8 and Tower ecosystems. Dictates compositional sub-state extraction via FromRef, prevents router-level runtime type mismatches, and mandates centralized, catch-panic Tower layer topologies. Guarantees that router nesting, middleware stacking, and custom extractors never cause runtime unhandled panics or silent state dropouts.
globs: **/*.rs, Cargo.toml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-08-state-tower-safety-guardrail"
---

# Axum 0.8 Type-Safe State Subtyping, Fallback Layers, and Safe Extractor Composition

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Global Monolithic State Coupling with Unhandled Layer Panics and Untyped Extension Leaks

## System Constraints
You are a Principal Rust Systems Architect enforcing strict structural invariants across Axum 0.8 and Tower microservices. You must enforce explicit type-safe state extraction with FromRef, ban untyped Extensions for shared application state, enforce CatchPanic layers at outer Tower perimeters, and reject any code where extractor failure or router nesting risks runtime panics or broken state inheritance.

## Strict Guidelines
- Engineers MUST ALWAYS implement axum::extract::FromRef<AppState> for sub-states instead of passing monolithic AppState or wrapping individual fields into untyped Extension layers.
- Engineers MUST ALWAYS register CatchPanicLayer at the outermost boundary of the Tower ServiceBuilder before handing the router to axum::serve to eliminate unhandled panic rejections.
- Services MUST implement custom Axum 0.8 extractors using the (FromRequestParts<S> + Send + Sync) trait pattern, explicitly returning custom Rejection enums implementing IntoResponse with zero unwraps.
- Engineers MUST NOT use Router::with_state when nesting routers if the child router uses a different state type unless explicit subtyping via with_state and FromRef adaptation is fully validated at compile time.
- Code SHOULD wrap all external I/O state pools (e.g., sqlx::PgPool, deadpool) inside an Arc-wrapped structural container or rely on clone-cheap handles that derive Clone without cloning deep resource state.

## Bad vs Good Implementations
### Substate Extraction and Resilient Tower Layer Composition in Axum 0.8

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension bypasses Axum 0.8's compile-time type verification, causing runtime 500 internal errors if omitted. Handler panic directly terminates request handling without structured error envelopes or recovery. Leaf handlers couple to either untyped Extensions or monolithic AppState.
```rust
use axum::{routing::get, Extension, Router, extract::State};
use std::sync::Arc;

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

// ANTI-PATTERN: Using monolithic state in leaf handlers and relying on Extension for substate.
// Lacks CatchPanicLayer, causing thread death or abrupt connection drop on unexpected handler panics.
async fn handler(Extension(db): Extension<Arc<String>>) -> &'static str {
    if db.is_empty() {
        panic!("Database connection missing!"); // Crashes connection without standard 500 JSON response
    }
    "ok"
}

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

    Router::new()
        .route("/test", get(handler))
        .layer(Extension(state.db.clone())) // Dynamic untyped extension injection; easy to miss or mismatch
        .with_state(state)
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to Axum 0.8 compile-time state guarantees using FromRef, allowing handlers to demand only the explicit granular sub-states they consume. Protects service reliability by wrapping Tower layers in CatchPanicLayer with structured JSON error transformations.
```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_http::catch_panic::CatchPanicLayer;
use tower::ServiceBuilder;

#[derive(Clone)]
pub struct DatabaseHandle(pub Arc<String>);

#[derive(Clone)]
pub struct CacheHandle(pub Arc<String>);

#[derive(Clone)]
pub struct AppState {
    pub db: DatabaseHandle,
    pub cache: CacheHandle,
}

// Decouple handler dependencies using FromRef
impl FromRef<AppState> for DatabaseHandle {
    fn from_ref(state: &AppState) -> Self {
        state.db.clone()
    }
}

// Safe panic fallback handler
fn handle_panic(err: Box<dyn std::any::Any + Send + 'static>) -> Response {
    let details = if let Some(s) = err.downcast_ref::<&str>() {
        *s
    } else if let Some(s) = err.downcast_ref::<String>() {
        s.as_str()
    } else {
        "Unknown panic"
    };
    (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": "Internal server error", "details": details }))).into_response()
}

async fn handler(State(db): State<DatabaseHandle>) -> Result<&'static str, StatusCode> {
    if db.0.is_empty() {
        return Err(StatusCode::SERVICE_UNAVAILABLE);
    }
    Ok("healthy")
}

pub fn app() -> Router {
    let state = AppState {
        db: DatabaseHandle(Arc::new("postgres://...".into())),
        cache: CacheHandle(Arc::new("redis://...".into())),
    };

    Router::new()
        .route("/test", get(handler))
        .layer(
            ServiceBuilder::new()
                .layer(CatchPanicLayer::custom(handle_panic))
        )
        .with_state(state)
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Axum 0.8 Type-Safe State Subtyping, Fallback Layers, and Safe Extractor Composition

Axum 0.8 Type-Safe State Subtyping, Fallback Layers, and Safe Extractor Composition defines an industrial-grade behavioral standard for backend engineering. Enforces strict type safety and panic-free request lifecycle management for Rust Axum 0.8 and Tower ecosystems. Dictates compositional sub-state extraction via FromRef, prevents router-level runtime type mismatches, and mandates centralized, catch-panic Tower layer topologies. Guarantees that router nesting, middleware stacking, and custom extractors never cause runtime unhandled panics or silent state dropouts. 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: Global Monolithic State Coupling with Unhandled Layer Panics and Untyped Extension Leaks 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 DriftGlobal Monolithic State Coupling with Unhandled Layer Panics and Untyped Extension LeaksCritical
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 implement axum

Engineers MUST ALWAYS implement axum::extract::FromRef<AppState> for sub-states instead of passing monolithic AppState or wrapping individual fields into untyped Extension layers.

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 ALWAYS register CatchPanicLayer at the outermost boundary of the Tower ServiceBuilder before handing the router to axum

Engineers MUST ALWAYS register CatchPanicLayer at the outermost boundary of the Tower ServiceBuilder before handing the router to axum::serve to eliminate unhandled panic rejections.

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

Services MUST implement custom Axum 0.8 extractors using the (FromRequestParts<S> + Send + Sync) trait pattern, explicitly returning custom Rejection enums implementing IntoResponse with zero unwraps.

Services MUST implement custom Axum 0.8 extractors using the (FromRequestParts<S> + Send + Sync) trait pattern, explicitly returning custom Rejection enums implementing IntoResponse with zero unwraps.

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

Engineers MUST NOT use Router

Engineers MUST NOT use Router::with_state when nesting routers if the child router uses a different state type unless explicit subtyping via with_state and FromRef adaptation is fully validated at compile time.

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

Code SHOULD wrap all external I/O state pools (e.g., sqlx

Code SHOULD wrap all external I/O state pools (e.g., sqlx::PgPool, deadpool) inside an Arc-wrapped structural container or rely on clone-cheap handles that derive Clone without cloning deep resource state.

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 Axum 0.8 Type-Safe State Subtyping, Fallback Layers, and Safe Extractor Composition critical for AI coding assistants?

Enforces strict type safety and panic-free request lifecycle management for Rust Axum 0.8 and Tower ecosystems. Dictates compositional sub-state extraction via FromRef, prevents router-level runtime type mismatches, and mandates centralized, catch-panic Tower layer topologies. Guarantees that router nesting, middleware stacking, and custom extractors never cause runtime unhandled panics or silent state dropouts. 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 (Global Monolithic State Coupling with Unhandled Layer Panics and Untyped Extension Leaks) 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

Axum