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

Axum 0.8 Type-Safe State, Tower Middleware Invariants, and Panic Isolation

Mandates type-safe State and FromRef extraction over dynamic Extensions, strictly enforces extractor parameter ordering where body-consuming extractors must be terminal, and guarantees zero unhandled connection drops via Tower CatchPanicLayer and typed rejections.

Prohibited Anti-Pattern: Untyped runtime extensions, inverted handler extractor ordering, and missing panic layers that terminate HTTP connections abruptly.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Type-Safe State, Tower Middleware Invariants, and Panic Isolation - Mandates type-safe State and FromRef extraction over dynamic Extensions, strictly enforces extractor parameter ordering where body-consuming extractors must be terminal, and guarantees zero unhandled connection drops via Tower CatchPanicLayer and typed rejections.
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"
---

# Axum 0.8 Type-Safe State, Tower Middleware Invariants, and Panic Isolation

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Untyped runtime extensions, inverted handler extractor ordering, and missing panic layers that terminate HTTP connections abruptly.

## System Constraints
You are a Principal Backend Systems Architect enforcing strict Rust Axum 0.8 and Tower Service invariants. Your rules mandate type-safe State<T> and FromRef composition over dynamic Extensions, terminal placement of body-consuming extractors in handler signatures, explicit Tower ServiceBuilder ordering, and CatchPanicLayer integration for resilient fail-safe HTTP error recovery.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` and derive or implement `axum::extract::FromRef` for sub-states instead of using runtime-checked `axum::Extension`.
- Engineers MUST ALWAYS place body-consuming extractors (`Json<T>`, `Bytes`, `String`) as the final parameter in Axum handler signatures to prevent compilation errors or unexpected stream exhaustion.
- Engineers MUST ALWAYS configure `tower_http::catch_panic::CatchPanicLayer` at the root router level to guarantee panics produce an HTTP 500 response rather than dropping TCP connections.
- Code MUST structure Tower middleware inside `tower::ServiceBuilder` adhering to explicit layer execution order: Observability (TraceLayer) -> Panic Containment (CatchPanicLayer) -> Request Limits/Timeout -> Authentication -> Route Execution.
- Services MUST map all extractor rejections and internal domain errors to an application-level enum implementing `axum::response::IntoResponse` with structured JSON payloads rather than leaking default plain-text error rejections.

## Bad vs Good Implementations
### Type-Safe State and Resilient Tower Middleware in Axum 0.8

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Placing Json before Path violates Axum's extractor contract (body extractors must be terminal). Relying on Extension deferrals bypasses compile-time state guarantees and will cause runtime panics if missing. The handler explicitly panics, and without CatchPanicLayer, hyper immediately drops the underlying TCP socket without emitting a valid HTTP 500 response.
```rust
use axum::{routing::post, Router, Extension, extract::{Json, Path}};
use serde::Deserialize;
use uuid::Uuid;

#[derive(Clone)]
struct AppState { db_pool: String }
#[derive(Deserialize)]
struct CreateItem { name: String }

// ANTI-PATTERN: 
// 1. Json consumes body before Path extractor runs
// 2. Uses Extension instead of compile-time checked State
// 3. Panics on unwrap with no CatchPanicLayer, abruptly resetting TCP connection
async fn create_item(
    Json(payload): Json<CreateItem>,
    Path(id): Path<Uuid>,
    Extension(state): Extension<AppState>,
) -> String {
    if payload.name.is_empty() {
        panic!("Invalid item name!");
    }
    format!("Created {} for {} using {}", payload.name, id, state.db_pool)
}

pub fn app() -> Router {
    Router::new()
        .route("/items/:id", post(create_item))
        .layer(Extension(AppState { db_pool: "postgres://...".into() }))
}
```

#### Production Standard (Correct)
> **Standard**: Type-safe State<DbPool> uses FromRef for modular state extraction. Non-body extractors precede the terminal Json extractor. CatchPanicLayer isolates unwinding panics into structured HTTP 500 JSON responses, protecting the Tower service stack and underlying TCP connection.
```rust
use axum::{
    extract::{FromRef, Path, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::post,
    Json, Router,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tower::ServiceBuilder;
use tower_http::{
    catch_panic::CatchPanicLayer,
    trace::TraceLayer,
};
use uuid::Uuid;

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

// Sub-state extraction via FromRef for modular domain routing
#[derive(Clone)]
pub struct DbPool(pub Arc<String>);

impl FromRef<AppState> for DbPool {
    fn from_ref(state: &AppState) -> Self {
        DbPool(Arc::clone(&state.db_pool))
    }
}

#[derive(Deserialize)]
pub struct CreateItem { pub name: String }

#[derive(Serialize)]
pub struct ItemResponse { pub id: Uuid, pub name: String }

#[derive(Serialize)]
pub struct ErrorResponse { pub error: String }

// INVARIANT: Non-body extractors (Path, State) FIRST; Body extractor (Json) LAST
async fn create_item(
    State(DbPool(_pool)): State<DbPool>,
    Path(id): Path<Uuid>,
    Json(payload): Json<CreateItem>,
) -> Result<Json<ItemResponse>, AppError> {
    if payload.name.trim().is_empty() {
        return Err(AppError::BadRequest("Item name cannot be empty".into()));
    }
    Ok(Json(ItemResponse { id, name: payload.name }))
}

enum AppError {
    BadRequest(String),
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, msg) = match self {
            AppError::BadRequest(m) => (StatusCode.BAD_REQUEST, m),
        };
        (status, Json(ErrorResponse { error: msg })).into_response()
    }
}

pub fn build_app(state: AppState) -> Router {
    Router::new()
        .route("/items/{id}", post(create_item))
        .layer(
            ServiceBuilder::new()
                .layer(TraceLayer::new_for_http())
                .layer(CatchPanicLayer::custom(handle_panic))
        )
        .with_state(state)
}

fn handle_panic(_err: Box<dyn std::any::Any + Send + 'static>) -> Response {
    (StatusCode::INTERNAL_SERVER_ERROR, Json(ErrorResponse {
        error: "Internal server error occurred".into()
    })).into_response()
}
```

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, Tower Middleware Invariants, and Panic Isolation

Axum 0.8 Type-Safe State, Tower Middleware Invariants, and Panic Isolation defines an industrial-grade behavioral standard for backend engineering. Mandates type-safe State and FromRef extraction over dynamic Extensions, strictly enforces extractor parameter ordering where body-consuming extractors must be terminal, and guarantees zero unhandled connection drops via Tower CatchPanicLayer and typed rejections. 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 runtime extensions, inverted handler extractor ordering, and missing panic layers that terminate HTTP connections abruptly. 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 runtime extensions, inverted handler extractor ordering, and missing panic layers that terminate HTTP connections abruptly.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` and derive or implement `axum::extract::FromRef` for sub-states instead of using runtime-checked `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 ALWAYS place body-consuming extractors (`Json<T>`, `Bytes`, `String`) as the final parameter in Axum handler signatures to prevent compilation errors or unexpected stream exhaustion.

Engineers MUST ALWAYS place body-consuming extractors (`Json<T>`, `Bytes`, `String`) as the final parameter in Axum handler signatures to prevent compilation errors or unexpected stream exhaustion.

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

Engineers MUST ALWAYS configure `tower_http::catch_panic::CatchPanicLayer` at the root router level to guarantee panics produce an HTTP 500 response rather than dropping TCP 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

Code MUST structure Tower middleware inside `tower

Code MUST structure Tower middleware inside `tower::ServiceBuilder` adhering to explicit layer execution order: Observability (TraceLayer) -> Panic Containment (CatchPanicLayer) -> Request Limits/Timeout -> Authentication -> Route Execution.

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

Services MUST map all extractor rejections and internal domain errors to an application-level enum implementing `axum

Services MUST map all extractor rejections and internal domain errors to an application-level enum implementing `axum::response::IntoResponse` with structured JSON payloads rather than leaking default plain-text error 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.
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, Tower Middleware Invariants, and Panic Isolation critical for AI coding assistants?

Mandates type-safe State and FromRef extraction over dynamic Extensions, strictly enforces extractor parameter ordering where body-consuming extractors must be terminal, and guarantees zero unhandled connection drops via Tower CatchPanicLayer and typed rejections. 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 runtime extensions, inverted handler extractor ordering, and missing panic layers that terminate HTTP connections abruptly.) 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