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

Axum 0.8 Type-Safe State Extractors & Tower Middleware Invariants

Enforces Axum 0.8 compile-time type-safe state access via FromRef sub-states rather than fallible dynamic Extension extractors. Mandates defensive Tower middleware ordering with CatchPanicLayer and structured custom rejection handlers to ensure zero unhandled panics or degraded error telemetry.

Prohibited Anti-Pattern: Dynamic Extension Extraction and Unprotected Tower Pipelines Yielding Runtime Panics

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Type-Safe State Extractors & Tower Middleware Invariants - Enforces Axum 0.8 compile-time type-safe state access via FromRef sub-states rather than fallible dynamic Extension extractors. Mandates defensive Tower middleware ordering with CatchPanicLayer and structured custom rejection handlers to ensure zero unhandled panics or degraded error telemetry.
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-guardrails"
---

# Axum 0.8 Type-Safe State Extractors & Tower Middleware Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Dynamic Extension Extraction and Unprotected Tower Pipelines Yielding Runtime Panics

## System Constraints
You are a Principal Rust Architect enforcing Axum 0.8 type-safe State extractors, modular FromRef sub-state delegation, and deterministic Tower middleware ordering. Never permit unvalidated Extension extractors for application state or raw unhandled rejections that drop panic telemetry.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` and implement `axum::extract::FromRef` for modular sub-state derivation, ensuring compile-time state availability.
- Engineers MUST NOT use `axum::extract::Extension` for static application dependencies, database connection pools, or environment configurations.
- Code MUST wrap the outermost application service with `tower_http::catch_panic::CatchPanicLayer` providing a custom response mapper to prevent unhandled thread crashes.
- Tower middleware pipelines MUST position `CatchPanicLayer` outside `TraceLayer` so that recovered panics emit structured tracing spans.
- Router handlers MUST use custom rejection wrapper types implementing `IntoResponse` to intercept extractor failures before Axum falls back to generic internal server errors.
- Services MUST ensure all shared state structures implement `Clone + Send + Sync + 'static` without wrapping internal fields in redundant outer `Arc` layers when inner primitives already manage atomic reference counting.

## Bad vs Good Implementations
### Type-Safe State Extraction and Tower Middleware Ordering

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension circumvents Rust's compile-time verification. If an engineer forgets to inject the Extension layer, requests fail at runtime with untracked 500 errors. Furthermore, the absence of CatchPanicLayer risks silent process/worker degradation on unhandled unwinds.
```rust
use axum::{routing::get, Extension, Router};
use std::sync::Arc;

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

// ANTI-PATTERN: Extension fails at runtime if omitted;
// Missing CatchPanicLayer drops panic details and breaks clients.
async fn handler(Extension(state): Extension<AppState>) -> String {
    format!("Connected to {}", state.db_pool)
}

pub fn make_app() -> Router {
    Router::new()
        .route("/data", get(handler))
        // Bug: If Extension is forgotten here, runtime crashes with a 500 without compile error
}
```

#### Production Standard (Correct)
> **Standard**: AppState implements compile-time type extraction using State and FromRef. Missing states are rejected by rustc at build time. CatchPanicLayer wraps TraceLayer to guarantee panic recovery and uniform HTTP error responses.
```rust
use axum::{
    extract::{FromRef, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use std::sync::Arc;
use tower::ServiceBuilder;
use tower_http::{
    catch_panic::CatchPanicLayer,
    trace::TraceLayer,
};

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

// Sub-state derivation via FromRef enables modular handler dependencies
impl FromRef<AppState> for Arc<String> {
    fn from_ref(state: &AppState) -> Self {
        state.db_pool.clone()
    }
}

async fn handler(State(pool): State<Arc<String>>) -> Result<String, AppError> {
    Ok(format!("Connected to {pool}"))
}

enum AppError {
    Internal,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        (StatusCode::INTERNAL_SERVER_ERROR, "Internal failure").into_response()
    }
}

fn handle_panic(_err: Box<dyn std::any::Any + Send + 'static>) -> Response {
    (StatusCode::INTERNAL_SERVER_ERROR, "Unhandled worker panic").into_response()
}

pub fn make_app(state: AppState) -> Router {
    Router::new()
        .route("/data", get(handler))
        .with_state(state)
        .layer(
            ServiceBuilder::new()
                .layer(CatchPanicLayer::custom(handle_panic))
                .layer(TraceLayer::new_for_http()),
        )
}
```

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 & Tower Middleware Invariants

Axum 0.8 Type-Safe State Extractors & Tower Middleware Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces Axum 0.8 compile-time type-safe state access via FromRef sub-states rather than fallible dynamic Extension extractors. Mandates defensive Tower middleware ordering with CatchPanicLayer and structured custom rejection handlers to ensure zero unhandled panics or degraded error telemetry. 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: Dynamic Extension Extraction and Unprotected Tower Pipelines Yielding Runtime Panics 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 DriftDynamic Extension Extraction and Unprotected Tower Pipelines Yielding Runtime PanicsCritical
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 sub-state derivation, ensuring compile-time state availability.

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 use `axum

Engineers MUST NOT use `axum::extract::Extension` for static application dependencies, database connection pools, or environment configurations.

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

Code MUST wrap the outermost application service with `tower_http

Code MUST wrap the outermost application service with `tower_http::catch_panic::CatchPanicLayer` providing a custom response mapper to prevent unhandled thread crashes.

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 pipelines MUST position `CatchPanicLayer` outside `TraceLayer` so that recovered panics emit structured tracing spans.

Tower middleware pipelines MUST position `CatchPanicLayer` outside `TraceLayer` so that recovered panics emit structured tracing spans.

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

Router handlers MUST use custom rejection wrapper types implementing `IntoResponse` to intercept extractor failures before Axum falls back to generic internal server errors.

Router handlers MUST use custom rejection wrapper types implementing `IntoResponse` to intercept extractor failures before Axum falls back to generic internal server errors.

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

Services MUST ensure all shared state structures implement `Clone + Send + Sync + 'static` without wrapping internal fields in redundant outer `Arc` layers when inner primitives already manage atomic reference counting.

Services MUST ensure all shared state structures implement `Clone + Send + Sync + 'static` without wrapping internal fields in redundant outer `Arc` layers when inner primitives already manage atomic reference counting.

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

Enforces Axum 0.8 compile-time type-safe state access via FromRef sub-states rather than fallible dynamic Extension extractors. Mandates defensive Tower middleware ordering with CatchPanicLayer and structured custom rejection handlers to ensure zero unhandled panics or degraded error telemetry. 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 (Dynamic Extension Extraction and Unprotected Tower Pipelines Yielding Runtime Panics) 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