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

Axum 0.8 Type-Safe State Extraction, Tower Middleware Ordering, and Panic Boundary Invariants

Enforces compile-time type-safe state extraction via Axum 0.8's State and FromRef traits instead of runtime Extension lookups. Mandates strict Tower ServiceBuilder middleware ordering with CatchPanicLayer, TimeoutLayer, and TraceLayer to prevent runtime panics, dropped connections, and untyped state degradation.

Prohibited Anti-Pattern: Runtime panics from missing request extensions, misordered Tower layers dropping traces, and unhandled extractor rejections

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Type-Safe State Extraction, Tower Middleware Ordering, and Panic Boundary Invariants - Enforces compile-time type-safe state extraction via Axum 0.8's State and FromRef traits instead of runtime Extension lookups. Mandates strict Tower ServiceBuilder middleware ordering with CatchPanicLayer, TimeoutLayer, and TraceLayer to prevent runtime panics, dropped connections, and untyped state degradation.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-08-state-tower-resilience-guardrail"
---

# Axum 0.8 Type-Safe State Extraction, Tower Middleware Ordering, and Panic Boundary Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Runtime panics from missing request extensions, misordered Tower layers dropping traces, and unhandled extractor rejections

## System Constraints
You are a Principal Rust Systems Architect specializing in Axum 0.8 and Tower service composition. Mandate compile-time guaranteed state extraction via `axum::extract::State` and `axum::extract::FromRef`, strict Tower middleware ordering in `tower::ServiceBuilder`, zero raw `.unwrap()` or panic rejections in route handlers, and deterministic RFC 7807/JSON error responses.

## Strict Guidelines
- Engineers MUST ALWAYS extract shared application state using `axum::extract::State` and implement `axum::extract::FromRef` for sub-states instead of using `axum::Extension`.
- Engineers MUST NOT rely on runtime `Extension` extraction for core application state, database connection pools, or configuration singletons.
- Code MUST order Tower layers deterministically in `ServiceBuilder`: outer `TraceLayer` -> `CatchPanicLayer` -> `TimeoutLayer` -> rate limiting/concurrency -> authentication -> router handlers.
- Services MUST configure `tower_http::catch_panic::CatchPanicLayer` with a custom panic response handler returning structured JSON with an HTTP 500 status code.
- Components NEVER expose raw standard library panics or unhandled extractor rejections to the client; all custom extractors MUST implement `FromRequestParts` or `FromRequest` with an associated `Rejection` implementing `IntoResponse`.

## Bad vs Good Implementations
### Axum 0.8 State Extraction and Tower Middleware Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension skips compile-time type verification for state, leading to runtime 500 errors if forgotten. Unwrapped environment access can panic the thread, causing TCP drops without an HTTP response because CatchPanicLayer is omitted.
```rust
use axum::{routing::get, Extension, Router, Json};
use tower_http::trace::TraceLayer;
use std::sync::Arc;

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

// ANTI-PATTERN: Extension fails at runtime if omitted in router setup;
// panic will terminate connection without HTTP response;
// middleware ordering loses trace context during panics.
async fn get_user(Extension(state): Extension<Arc<AppState>>) -> Json<String> {
    // ANTI-PATTERN: Raw unwrap panics handler without structured rejection
    let val = std::env::var("CRITICAL_KEY").unwrap();
    Json(val)
}

pub fn app(state: Arc<AppState>) -> Router {
    Router::new()
        .route("/user", get(get_user))
        // ANTI-PATTERN: Extension provides zero compile-time state guarantees
        .layer(Extension(state))
        // ANTI-PATTERN: TraceLayer without CatchPanicLayer drops connection silently on panic
        .layer(TraceLayer::new_for_http())
}
```

#### Production Standard (Correct)
> **Standard**: AppState implements FromRef for fine-grained, compile-time verified sub-state extraction via State. The Tower ServiceBuilder places TraceLayer outermost, followed by CatchPanicLayer to guarantee zero dropped connections and standardized JSON responses on failure.
```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,
    timeout::TimeoutLayer,
    trace::TraceLayer,
};
use std::time::Duration;

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

// Sub-state extraction: compile-time guaranteed modularity
impl FromRef<AppState> for sqlx::PgPool {
    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!({
        "type": "https://errors.example.com/internal-error",
        "title": "Internal Server Error",
        "status": 500,
        "detail": "An unexpected error occurred while processing the request."
    }))).into_response()
}

async fn get_user(State(pool): State<sqlx::PgPool>) -> Result<Json<String>, (StatusCode, Json<serde_json::Value>)> {
    let key = std::env::var("CRITICAL_KEY").map_err(|_| {
        (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": "Configuration missing"})))
    })?;
    Ok(Json(key))
}

pub fn app(state: AppState) -> Router {
    let middleware_stack = ServiceBuilder::new()
        // Outer layer captures full lifecycle traces including panics
        .layer(TraceLayer::new_for_http())
        // CatchPanic transforms unwinds into deterministic RFC 7807 500 responses
        .layer(CatchPanicLayer::custom(handle_panic))
        // Bound request execution time before hitting handlers
        .layer(TimeoutLayer::new(Duration::from_secs(30)));

    Router::new()
        .route("/user", get(get_user))
        .layer(middleware_stack)
        .with_state(state) // Axum 0.8 compile-time type-safe state injection
}
```

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 Extraction, Tower Middleware Ordering, and Panic Boundary Invariants

Axum 0.8 Type-Safe State Extraction, Tower Middleware Ordering, and Panic Boundary Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces compile-time type-safe state extraction via Axum 0.8's State and FromRef traits instead of runtime Extension lookups. Mandates strict Tower ServiceBuilder middleware ordering with CatchPanicLayer, TimeoutLayer, and TraceLayer to prevent runtime panics, dropped connections, and untyped state degradation. 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 panics from missing request extensions, misordered Tower layers dropping traces, and unhandled extractor rejections 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 panics from missing request extensions, misordered Tower layers dropping traces, and unhandled extractor rejectionsCritical
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 extract shared application state using `axum

Engineers MUST ALWAYS extract shared application state using `axum::extract::State` and implement `axum::extract::FromRef` for sub-states instead of using `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 rely on runtime `Extension` extraction for core application state, database connection pools, or configuration singletons.

Engineers MUST NOT rely on runtime `Extension` extraction for core application state, database connection pools, or configuration singletons.

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 order Tower layers deterministically in `ServiceBuilder`

Code MUST order Tower layers deterministically in `ServiceBuilder`: outer `TraceLayer` -> `CatchPanicLayer` -> `TimeoutLayer` -> rate limiting/concurrency -> authentication -> router handlers.

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 configure `tower_http

Services MUST configure `tower_http::catch_panic::CatchPanicLayer` with a custom panic response handler returning structured JSON with an HTTP 500 status code.

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 expose raw standard library panics or unhandled extractor rejections to the client

Components NEVER expose raw standard library panics or unhandled extractor rejections to the client; all custom extractors MUST implement `FromRequestParts` or `FromRequest` with an associated `Rejection` implementing `IntoResponse`.

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 Extraction, Tower Middleware Ordering, and Panic Boundary Invariants critical for AI coding assistants?

Enforces compile-time type-safe state extraction via Axum 0.8's State and FromRef traits instead of runtime Extension lookups. Mandates strict Tower ServiceBuilder middleware ordering with CatchPanicLayer, TimeoutLayer, and TraceLayer to prevent runtime panics, dropped connections, and untyped state degradation. 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 panics from missing request extensions, misordered Tower layers dropping traces, and unhandled extractor rejections) 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