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-resilience-production-standard

Axum 0.8 Type-Safe State Subtyping, Tower Middleware Ordering, and Panic Catching

Enforces type-safe state extraction using Axum 0.8's FromRef trait for modular sub-routers, strict Tower ServiceBuilder middleware sequencing, and mandatory CatchPanicLayer integration. Prevents runtime routing panics, state extraction mismatches, and unhandled thread panics dropping active client connections without structured HTTP 500 telemetry.

Prohibited Anti-Pattern: Dynamic Extension-based state injections and unordered Tower middleware stacks lacking panic safety boundaries.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Type-Safe State Subtyping, Tower Middleware Ordering, and Panic Catching - Enforces type-safe state extraction using Axum 0.8's FromRef trait for modular sub-routers, strict Tower ServiceBuilder middleware sequencing, and mandatory CatchPanicLayer integration. Prevents runtime routing panics, state extraction mismatches, and unhandled thread panics dropping active client connections without structured HTTP 500 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-resilience-production-standard"
---

# Axum 0.8 Type-Safe State Subtyping, Tower Middleware Ordering, and Panic Catching

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Dynamic Extension-based state injections and unordered Tower middleware stacks lacking panic safety boundaries.

## System Constraints
You are a Principal Rust Architect enforcing type-safe state composition, idiomatic Tower Service layers, and panic resilience in Axum 0.8 microservices. Reject dynamic Extension extraction for core application state, enforce compile-time verified sub-states via axum::extract::FromRef, mandate correct Tower middleware composition order, and guarantee all panics are caught with structured HTTP responses.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` instead of `axum::Extension` for shared application dependencies to ensure compile-time dependency verification.
- Engineers MUST implement `axum::extract::FromRef<AppState>` for granular sub-states when composing nested modular routers with `Router::with_state`.
- Engineers MUST encapsulate shared mutable states inside `Arc<RwLock<T>>` or `Arc<Atomic*>` and ensure cloned state handles in extractors are cheap shallow references.
- Services MUST place `tower_http::catch_panic::CatchPanicLayer` at the boundary of the `tower::ServiceBuilder` stack to intercept panicking handlers and return structured JSON 500 errors.
- Middleware stacks MUST follow strict sequencing in `ServiceBuilder`: tracing and request ID on the outer layer, timeout and panic interception in the middle, and authentication/authorization on the inner layer.
- Handlers MUST NEVER execute blocking synchronous operations directly on the Tokio runtime thread pool; all blocking calls MUST be offloaded to `tokio::task::spawn_blocking`.
- State structs MUST NOT hold raw database connections or transaction objects directly; they MUST hold connection pools (e.g., `sqlx::Pool`) or transactional factories.

## Bad vs Good Implementations
### Anti-Pattern: Untyped Extension State, Direct Panics, and Unsafe Tower Stack

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension relies on runtime type-map resolution rather than compile-time checking. If the Extension layer is omitted or typed incorrectly, requests will fail at runtime. Furthermore, handlers that panic drop TCP connections without returning a structured 500 response because CatchPanicLayer is missing.
```rust
use axum::{routing::get, Extension, Router};
use tower_http::trace::TraceLayer;

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

async fn get_data(Extension(state): Extension<AppState>) -> String {
    // Runtime panic if Extension layer was forgotten, drops connection immediately
    if state.db_url.is_empty() {
        panic!("Critical database configuration missing!");
    }
    format!("Connected to {}", state.db_url)
}

pub fn app() -> Router {
    // Anti-pattern: runtime-checked Extension, missing CatchPanicLayer
    Router::new()
        .route("/data", get(get_data))
        .layer(TraceLayer::new_for_http())
        .layer(Extension(AppState { db_url: String::new() }))
}
```

#### Production Standard (Correct)
> **Standard**: Type-safe extraction is validated at compile-time via State and FromRef. Tower ServiceBuilder coordinates TraceLayer and CatchPanicLayer with a custom panic handler that guarantees structured JSON responses and error tracing instead of unceremonious connection drops.
```rust
use axum::{
    extract::{FromRef, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Json,
    Router,
};
use serde_json::json;
use std::sync::Arc;
use tower::ServiceBuilder;
use tower_http::{catch_panic::CatchPanicLayer, trace::TraceLayer};

#[derive(Clone)]
pub struct DatabaseConfig {
    pub pool_size: u32,
}

#[derive(Clone)]
pub struct AppState {
    pub db: Arc<DatabaseConfig>,
}

// Compile-time guarantee: modular extractors can extract sub-state directly
impl FromRef<AppState> for Arc<DatabaseConfig> {
    fn from_ref(state: &AppState) -> Self {
        Arc::clone(&state.db)
    }
}

fn handle_panic(err: Box<dyn std::any::Any + Send + 'static>) -> Response {
    let details = err
        .downcast_ref::<&str>()
        .copied()
        .or_else(|| err.downcast_ref::<String>().map(String::as_str))
        .unwrap_or("Unhandled internal error");
    
    tracing::error!(panic_message = %details, "Worker panicked during request handling");
    
    (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({
        "error": "INTERNAL_SERVER_ERROR",
        "message": "A critical processing error occurred."
    }))).into_response()
}

async fn get_data(State(db): State<Arc<DatabaseConfig>>) -> Result<Json<serde_json::Value>, StatusCode> {
    Ok(Json(json!({ "pool_size": db.pool_size })))
}

pub fn app(state: AppState) -> Router {
    let middleware = ServiceBuilder::new()
        .layer(TraceLayer::new_for_http())
        .layer(CatchPanicLayer::custom(handle_panic));

    Router::new()
        .route("/data", get(get_data))
        .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 Type-Safe State Subtyping, Tower Middleware Ordering, and Panic Catching

Axum 0.8 Type-Safe State Subtyping, Tower Middleware Ordering, and Panic Catching defines an industrial-grade behavioral standard for backend engineering. Enforces type-safe state extraction using Axum 0.8's FromRef trait for modular sub-routers, strict Tower ServiceBuilder middleware sequencing, and mandatory CatchPanicLayer integration. Prevents runtime routing panics, state extraction mismatches, and unhandled thread panics dropping active client connections without structured HTTP 500 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-based state injections and unordered Tower middleware stacks lacking panic safety boundaries. 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-based state injections and unordered Tower middleware stacks lacking panic safety boundaries.Critical
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::Extension` for shared application dependencies to ensure compile-time dependency verification.

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<AppState>` for granular sub-states when composing nested modular routers with `Router::with_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.
3

Engineers MUST encapsulate shared mutable states inside `Arc<RwLock<T>>` or `Arc<Atomic*>` and ensure cloned state handles in extractors are cheap shallow references.

Engineers MUST encapsulate shared mutable states inside `Arc<RwLock<T>>` or `Arc<Atomic*>` and ensure cloned state handles in extractors are cheap shallow references.

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

Services MUST place `tower_http::catch_panic::CatchPanicLayer` at the boundary of the `tower::ServiceBuilder` stack to intercept panicking handlers and return structured JSON 500 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.
5

Middleware stacks MUST follow strict sequencing in `ServiceBuilder`

Middleware stacks MUST follow strict sequencing in `ServiceBuilder`: tracing and request ID on the outer layer, timeout and panic interception in the middle, and authentication/authorization on the inner layer.

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

Handlers MUST NEVER execute blocking synchronous operations directly on the Tokio runtime thread pool

Handlers MUST NEVER execute blocking synchronous operations directly on the Tokio runtime thread pool; all blocking calls MUST be offloaded to `tokio::task::spawn_blocking`.

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

State structs MUST NOT hold raw database connections or transaction objects directly

State structs MUST NOT hold raw database connections or transaction objects directly; they MUST hold connection pools (e.g., `sqlx::Pool`) or transactional factories.

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

Enforces type-safe state extraction using Axum 0.8's FromRef trait for modular sub-routers, strict Tower ServiceBuilder middleware sequencing, and mandatory CatchPanicLayer integration. Prevents runtime routing panics, state extraction mismatches, and unhandled thread panics dropping active client connections without structured HTTP 500 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-based state injections and unordered Tower middleware stacks lacking panic safety boundaries.) 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