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

Axum 0.8 Substate Extraction, Tower Middleware Composition & CatchPanic Enforcement

Enforces Axum 0.8 compile-time type-safe substate extraction via `FromRef`, strict Tower layer ordering via `ServiceBuilder`, and boundary panic containment. Eliminates runtime dynamic extractor failures and unhandled thread panics dropping raw TCP streams.

Prohibited Anti-Pattern: Untyped Dynamic Extensions and Unordered Tower Middleware Causing Silent Panics and Runtime Extraction Failures

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Substate Extraction, Tower Middleware Composition & CatchPanic Enforcement - Enforces Axum 0.8 compile-time type-safe substate extraction via `FromRef`, strict Tower layer ordering via `ServiceBuilder`, and boundary panic containment. Eliminates runtime dynamic extractor failures and unhandled thread panics dropping raw TCP streams.
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-service-guardrail"
---

# Axum 0.8 Substate Extraction, Tower Middleware Composition & CatchPanic Enforcement

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Untyped Dynamic Extensions and Unordered Tower Middleware Causing Silent Panics and Runtime Extraction Failures

## System Constraints
You are a Principal Rust Backend Architect enforcing Axum 0.8 architectural invariants. Mandate modular type-safe state injection via FromRef, ordered Tower middleware stacks, and zero-panic guarantees with CatchPanicLayer.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` with composite state structures implementing `axum::extract::FromRef` instead of runtime `axum::Extension` for shared application state.
- Engineers MUST NOT leak monolithic application state into isolated domain sub-routers; sub-routers MUST consume strictly scoped substates via `FromRef`.
- Code MUST wrap edge routing in `tower_http::catch_panic::CatchPanicLayer` before response serialization to convert thread unwinds into RFC 7807/JSON 500 responses without dropping connections.
- Services MUST order Tower layers using `ServiceBuilder`: outer trace/metrics -> panic containment -> timeouts -> load shedding -> rate limiting -> authentication -> handler routing.
- Components NEVER use `unwrap()` or `expect()` on internal mutexes, channels, or database pools inside handler bodies; fallible operations must propagate through typed `Result<T, AppError>` implementing `IntoResponse`.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension bypasses Axum 0.8's compile-time type-safety checks, failing at runtime with a 500 Internal Server Error if the extension is omitted. Furthermore, the unhandled panic terminates the task without a structured response, dropping client TCP connections.
```rust
use axum::{routing::get, Extension, Router};
use std::sync::Arc;

struct AppState {
    db_pool: String,
}

// ANTI-PATTERN: Handler relies on dynamic Extension lookup (runtime failure risk),
// unhandled panic tears down the connection without a 500 response, and monolithic state is untyped.
async fn handler(Extension(state): Extension<Arc<AppState>>) -> String {
    if state.db_pool.is_empty() {
        panic!("database pool is missing!"); // Panics abort HTTP stream without JSON body
    }
    format!("Connected to: {}", state.db_pool)
}

pub fn app() -> Router {
    Router::new()
        .route("/data", get(handler))
        .layer(Extension(Arc::new(AppState { db_pool: String::new() })))
}
```

#### Production Standard (Correct)
> **Standard**: Leverages Axum 0.8's `FromRef` for compile-time verified substate extraction, structured error propagation via `IntoResponse`, and `CatchPanicLayer` to guarantee that unexpected panics are intercepted and serialized into compliant JSON 500 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: DbPool,
}

#[derive(Clone)]
pub struct DbPool(pub String);

// Enables granular substate extraction for modular domain handlers
impl FromRef<AppState> for DbPool {
    fn from_ref(state: &AppState) -> Self {
        state.db_pool.clone()
    }
}

async fn handler(State(pool): State<DbPool>) -> Result<Json<serde_json::Value>, AppError> {
    if pool.0.is_empty() {
        return Err(AppError::Configuration("Database pool uninitialized".into()));
    }
    Ok(Json(json!({ "status": "connected", "target": pool.0 })))
}

enum AppError {
    Configuration(String),
}

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

pub fn app(state: AppState) -> Router {
    let middleware = ServiceBuilder::new()
        .layer(TraceLayer::new_for_http())
        .layer(CatchPanicLayer::custom(|_err| {
            Response::builder()
                .status(StatusCode::INTERNAL_SERVER_ERROR)
                .header("content-type", "application/json")
                .body(axum::body::Body::from(r#"{"error":"internal_panic"}"#))
                .unwrap()
        }));

    Router::new()
        .route("/data", get(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 Substate Extraction, Tower Middleware Composition & CatchPanic Enforcement

Axum 0.8 Substate Extraction, Tower Middleware Composition & CatchPanic Enforcement defines an industrial-grade behavioral standard for backend engineering. Enforces Axum 0.8 compile-time type-safe substate extraction via `FromRef`, strict Tower layer ordering via `ServiceBuilder`, and boundary panic containment. Eliminates runtime dynamic extractor failures and unhandled thread panics dropping raw TCP streams. 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 Dynamic Extensions and Unordered Tower Middleware Causing Silent Panics and Runtime Extraction Failures 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 Dynamic Extensions and Unordered Tower Middleware Causing Silent Panics and Runtime Extraction FailuresCritical
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` with composite state structures implementing `axum::extract::FromRef` instead of runtime `axum::Extension` for shared application 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.
2

Engineers MUST NOT leak monolithic application state into isolated domain sub-routers

Engineers MUST NOT leak monolithic application state into isolated domain sub-routers; sub-routers MUST consume strictly scoped substates via `FromRef`.

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 edge routing in `tower_http

Code MUST wrap edge routing in `tower_http::catch_panic::CatchPanicLayer` before response serialization to convert thread unwinds into RFC 7807/JSON 500 responses without dropping connections.

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

Services MUST order Tower layers using `ServiceBuilder`: outer trace/metrics -> panic containment -> timeouts -> load shedding -> rate limiting -> authentication -> handler routing.

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 use `unwrap()` or `expect()` on internal mutexes, channels, or database pools inside handler bodies

Components NEVER use `unwrap()` or `expect()` on internal mutexes, channels, or database pools inside handler bodies; fallible operations must propagate through typed `Result<T, AppError>` 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 Substate Extraction, Tower Middleware Composition & CatchPanic Enforcement critical for AI coding assistants?

Enforces Axum 0.8 compile-time type-safe substate extraction via `FromRef`, strict Tower layer ordering via `ServiceBuilder`, and boundary panic containment. Eliminates runtime dynamic extractor failures and unhandled thread panics dropping raw TCP streams. 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 Dynamic Extensions and Unordered Tower Middleware Causing Silent Panics and Runtime Extraction Failures) 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