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-service-safety

Axum 0.8 Type-Safe State Extractors & Tower Middleware Invariants

Enforces Axum 0.8 compile-time type-safe State and Substate extraction via FromRef, strict Tower ServiceBuilder middleware ordering with CatchPanicLayer, and zero unhandled panic rejections across HTTP handler boundaries.

Prohibited Anti-Pattern: Fragile untyped extensions, substate type-mismatch compilation panics, and unshielded middleware stacks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Type-Safe State Extractors & Tower Middleware Invariants - Enforces Axum 0.8 compile-time type-safe State and Substate extraction via FromRef, strict Tower ServiceBuilder middleware ordering with CatchPanicLayer, and zero unhandled panic rejections across HTTP handler boundaries.
globs: src/**/*.rs, tests/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rust-axum-0-8-state-tower-service-safety"
---

# Axum 0.8 Type-Safe State Extractors & Tower Middleware Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Fragile untyped extensions, substate type-mismatch compilation panics, and unshielded middleware stacks

## System Constraints
You are a Principal Rust Systems Architect specializing in Axum 0.8 and the Tower service ecosystem. Enforce compile-time validated state injection, substate extraction through `FromRef`, strict outer-to-inner Tower layer execution topologies, and bulletproof rejection mappings that guarantee zero unhandled runtime panics.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` instead of `axum::extract::Extension` for core application dependencies, ensuring dependency availability is validated at compile-time.
- Engineers MUST implement `axum::extract::FromRef<AppState>` for granular sub-states to keep route handlers loosely coupled and modular.
- Engineers MUST configure `tower_http::catch_panic::CatchPanicLayer` at the boundary of the `Router` to catch panicking handlers and return structured 500 JSON responses rather than severing TCP connections.
- Engineers MUST NEVER invoke `unwrap()` or `expect()` inside custom extractors or handlers; all fallible operations MUST propagate errors via custom types implementing `axum::response::IntoResponse`.
- Engineers MUST order Tower `ServiceBuilder` layers so that telemetry (`TraceLayer`) and panic shielding (`CatchPanicLayer`) wrap timeout, rate-limiting, and authentication layers in the correct outer-to-inner sequence.
- Nested routers MUST receive their shared state via `.with_state()` or inherit sub-states via explicit type contracts, preventing router attachment type mismatches.

## Bad vs Good Implementations
### Type-Safe State and Substate Extraction with Panic Shielding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension circumvents Axum's compile-time State checks, risking runtime panics if the layer is omitted. The unshielded panic abruptly drops the client connection instead of returning a 500 Internal Server Error.
```rust
use axum::{extract::Extension, routing::get, Router};
use std::sync::Arc;

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

// ANTI-PATTERN: Extension lacks compile-time safety and panics at runtime if missing.
// Handler panics without CatchPanicLayer, abruptly dropping HTTP connections.
async fn handler(Extension(state): Extension<Arc<AppState>>) -> &'static str {
    if state.db_pool.is_empty() {
        panic!("Database connection vanished");
    }
    "ok"
}

pub fn make_app() -> Router {
    Router::new()
        .route("/data", get(handler))
        // Extension provided dynamically without static router-level validation
        .layer(axum::extract::Extension(Arc::new(AppState { db_pool: String::new() })))
}
```

#### Production Standard (Correct)
> **Standard**: Leverages Axum 0.8 `State` and `FromRef` for compile-time verified substate extraction. Integrates Tower `CatchPanicLayer` with a custom JSON response handler to guarantee zero dropped sockets on edge-case failures.
```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;
use tower_http::trace::TraceLayer;

#[derive(Clone)]
pub struct AppState {
    pub db_pool: DbPool,
}

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

// Modular substate extraction via FromRef
impl FromRef<AppState> for DbPool {
    fn from_ref(state: &AppState) -> Self {
        state.db_pool.clone()
    }
}

fn handle_panic(err: Box<dyn std::any::Any + Send + 'static>) -> Response {
    let details = if let Some(s) = err.downcast_ref::<&str>() {
        s.to_string()
    } else if let Some(s) = err.downcast_ref::<String>() {
        s.clone()
    } else {
        "Unknown panic payload".to_string()
    };
    tracing::error!(panic_details = %details, "Unhandled handler panic caught");
    (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": "Internal server error"}))).into_response()
}

async fn handler(State(pool): State<DbPool>) -> Result<&'static str, StatusCode> {
    if pool.0.is_empty() {
        return Err(StatusCode::SERVICE_UNAVAILABLE);
    }
    Ok("healthy")
}

pub fn build_router(state: AppState) -> Router {
    Router::new()
        .route("/health", get(handler))
        .layer(
            ServiceBuilder::new()
                .layer(TraceLayer::new_for_http())
                .layer(CatchPanicLayer::custom(handle_panic))
        )
        .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 & Tower Middleware Invariants

Axum 0.8 Type-Safe State Extractors & Tower Middleware Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces Axum 0.8 compile-time type-safe State and Substate extraction via FromRef, strict Tower ServiceBuilder middleware ordering with CatchPanicLayer, and zero unhandled panic rejections across HTTP handler boundaries. 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: Fragile untyped extensions, substate type-mismatch compilation panics, and unshielded middleware stacks 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 DriftFragile untyped extensions, substate type-mismatch compilation panics, and unshielded middleware stacksCritical
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::extract::Extension` for core application dependencies, ensuring dependency availability is validated at compile-time.

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 to keep route handlers loosely coupled and modular.

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

Engineers MUST configure `tower_http::catch_panic::CatchPanicLayer` at the boundary of the `Router` to catch panicking handlers and return structured 500 JSON responses rather than severing 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

Engineers MUST NEVER invoke `unwrap()` or `expect()` inside custom extractors or handlers

Engineers MUST NEVER invoke `unwrap()` or `expect()` inside custom extractors or handlers; all fallible operations MUST propagate errors via custom types implementing `axum::response::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.
5

Engineers MUST order Tower `ServiceBuilder` layers so that telemetry (`TraceLayer`) and panic shielding (`CatchPanicLayer`) wrap timeout, rate-limiting, and authentication layers in the correct outer-to-inner sequence.

Engineers MUST order Tower `ServiceBuilder` layers so that telemetry (`TraceLayer`) and panic shielding (`CatchPanicLayer`) wrap timeout, rate-limiting, and authentication layers in the correct outer-to-inner sequence.

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

Nested routers MUST receive their shared state via `.with_state()` or inherit sub-states via explicit type contracts, preventing router attachment type mismatches.

Nested routers MUST receive their shared state via `.with_state()` or inherit sub-states via explicit type contracts, preventing router attachment type mismatches.

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

Enforces Axum 0.8 compile-time type-safe State and Substate extraction via FromRef, strict Tower ServiceBuilder middleware ordering with CatchPanicLayer, and zero unhandled panic rejections across HTTP handler boundaries. 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 (Fragile untyped extensions, substate type-mismatch compilation panics, and unshielded middleware stacks) 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