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

Axum 0.8 Type-Safe State Extractors & Resilient Tower Middleware Ordering

Enforces strict Axum 0.8 compile-time state derivation through FromRef sub-states and infallible Tower middleware topologies. Prevents runtime extractor panics from legacy Extension<T> patterns and guarantees unhandled panic isolation via structured CatchPanicLayer ordering.

Prohibited Anti-Pattern: Monolithic State Coupling and Inverted Tower Middleware Causing Extractor Mismatches and Panic Leaks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Type-Safe State Extractors & Resilient Tower Middleware Ordering - Enforces strict Axum 0.8 compile-time state derivation through FromRef sub-states and infallible Tower middleware topologies. Prevents runtime extractor panics from legacy Extension<T> patterns and guarantees unhandled panic isolation via structured CatchPanicLayer ordering.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-08-state-extractors-tower-service"
---

# Axum 0.8 Type-Safe State Extractors & Resilient Tower Middleware Ordering

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Monolithic State Coupling and Inverted Tower Middleware Causing Extractor Mismatches and Panic Leaks

## System Constraints
You are a Principal Rust Architect enforcing Axum 0.8 and Tower production standards. You must mandate compile-time checked sub-states using axum::extract::FromRef, eliminate dynamic Extension<T> dependencies for shared context, and enforce strict, deterministic Tower ServiceBuilder layer sequencing with custom panic handlers.

## Strict Guidelines
- Engineers MUST ALWAYS use axum::extract::State<T> with custom sub-states implemented via axum::extract::FromRef instead of injecting dynamic axum::Extension<T> for application dependencies.
- Engineers MUST ALWAYS order Tower middleware layers deterministically: CatchPanicLayer outermost, followed by TraceLayer, TimeoutLayer, and inner request-transform layers.
- Engineers MUST NOT leak raw panics or unhandled error types across handler boundaries; all handler errors must implement axum::response::IntoResponse with explicit RFC-7807 or uniform JSON error contracts.
- Services MUST ensure all shared application state types are wrapped in std::sync::Arc or are cheaply Clone before being passed into axum::Router::with_state.
- Components NEVER execute blocking synchronous operations inside Axum async handler tasks; engineers must use tokio::task::spawn_blocking or dedicated thread pools.

## Bad vs Good Implementations
### Sub-State Extraction and Infallible Middleware Pipeline in Axum 0.8

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension<T> bypasses Axum 0.8's compile-time type verification for state, deferring missing dependency bugs to runtime panics. Missing CatchPanicLayer and improper middleware ordering allow unhandled unwinds to terminate connections abruptly without structured HTTP 500 JSON responses.
```rust
use axum::{routing::get, Extension, Router};
use tower_http::trace::TraceLayer;
use std::sync::Arc;

struct AppState {
    db_pool: sqlx::PgPool,
    api_token: String,
}

// ANTI-PATTERN: Untyped Extension fallback, dynamic lookup panics at runtime if omitted,
// and missing CatchPanicLayer leaves worker thread panics unhandled.
async fn bad_handler(Extension(pool): Extension<Arc<sqlx::PgPool>>) -> &'static str {
    // Synchronous execution or panicking extractors cause 502/TCP reset
    "OK"
}

pub fn bad_router(state: AppState) -> Router {
    Router::new()
        .route("/health", get(bad_handler))
        // Layers executed in inverted order without catch-panic isolation
        .layer(TraceLayer::new_for_http())
        .layer(Extension(Arc::new(state.db_pool)))
}
```

#### Production Standard (Correct)
> **Standard**: Implements Axum 0.8 compile-time checked sub-states via FromRef, allowing modular handlers to only depend on sqlx::PgPool rather than the monolithic AppState. The Tower middleware is composed via ServiceBuilder with CatchPanicLayer outermost, ensuring all unwinds are caught and converted to RFC-compliant JSON 500 responses.
```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, ResponseForPanic},
    trace::TraceLayer,
};

#[derive(Clone)]
pub struct AppState {
    pub db_pool: sqlx::PgPool,
    pub api_token: String,
}

// Sub-state derivation guarantees compile-time validation for modular routes
impl FromRef<AppState> for sqlx::PgPool {
    fn from_ref(state: &AppState) -> Self {
        state.db_pool.clone()
    }
}

struct CustomPanicHandler;
impl ResponseForPanic for CustomPanicHandler {
    fn response_for_panic(&mut self, _: Box<dyn std::any::Any + Send + 'static>) -> Response {
        let body = Json(json!({
            "error": "InternalServerError",
            "message": "An unhandled panic occurred"
        }));
        (StatusCode::INTERNAL_SERVER_ERROR, body).into_response()
    }
}

async fn robust_handler(State(pool): State<sqlx::PgPool>) -> Result<Json<serde_json::Value>, StatusCode> {
    // State is statically verified at compile time by Axum 0.8 router
    Ok(Json(json!({"status": "healthy"})))
}

pub fn robust_router(state: AppState) -> Router {
    let middleware = ServiceBuilder::new()
        // CatchPanicLayer must wrap outside to capture panics from inner layers/handlers
        .layer(CatchPanicLayer::custom(CustomPanicHandler))
        .layer(TraceLayer::new_for_http());

    Router::new()
        .route("/health", get(robust_handler))
        .layer(middleware)
        .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 Extractors & Resilient Tower Middleware Ordering

Axum 0.8 Type-Safe State Extractors & Resilient Tower Middleware Ordering defines an industrial-grade behavioral standard for backend engineering. Enforces strict Axum 0.8 compile-time state derivation through FromRef sub-states and infallible Tower middleware topologies. Prevents runtime extractor panics from legacy Extension<T> patterns and guarantees unhandled panic isolation via structured CatchPanicLayer ordering. 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: Monolithic State Coupling and Inverted Tower Middleware Causing Extractor Mismatches and Panic 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 DriftMonolithic State Coupling and Inverted Tower Middleware Causing Extractor Mismatches and Panic 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 use axum

Engineers MUST ALWAYS use axum::extract::State<T> with custom sub-states implemented via axum::extract::FromRef instead of injecting dynamic axum::Extension<T> for application dependencies.

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 order Tower middleware layers deterministically

Engineers MUST ALWAYS order Tower middleware layers deterministically: CatchPanicLayer outermost, followed by TraceLayer, TimeoutLayer, and inner request-transform 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.
3

Engineers MUST NOT leak raw panics or unhandled error types across handler boundaries

Engineers MUST NOT leak raw panics or unhandled error types across handler boundaries; all handler errors must implement axum::response::IntoResponse with explicit RFC-7807 or uniform JSON error contracts.

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

Services MUST ensure all shared application state types are wrapped in std

Services MUST ensure all shared application state types are wrapped in std::sync::Arc or are cheaply Clone before being passed into axum::Router::with_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.
5

Components NEVER execute blocking synchronous operations inside Axum async handler tasks

Components NEVER execute blocking synchronous operations inside Axum async handler tasks; engineers must use tokio::task::spawn_blocking or dedicated thread pools.

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 Extractors & Resilient Tower Middleware Ordering critical for AI coding assistants?

Enforces strict Axum 0.8 compile-time state derivation through FromRef sub-states and infallible Tower middleware topologies. Prevents runtime extractor panics from legacy Extension<T> patterns and guarantees unhandled panic isolation via structured CatchPanicLayer ordering. 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 (Monolithic State Coupling and Inverted Tower Middleware Causing Extractor Mismatches and Panic 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