This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-0-8-type-safe-state-and-tower-composition

Axum 0.8 Type-Safe State Extraction, Tower Middleware Composition & Panic Guardrails

Mandates compile-time type-safe state extraction via Axum 0.8's State extractor and FromRef pattern, eliminating runtime Extension panics. Enforces deterministic Tower ServiceBuilder layer ordering and boundary-level panic interception to ensure zero unhandled connection drops.

Prohibited Anti-Pattern: Runtime Panics via Fallible Extension Extractors & Dropped Connections from Inverted Tower Layers

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 Composition & Panic Guardrails - Mandates compile-time type-safe state extraction via Axum 0.8's State extractor and FromRef pattern, eliminating runtime Extension panics. Enforces deterministic Tower ServiceBuilder layer ordering and boundary-level panic interception to ensure zero unhandled connection drops.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-type-safe-state-and-tower-composition"
---

# Axum 0.8 Type-Safe State Extraction, Tower Middleware Composition & Panic Guardrails

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Runtime Panics via Fallible Extension Extractors & Dropped Connections from Inverted Tower Layers

## System Constraints
You are a Principal Rust Architect enforcing idiomatic, high-performance, and resilient Axum 0.8 services. Mandate compile-time type safety via `axum::extract::State` and `axum::extract::FromRef`. Prohibit dynamic `Extension` for core application dependencies. Enforce deterministic Tower middleware layering with `ServiceBuilder`, and guarantee zero unhandled panic rejections across all HTTP boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` instead of `axum::Extension` for required application dependencies (e.g., database connection pools, clients, configuration).
- Engineers MUST implement `axum::extract::FromRef<AppState>` for granular sub-states rather than injecting the monolithic `AppState` into leaf handlers.
- Engineers MUST use `tower::ServiceBuilder` to construct middleware stacks, ensuring consistent top-to-bottom outer-to-inner execution ordering.
- Services MUST include `tower_http::catch_panic::CatchPanicLayer` wrapped with a custom panic-to-response handler to prevent hyper from dropping TCP connections without valid HTTP status codes.
- Engineers MUST NOT call `.layer()` sequentially on `axum::Router` when ordering dependencies matter, because Axum's `.layer()` executes layers from bottom-to-top (inside-out) whereas `ServiceBuilder` executes in declared order.
- Custom extractors MUST implement `FromRequest` or `FromRequestParts` with custom error rejection types implementing `IntoResponse` that serialize deterministic JSON errors instead of default plain-text rejections.
- Shared state structs MUST be cheap to clone (e.g., wrap internal mutable state in `Arc` or use client pools that internally manage `Arc`).

## Bad vs Good Implementations
### State Extraction & Tower Layer Composition (Axum 0.8)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension<T> moves dependency verification from compile-time to runtime, leading to catastrophic runtime panics if a layer is forgotten. Furthermore, failing to handle panics via CatchPanicLayer causes hyper to terminate HTTP streams abruptly without a valid response body, and raw sequential Router::layer calls lead to execution-order hazards.
```rust
use axum::{routing::get, Extension, Router, Json};
use std::sync::Arc;
use tower_http::trace::TraceLayer;

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

// ANTI-PATTERN: Extension panics at runtime if omitted in router setup.
// Handlers take monolithic state or loosely typed extensions.
async fn get_users(Extension(state): Extension<Arc<AppState>>) -> Json<Vec<String>> {
    // If Extension is not registered, hyper panics with unhandled 500 or connection drop
    Json(vec!["alice".to_string()])
}

pub fn build_app(state: AppState) -> Router {
    Router::new()
        .route("/users", get(get_users))
        // Inverted or sequential .layer calls lead to counterintuitive execution order
        // No CatchPanicLayer means an internal panic aborts the TCP stream without an HTTP response
        .layer(TraceLayer::new_for_http())
        .layer(Extension(Arc::new(state)))
}
```

#### Production Standard (Correct)
> **Standard**: State extraction is verified at compile-time using State and FromRef, preventing runtime routing crashes. The ServiceBuilder cleanly defines the Tower stack with CatchPanicLayer outermost, ensuring panics produce structured JSON 500 responses rather than dropped connections.
```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 AppState {
    pub db_pool: sqlx::PgPool,
    pub api_version: Arc<str>,
}

// Sub-state extraction: handlers only depend on what they need
impl FromRef<AppState> for sqlx::PgPool {
    fn from_ref(state: &AppState) -> Self {
        state.db_pool.clone()
    }
}

// Compile-time safe extraction of PgPool via FromRef
async fn get_users(State(pool): State<sqlx::PgPool>) -> Result<Json<Vec<String>>, AppError> {
    Ok(Json(vec!["alice".to_string()]))
}

fn handle_panic(_err: Box<dyn std::any::Any + Send + 'static>) -> Response {
    let body = Json(json!({
        "error": {
            "code": "INTERNAL_SERVER_ERROR",
            "message": "An unexpected panic occurred"
        }
    }));
    (StatusCode::INTERNAL_SERVER_ERROR, body).into_response()
}

pub fn build_app(state: AppState) -> Router {
    // ServiceBuilder guarantees explicit top-to-bottom execution order
    let middleware = ServiceBuilder::new()
        .layer(CatchPanicLayer::custom(handle_panic))
        .layer(TraceLayer::new_for_http());

    Router::new()
        .route("/users", get(get_users))
        .layer(middleware)
        .with_state(state) // Axum 0.8 verified compile-time state contract
}

enum AppError {
    Database(sqlx::Error),
}

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Axum 0.8 Type-Safe State Extraction, Tower Middleware Composition & Panic Guardrails

Axum 0.8 Type-Safe State Extraction, Tower Middleware Composition & Panic Guardrails defines an industrial-grade behavioral standard for backend engineering. Mandates compile-time type-safe state extraction via Axum 0.8's State extractor and FromRef pattern, eliminating runtime Extension panics. Enforces deterministic Tower ServiceBuilder layer ordering and boundary-level panic interception to ensure zero unhandled connection drops. 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 via Fallible Extension Extractors & Dropped Connections from Inverted Tower Layers 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 via Fallible Extension Extractors & Dropped Connections from Inverted Tower LayersCritical
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 required application dependencies (e.g., database connection pools, clients, configuration).

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 rather than injecting the monolithic `AppState` into leaf 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.
3

Engineers MUST use `tower

Engineers MUST use `tower::ServiceBuilder` to construct middleware stacks, ensuring consistent top-to-bottom outer-to-inner execution ordering.

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

Services MUST include `tower_http::catch_panic::CatchPanicLayer` wrapped with a custom panic-to-response handler to prevent hyper from dropping TCP connections without valid HTTP status codes.

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

Engineers MUST NOT call `.layer()` sequentially on `axum

Engineers MUST NOT call `.layer()` sequentially on `axum::Router` when ordering dependencies matter, because Axum's `.layer()` executes layers from bottom-to-top (inside-out) whereas `ServiceBuilder` executes in declared 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

Custom extractors MUST implement `FromRequest` or `FromRequestParts` with custom error rejection types implementing `IntoResponse` that serialize deterministic JSON errors instead of default plain-text rejections.

Custom extractors MUST implement `FromRequest` or `FromRequestParts` with custom error rejection types implementing `IntoResponse` that serialize deterministic JSON errors instead of default plain-text 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.
7

Shared state structs MUST be cheap to clone (e.g., wrap internal mutable state in `Arc` or use client pools that internally manage `Arc`).

Shared state structs MUST be cheap to clone (e.g., wrap internal mutable state in `Arc` or use client pools that internally manage `Arc`).

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 Composition & Panic Guardrails critical for AI coding assistants?

Mandates compile-time type-safe state extraction via Axum 0.8's State extractor and FromRef pattern, eliminating runtime Extension panics. Enforces deterministic Tower ServiceBuilder layer ordering and boundary-level panic interception to ensure zero unhandled connection drops. 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 via Fallible Extension Extractors & Dropped Connections from Inverted Tower Layers) 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