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

Axum 0.8 Type-Safe State Sub-Extractors and Infallible Tower Middleware

Enforces compile-time type safety in Axum 0.8 by mandating State extractors with FromRef composition over untyped Extensions. Guarantees infallible Tower middleware stacks through structured CatchPanicLayer boundaries and deterministic IntoResponse error mapping.

Prohibited Anti-Pattern: Runtime Extension Panics and Monolithic State Coupling Without CatchPanic Guardrails

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Type-Safe State Sub-Extractors and Infallible Tower Middleware - Enforces compile-time type safety in Axum 0.8 by mandating State extractors with FromRef composition over untyped Extensions. Guarantees infallible Tower middleware stacks through structured CatchPanicLayer boundaries and deterministic IntoResponse error mapping.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-type-safe-state-tower-service-guardrail"
---

# Axum 0.8 Type-Safe State Sub-Extractors and Infallible Tower Middleware

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Runtime Extension Panics and Monolithic State Coupling Without CatchPanic Guardrails

## System Constraints
You are a Principal Rust Architect enforcing idiomatic, high-reliability Axum 0.8 and Tower service architecture. Mandate compile-time type-safe State extractors using FromRef, forbid Extension for core dependencies, and require infallible Tower middleware topologies with strict CatchPanicLayer resilience.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` instead of `axum::extract::Extension` for shared application state to guarantee presence at compile-time.
- Engineers MUST implement `axum::extract::FromRef` on monolithic application state wrappers to expose granular sub-states (e.g., database pool, redis client, cryptographic keys) to modular sub-routers.
- Engineers MUST NEVER leak internal errors or panic in handler execution; all handler returns MUST implement `axum::response::IntoResponse` with explicit HTTP status codes and RFC 7807/JSON problem details.
- Services MUST wrap the root Axum router in a `tower::ServiceBuilder` containing `tower_http::catch_panic::CatchPanicLayer` with a custom panic-to-response mapper to guarantee zero unhandled connection drops.
- Components NEVER call `.unwrap()` or `.expect()` inside asynchronous request handlers; all fallible domain operations MUST use the `?` operator over typed domain errors.

## Bad vs Good Implementations
### State Extraction and Middleware Resilience

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension bypasses Axum's compile-time type verification. If the layer is omitted or mismatched, the application panics on incoming requests. Calling unwrap() inside the handler combined with the lack of CatchPanicLayer causes abrupt HTTP connection drops.
```rust
use axum::{routing::get, Extension, Router, Json};
use std::sync::Arc;

struct AppState {
    pool: sqlx::PgPool,
}

// ANTI-PATTERN: Extension fails at runtime if unregistered.
// Unhandled unwrap causes raw panics and dropped connections without CatchPanicLayer.
async fn get_user(Extension(state): Extension<Arc<AppState>>) -> Json<String> {
    let user_name = state.pool.acquire().await.unwrap(); // Panics on pool exhaustion
    Json(format!("User: {:?}", user_name))
}

pub fn app(state: AppState) -> Router {
    Router::new()
        .route("/user", get(get_user))
        .layer(axum::extract::Extension(Arc::new(state)))
}
```

#### Production Standard (Correct)
> **Standard**: Router enforces state provision at compile-time via with_state. Handlers consume only the PgPool sub-state via FromRef, minimizing coupling. CatchPanicLayer prevents service termination on unwinding panics, and AppError converts all fallible logic into structured HTTP responses.
```rust
use axum::{
    extract::{FromRef, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Json,
    Router,
};
use serde_json::json;
use tower::ServiceBuilder;
use tower_http::{catch_panic::CatchPanicLayer, trace::TraceLayer};

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

// Granular sub-state extraction via FromRef
impl FromRef<AppState> for sqlx::PgPool {
    fn from_ref(app_state: &AppState) -> Self {
        app_state.db_pool.clone()
    }
}

pub enum AppError {
    Database(sqlx::Error),
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "Database error occurred"),
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}

// Handlers depend only on the specific sub-state required
async fn get_user(State(pool): State<sqlx::PgPool>) -> Result<Json<serde_json::Value>, AppError> {
    let _conn = pool.acquire().await.map_err(AppError::Database)?;
    Ok(Json(json!({ "status": "connected" })))
}

pub fn app(state: AppState) -> Router {
    Router::new()
        .route("/user", get(get_user))
        .layer(
            ServiceBuilder::new()
                .layer(TraceLayer::new_for_http())
                .layer(CatchPanicLayer::custom(|_panic_err| {
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        Json(json!({ "error": "Internal server error" })),
                    )
                        .into_response()
                })),
        )
        .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 Sub-Extractors and Infallible Tower Middleware

Axum 0.8 Type-Safe State Sub-Extractors and Infallible Tower Middleware defines an industrial-grade behavioral standard for backend engineering. Enforces compile-time type safety in Axum 0.8 by mandating State extractors with FromRef composition over untyped Extensions. Guarantees infallible Tower middleware stacks through structured CatchPanicLayer boundaries and deterministic IntoResponse error mapping. 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: Runtime Extension Panics and Monolithic State Coupling Without CatchPanic Guardrails 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 DriftRuntime Extension Panics and Monolithic State Coupling Without CatchPanic GuardrailsCritical
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` instead of `axum::extract::Extension` for shared application state to guarantee presence 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.
2

Engineers MUST implement `axum

Engineers MUST implement `axum::extract::FromRef` on monolithic application state wrappers to expose granular sub-states (e.g., database pool, redis client, cryptographic keys) to modular sub-routers.

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 NEVER leak internal errors or panic in handler execution

Engineers MUST NEVER leak internal errors or panic in handler execution; all handler returns MUST implement `axum::response::IntoResponse` with explicit HTTP status codes and RFC 7807/JSON problem details.

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 wrap the root Axum router in a `tower

Services MUST wrap the root Axum router in a `tower::ServiceBuilder` containing `tower_http::catch_panic::CatchPanicLayer` with a custom panic-to-response mapper to guarantee zero unhandled connection drops.

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 call `.unwrap()` or `.expect()` inside asynchronous request handlers

Components NEVER call `.unwrap()` or `.expect()` inside asynchronous request handlers; all fallible domain operations MUST use the `?` operator over typed domain 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.
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 Sub-Extractors and Infallible Tower Middleware critical for AI coding assistants?

Enforces compile-time type safety in Axum 0.8 by mandating State extractors with FromRef composition over untyped Extensions. Guarantees infallible Tower middleware stacks through structured CatchPanicLayer boundaries and deterministic IntoResponse error mapping. 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 (Runtime Extension Panics and Monolithic State Coupling Without CatchPanic Guardrails) 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