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

Axum 0.8 Type-Safe State Extractors & Resilient Tower Middleware Composition

Enforces Axum 0.8 idioms for type-safe state extraction via FromRef and State<T>, deterministic Tower ServiceBuilder middleware sequencing, and mandatory CatchPanicLayer integration. Prevents runtime state-resolution panics, dropped connections, and silent request body consumption errors.

Prohibited Anti-Pattern: Runtime Extension extraction failures, inverted Tower middleware order, and unhandled handler panics causing connection drops

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Type-Safe State Extractors & Resilient Tower Middleware Composition - Enforces Axum 0.8 idioms for type-safe state extraction via FromRef and State<T>, deterministic Tower ServiceBuilder middleware sequencing, and mandatory CatchPanicLayer integration. Prevents runtime state-resolution panics, dropped connections, and silent request body consumption errors.
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-guardrails"
---

# Axum 0.8 Type-Safe State Extractors & Resilient Tower Middleware Composition

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Runtime Extension extraction failures, inverted Tower middleware order, and unhandled handler panics causing connection drops

## System Constraints
You are a Principal Rust Architect enforcing Axum 0.8 and Tower Service production standards. Axum 0.8 enforces compile-time type verification through State extractors and substate derivation via FromRef. You must prohibit Extension-based dependency injection for global state, mandate CatchPanicLayer and TraceLayer ordering within Tower's ServiceBuilder, strictly order extractors such that body-consuming extractors (Json, Bytes) are evaluated last, and map all custom rejections into explicit HTTP responses without runtime panics.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` with types implementing `Clone + Send + Sync + 'static` instead of `axum::extract::Extension` for application dependencies.
- Engineers MUST implement `axum::extract::FromRef<AppState>` for granular sub-states (e.g., DatabasePool, CacheClient) to decouple handlers from the monolith application state.
- Engineers MUST place consuming extractors (such as `axum::Json<T>`, `axum::body::Bytes`, or custom streaming bodies) as the absolute LAST parameter in handler signatures.
- Engineers MUST wrap all top-level routers with `tower_http::catch_panic::CatchPanicLayer` to prevent unhandled panics from terminating Tokio worker tasks or dropping HTTP/2 TCP streams without a 500 response.
- Services MUST define Tower middleware using `tower::ServiceBuilder` to ensure canonical top-to-bottom outer-to-inner execution order.
- Engineers MUST distinguish between `Router::layer` (wraps entire router including fallback) and `Router::route_layer` (applies solely to matched routes before fallback matching).
- Components NEVER expose raw Tokio or SQLx errors across HTTP boundaries; all handler errors MUST implement `axum::response::IntoResponse` with structured JSON payloads and appropriate `StatusCode` values.

## Bad vs Good Implementations
### State Extraction and Resilient Tower Middleware Stack

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension relies on runtime dynamic typing which panics if the type is unregistered. Placing Json before Extension violates Axum's extractor protocol. A panic inside the handler crashes the task without an RFC-compliant HTTP 500 response.
```rust
use axum::{routing::post, Router, Extension, Json};
use serde::Deserialize;
use std::sync::Arc;

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

#[derive(Deserialize)]
struct Payload { data: String }

// ANTI-PATTERN: Consuming body extractor `Json` is placed before Extension;
// Extension extraction fails at runtime with panic if not registered;
// Raw panic causes abrupt HTTP connection drop without 500 status.
async fn create_item(
    Json(payload): Json<Payload>,
    Extension(state): Extension<AppState>,
) -> String {
    if payload.data.is_empty() {
        panic!("invalid payload"); // Dropped connection!
    }
    format!("Inserted {} into {}", payload.data, state.db)
}

pub fn app() -> Router {
    Router::new()
        .route("/items", post(create_item))
        // Missing State type verification and CatchPanicLayer
        .layer(Extension(AppState { db: Arc::new("postgres://...".into()) }))
}
```

#### Production Standard (Correct)
> **Standard**: Employs type-safe State with FromRef substate extraction verified at compile time. CatchPanicLayer captures unforeseen panics and safely returns HTTP 500. Json extractor is placed last, and errors are mapped via IntoResponse.
```rust
use axum::{
    extract::{FromRef, 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;
use tower_http::trace::TraceLayer;

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

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

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

#[derive(Deserialize)]
pub struct CreateItemRequest {
    pub data: String,
}

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

pub 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()
    }
}

// INVARIANT: State extractor derived via FromRef; Body-consuming extractor placed LAST
async fn create_item(
    State(DbPool(db)): State<DbPool>,
    Json(payload): Json<CreateItemRequest>,
) -> Result<StatusCode, AppError> {
    if payload.data.is_empty() {
        return Err(AppError::BadRequest("data cannot be empty".into()));
    }
    let _ = db;
    Ok(StatusCode::CREATED)
}

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

    Router::new()
        .route("/items", post(create_item))
        .layer(middleware_stack)
        .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 Extractors & Resilient Tower Middleware Composition

Axum 0.8 Type-Safe State Extractors & Resilient Tower Middleware Composition defines an industrial-grade behavioral standard for backend engineering. Enforces Axum 0.8 idioms for type-safe state extraction via FromRef and State<T>, deterministic Tower ServiceBuilder middleware sequencing, and mandatory CatchPanicLayer integration. Prevents runtime state-resolution panics, dropped connections, and silent request body consumption errors. 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 Extension extraction failures, inverted Tower middleware order, and unhandled handler panics causing connection drops 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 Extension extraction failures, inverted Tower middleware order, and unhandled handler panics causing connection dropsCritical
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 types implementing `Clone + Send + Sync + 'static` instead of `axum::extract::Extension` for application dependencies.

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 (e.g., DatabasePool, CacheClient) to decouple handlers from the monolith 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.
3

Engineers MUST place consuming extractors (such as `axum

Engineers MUST place consuming extractors (such as `axum::Json<T>`, `axum::body::Bytes`, or custom streaming bodies) as the absolute LAST parameter in handler signatures.

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

Engineers MUST wrap all top-level routers with `tower_http

Engineers MUST wrap all top-level routers with `tower_http::catch_panic::CatchPanicLayer` to prevent unhandled panics from terminating Tokio worker tasks or dropping HTTP/2 TCP streams without a 500 response.

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 define Tower middleware using `tower

Services MUST define Tower middleware using `tower::ServiceBuilder` to ensure canonical top-to-bottom outer-to-inner execution order.

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

Engineers MUST distinguish between `Router

Engineers MUST distinguish between `Router::layer` (wraps entire router including fallback) and `Router::route_layer` (applies solely to matched routes before fallback matching).

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

Components NEVER expose raw Tokio or SQLx errors across HTTP boundaries

Components NEVER expose raw Tokio or SQLx errors across HTTP boundaries; all handler errors MUST implement `axum::response::IntoResponse` with structured JSON payloads and appropriate `StatusCode` values.

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 Extractors & Resilient Tower Middleware Composition critical for AI coding assistants?

Enforces Axum 0.8 idioms for type-safe state extraction via FromRef and State<T>, deterministic Tower ServiceBuilder middleware sequencing, and mandatory CatchPanicLayer integration. Prevents runtime state-resolution panics, dropped connections, and silent request body consumption errors. 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 Extension extraction failures, inverted Tower middleware order, and unhandled handler panics causing connection drops) 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