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

Rust Axum 0.8 Strict State Extraction & Tower Middleware Resilience

Enforces compile-time type-safe state extraction via Axum 0.8 State and FromRef sub-states while prohibiting untyped Extension-based dependency injection. Mandates deterministic Tower middleware ordering featuring outer CatchPanicLayer, structured TraceLayer, and typed custom rejections to eliminate unhandled panics and silent TCP connection terminations.

Prohibited Anti-Pattern: Untyped Extension Injection, Inverted Middleware Layering, and Panic-Induced Client Disconnections

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Rust Axum 0.8 Strict State Extraction & Tower Middleware Resilience - Enforces compile-time type-safe state extraction via Axum 0.8 State and FromRef sub-states while prohibiting untyped Extension-based dependency injection. Mandates deterministic Tower middleware ordering featuring outer CatchPanicLayer, structured TraceLayer, and typed custom rejections to eliminate unhandled panics and silent TCP connection terminations.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rust-axum-0-8-state-tower-resilience-standard"
---

# Rust Axum 0.8 Strict State Extraction & Tower Middleware Resilience

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Untyped Extension Injection, Inverted Middleware Layering, and Panic-Induced Client Disconnections

## System Constraints
You are a Principal Rust Backend Architect enforcing Axum 0.8 production invariants. Mandate compile-time verified State extractors, explicit sub-state derivation via FromRef, strict Tower layer composition order, and zero uncaught panics across all route handlers and services.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` paired with `axum::extract::FromRef` for state dependency injection instead of `axum::Extension`.
- Engineers MUST NOT allow unhandled panics in handlers or middleware; all Axum routers MUST be wrapped with `tower_http::catch_panic::CatchPanicLayer` with a custom panic-to-response mapper.
- Middleware stacks MUST follow strict outer-to-inner execution order: `CatchPanicLayer` outermost, followed by `TraceLayer`, timeout/concurrency limits, and then authentication/authorization layers.
- Custom extractors MUST return explicit custom rejection types implementing `axum::response::IntoResponse` with standardized JSON error envelopes rather than falling back to default Axum plaintext rejections.
- Sub-routers MUST be modularized by consuming specific sub-states derived via `FromRef<AppState>` to prevent exposing monolithic state structs across independent domain boundaries.

## Bad vs Good Implementations
### Axum 0.8 Type-Safe State and Resilient Tower Layer Composition

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension deferment drops type safety from compile time to runtime, producing a 500 or panic if omitted. Panicking inside the handler without CatchPanicLayer drops the HTTP connection abruptly without structured JSON error logging or standard status codes.
```rust
use axum::{routing::get, Extension, Router};
use std::sync::Arc;

struct AppState { db_pool: String }

// Anti-pattern: Untyped runtime Extension extraction that panics at runtime if omitted,
// combined with zero panic boundaries or structured middleware layering.
async fn handler(Extension(state): Extension<Arc<AppState>>) -> &'static str {
    if state.db_pool.is_empty() {
        panic!("Critical database pool failure"); // Unhandled panic crashes TCP stream
    }
    "OK"
}

pub fn app() -> Router {
    let state = Arc::new(AppState { db_pool: String::new() });
    // Fragile runtime layer injection; missing CatchPanicLayer and State
    Router::new()
        .route("/api", get(handler))
        .layer(Extension(state))
}
```

#### Production Standard (Correct)
> **Standard**: State extractors enforce compile-time verification of dependency availability. FromRef isolates sub-state domains cleanly. CatchPanicLayer::custom guarantees all unexpected panics convert gracefully into standardized JSON 500 envelopes without terminating connections.
```rust
use axum::{extract::{FromRef, State}, http::StatusCode, response::{IntoResponse, Response}, routing::get, Json, Router};
use tower_http::{catch_panic::CatchPanicLayer, trace::TraceLayer};
use serde_json::json;

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

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

fn handle_panic(_err: Box<dyn std::any::Any + Send + 'static>) -> Response {
    (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({
        "error": {
            "code": "INTERNAL_PANIC",
            "message": "A critical unhandled execution fault occurred."
        }
    }))).into_response()
}

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

pub fn app() -> Router {
    let state = AppState { db_pool: "postgres://...".into() };

    Router::new()
        .route("/api", get(handler))
        .with_state(state)
        // Tower execution order: Trace layer captures mapped panic responses,
        // CatchPanicLayer catches handler panics before they tear down connections.
        .layer(TraceLayer::new_for_http())
        .layer(CatchPanicLayer::custom(handle_panic))
}
```

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: Rust Axum 0.8 Strict State Extraction & Tower Middleware Resilience

Rust Axum 0.8 Strict State Extraction & Tower Middleware Resilience defines an industrial-grade behavioral standard for backend engineering. Enforces compile-time type-safe state extraction via Axum 0.8 State and FromRef sub-states while prohibiting untyped Extension-based dependency injection. Mandates deterministic Tower middleware ordering featuring outer CatchPanicLayer, structured TraceLayer, and typed custom rejections to eliminate unhandled panics and silent TCP 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: Untyped Extension Injection, Inverted Middleware Layering, and Panic-Induced Client Disconnections 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 DriftUntyped Extension Injection, Inverted Middleware Layering, and Panic-Induced Client DisconnectionsCritical
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` paired with `axum::extract::FromRef` for state dependency injection instead of `axum::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 allow unhandled panics in handlers or middleware

Engineers MUST NOT allow unhandled panics in handlers or middleware; all Axum routers MUST be wrapped with `tower_http::catch_panic::CatchPanicLayer` with a custom panic-to-response mapper.

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

Middleware stacks MUST follow strict outer-to-inner execution order

Middleware stacks MUST follow strict outer-to-inner execution order: `CatchPanicLayer` outermost, followed by `TraceLayer`, timeout/concurrency limits, and then authentication/authorization 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.
4

Custom extractors MUST return explicit custom rejection types implementing `axum

Custom extractors MUST return explicit custom rejection types implementing `axum::response::IntoResponse` with standardized JSON error envelopes rather than falling back to default Axum plaintext 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.
5

Sub-routers MUST be modularized by consuming specific sub-states derived via `FromRef<AppState>` to prevent exposing monolithic state structs across independent domain boundaries.

Sub-routers MUST be modularized by consuming specific sub-states derived via `FromRef<AppState>` to prevent exposing monolithic state structs across independent domain boundaries.

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 Strict State Extraction & Tower Middleware Resilience critical for AI coding assistants?

Enforces compile-time type-safe state extraction via Axum 0.8 State and FromRef sub-states while prohibiting untyped Extension-based dependency injection. Mandates deterministic Tower middleware ordering featuring outer CatchPanicLayer, structured TraceLayer, and typed custom rejections to eliminate unhandled panics and silent TCP 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 (Untyped Extension Injection, Inverted Middleware Layering, and Panic-Induced Client Disconnections) 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