This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: rust-axum-08-state-tower-guardrail

Axum 0.8 Strict Type-Safe State Extraction and Tower Middleware Invariants

Mandates compile-time verified dependency injection via Axum 0.8 State extractors with FromRef modular sub-state derivation. Enforces deterministic Tower Service layer ordering with CatchPanicLayer at the perimeter to guarantee zero unhandled runtime panic drops.

Prohibited Anti-Pattern: Untyped Extension Passing, Missing FromRef Decompositions, and Unhandled Panic Connection Drops

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Strict Type-Safe State Extraction and Tower Middleware Invariants - Mandates compile-time verified dependency injection via Axum 0.8 State extractors with FromRef modular sub-state derivation. Enforces deterministic Tower Service layer ordering with CatchPanicLayer at the perimeter to guarantee zero unhandled runtime panic drops.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rust-axum-08-state-tower-guardrail"
---

# Axum 0.8 Strict Type-Safe State Extraction and Tower Middleware Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Untyped Extension Passing, Missing FromRef Decompositions, and Unhandled Panic Connection Drops

## System Constraints
You are a Principal Systems Architect enforcing Rust Axum 0.8 State Extractors and Tower Service integrity. You strictly enforce compile-time dependency injection using axum::extract::State and FromRef, reject untyped Extension usage for core services, mandate exact Tower middleware layer ordering, and require custom CatchPanicLayer boundary handling to prevent process abortion or socket termination.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State<T>` instead of untyped `axum::Extension<T>` for core application dependencies.
- Engineers MUST implement `axum::extract::FromRef<AppState>` for granular sub-states to prevent modular routers from coupling directly to monolithic root state structs.
- Engineers MUST ALWAYS apply `tower_http::catch_panic::CatchPanicLayer` with a custom error response converter as the outermost layer of the application router stack.
- Engineers MUST preserve the deterministic Tower execution sequence: CatchPanic -> Trace/Telemetry -> Timeout -> Compression/CORS -> Authentication -> Handler.
- Engineers MUST NOT call `.unwrap()` or `.expect()` inside Axum handlers; all fallible domain operations MUST resolve to an explicit `Result<T, AppError>` implementing `IntoResponse` with sanitized client payloads.
- Nested routers MUST consume sub-states via `.with_state()` or inherit sub-states strictly derived through `FromRef`.

## Bad vs Good Implementations
### State Extraction and Middleware Layering

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension bypasses Axum's compile-time type-safety guarantees, causing runtime panics if state is omitted. Missing CatchPanicLayer causes abrupt connection drops when unwrap() panics.
```rust
use axum::{routing::get, Extension, Router};
use std::sync::Arc;

struct AppState {
    db: String,
}

// ANTI-PATTERN: Untyped runtime extension lookup, panics unhandled, no FromRef isolation
async fn get_db(Extension(state): Extension<Arc<AppState>>) -> String {
    // Runtime failure if Extension was omitted, unhandled panic drops TCP stream
    let db_val = state.db.split(':').nth(1).unwrap();
    db_val.to_string()
}

pub fn app() -> Router {
    Router::new()
        .route("/db", get(get_db))
        // Fragile: Extension lacks compile-time state completeness checks
        .layer(Extension(Arc::new(AppState { db: "postgres:primary".into() })))
}
```

#### Production Standard (Correct)
> **Standard**: Uses compile-time checked `State` with `FromRef` for modular sub-state injection. Employs `CatchPanicLayer::custom` to sanitize panics into standard 500 HTTP responses, and handles missing substrings explicitly without panic.
```rust
use axum::{
    extract::{FromRef, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use std::sync::Arc;
use tower::ServiceBuilder;
use tower_http::catch_panic::CatchPanicLayer;

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

#[derive(Clone)]
pub struct AppState {
    pub db: DatabasePool,
}

// Sub-state extraction via FromRef prevents handler coupling to root state
impl FromRef<AppState> for DatabasePool {
    fn from_ref(state: &AppState) -> Self {
        state.db.clone()
    }
}

fn handle_panic(_err: Box<dyn std::any::Any + Send + 'static>) -> Response {
    (StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error").into_response()
}

async fn get_db(State(db): State<DatabasePool>) -> Result<String, (StatusCode, &'static str)> {
    db.0.split(':')
        .nth(1)
        .map(|s| s.to_string())
        .ok_or((StatusCode::BAD_REQUEST, "Malformed connection string"))
}

pub fn app(state: AppState) -> Router {
    Router::new()
        .route("/db", get(get_db))
        .layer(
            ServiceBuilder::new()
                .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 Strict Type-Safe State Extraction and Tower Middleware Invariants

Axum 0.8 Strict Type-Safe State Extraction and Tower Middleware Invariants defines an industrial-grade behavioral standard for backend engineering. Mandates compile-time verified dependency injection via Axum 0.8 State extractors with FromRef modular sub-state derivation. Enforces deterministic Tower Service layer ordering with CatchPanicLayer at the perimeter to guarantee zero unhandled runtime panic 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: Untyped Extension Passing, Missing FromRef Decompositions, and Unhandled Panic 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 DriftUntyped Extension Passing, Missing FromRef Decompositions, and Unhandled Panic 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<T>` instead of untyped `axum::Extension<T>` for core 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 to prevent modular routers from coupling directly to monolithic root state structs.

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

Engineers MUST ALWAYS apply `tower_http::catch_panic::CatchPanicLayer` with a custom error response converter as the outermost layer of the application router stack.

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 preserve the deterministic Tower execution sequence

Engineers MUST preserve the deterministic Tower execution sequence: CatchPanic -> Trace/Telemetry -> Timeout -> Compression/CORS -> Authentication -> Handler.

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 `.unwrap()` or `.expect()` inside Axum handlers

Engineers MUST NOT call `.unwrap()` or `.expect()` inside Axum handlers; all fallible domain operations MUST resolve to an explicit `Result<T, AppError>` implementing `IntoResponse` with sanitized client payloads.

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 consume sub-states via `.with_state()` or inherit sub-states strictly derived through `FromRef`.

Nested routers MUST consume sub-states via `.with_state()` or inherit sub-states strictly derived through `FromRef`.

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 Strict Type-Safe State Extraction and Tower Middleware Invariants critical for AI coding assistants?

Mandates compile-time verified dependency injection via Axum 0.8 State extractors with FromRef modular sub-state derivation. Enforces deterministic Tower Service layer ordering with CatchPanicLayer at the perimeter to guarantee zero unhandled runtime panic 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 (Untyped Extension Passing, Missing FromRef Decompositions, and Unhandled Panic 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