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-resilience-standard

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

Enforces compile-time type safety for Axum 0.8 application state through the FromRef substate pattern, prevents connection dropping via explicit CatchPanicLayer and HandleErrorLayer integration, and forbids runtime extension lookups in favor of strongly typed State extractors.

Prohibited Anti-Pattern: Dynamic Runtime Extension Lookups, Missing Panic Guards, and Unbounded Tower Error Propagation

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 - Enforces compile-time type safety for Axum 0.8 application state through the FromRef substate pattern, prevents connection dropping via explicit CatchPanicLayer and HandleErrorLayer integration, and forbids runtime extension lookups in favor of strongly typed State extractors.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rust-axum-08-state-tower-resilience-standard"
---

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

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Dynamic Runtime Extension Lookups, Missing Panic Guards, and Unbounded Tower Error Propagation

## System Constraints
You are a Principal Rust Systems Architect enforcing Axum 0.8 and Tower production standards. You strictly mandate compile-time checked State<T> extraction via FromRef, ordered Tower middleware hierarchies with panic recovery, and deterministic response conversions for all fallible operations.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` instead of `axum::Extension` for dependency injection and application state.
- Engineers MUST implement `axum::extract::FromRef` on compound state structs when sub-routers or child modules require isolated access to specific fields.
- Engineers MUST wrap all public routes with `tower_http::catch_panic::CatchPanicLayer` to prevent unhandled panics from severing HTTP/1.1 or HTTP/2 client connections.
- Code MUST place `tower::ServiceBuilder` layers in the correct execution order: outermost guards (timeout, trace, catch_panic) MUST wrap innermost routing and auth layers.
- Services MUST map fallible Tower middleware layers using `tower::load_shed::LoadShedLayer` or `tower::timeout::TimeoutLayer` with an accompanying `axum::error_handling::HandleErrorLayer`.
- Handlers MUST NEVER use raw `.unwrap()` or `.expect()` inside extractor blocks or async blocks; all errors MUST implement `axum::response::IntoResponse`.

## Bad vs Good Implementations
### Type-Safe State Extraction vs Untyped Extension with Panic Guarding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension relies on runtime type map lookups instead of compile-time verification. If an extension is omitted or the wrong type is provided, Axum raises a runtime 500 Internal Server Error without compile-time warnings. Additionally, the lack of CatchPanicLayer drops client connections upon unexpected panic.
```rust
use axum::{routing::get, Extension, Router};
use std::sync::Arc;

struct DatabasePool;
struct AppConfig;

// ANTI-PATTERN: Loose Extension injection causes runtime panics if missing,
// lacking Tower catch-panic middleware and structured state derivation.
async fn handler(Extension(pool): Extension<Arc<DatabasePool>>) -> &'static str {
    let _ = pool;
    "OK"
}

pub fn app() -> Router {
    Router::new()
        .route("/data", get(handler))
        // If developer forgets to add Extension, route compiles but panics at runtime
        .layer(Extension(Arc::new(AppConfig)))
}
```

#### Production Standard (Correct)
> **Standard**: Axum 0.8 State<T> with FromRef guarantees state compatibility at compile time: the app will fail to build if AppState does not supply DatabasePool. CatchPanicLayer converts uncaught panics into well-formed 500 HTTP responses, preserving connection integrity.
```rust
use axum::{
    extract::{FromRef, State},
    http::StatusCode,
    response::IntoResponse,
    routing::get,
    Router,
};
use std::sync::Arc;
use tower::ServiceBuilder;
use tower_http::catch_panic::CatchPanicLayer;
use tower_http::trace::TraceLayer;

#[derive(Clone)]
pub struct DatabasePool;

#[derive(Clone)]
pub struct AppConfig;

#[derive(Clone, FromRef)]
pub struct AppState {
    pub pool: DatabasePool,
    pub config: Arc<AppConfig>,
}

// INVARIANT: Compile-time checked Substate extraction via FromRef
async fn handler(State(pool): State<DatabasePool>) -> impl IntoResponse {
    let _ = pool;
    (StatusCode::OK, "OK")
}

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

pub fn app(state: AppState) -> Router {
    Router::new()
        .route("/data", get(handler))
        .layer(
            ServiceBuilder::new()
                .layer(CatchPanicLayer::custom(handle_panic))
                .layer(TraceLayer::new_for_http()),
        )
        .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. Enforces compile-time type safety for Axum 0.8 application state through the FromRef substate pattern, prevents connection dropping via explicit CatchPanicLayer and HandleErrorLayer integration, and forbids runtime extension lookups in favor of strongly typed State extractors. 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: Dynamic Runtime Extension Lookups, Missing Panic Guards, and Unbounded Tower Error Propagation 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 DriftDynamic Runtime Extension Lookups, Missing Panic Guards, and Unbounded Tower Error PropagationCritical
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 dependency injection and 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.
2

Engineers MUST implement `axum

Engineers MUST implement `axum::extract::FromRef` on compound state structs when sub-routers or child modules require isolated access to specific fields.

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 wrap all public routes with `tower_http

Engineers MUST wrap all public routes with `tower_http::catch_panic::CatchPanicLayer` to prevent unhandled panics from severing HTTP/1.1 or HTTP/2 client 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 place `tower

Code MUST place `tower::ServiceBuilder` layers in the correct execution order: outermost guards (timeout, trace, catch_panic) MUST wrap innermost routing and auth layers.

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

Services MUST map fallible Tower middleware layers using `tower::load_shed::LoadShedLayer` or `tower::timeout::TimeoutLayer` with an accompanying `axum::error_handling::HandleErrorLayer`.

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

Handlers MUST NEVER use raw `.unwrap()` or `.expect()` inside extractor blocks or async blocks

Handlers MUST NEVER use raw `.unwrap()` or `.expect()` inside extractor blocks or async blocks; all errors MUST implement `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.
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?

Enforces compile-time type safety for Axum 0.8 application state through the FromRef substate pattern, prevents connection dropping via explicit CatchPanicLayer and HandleErrorLayer integration, and forbids runtime extension lookups in favor of strongly typed State extractors. 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 (Dynamic Runtime Extension Lookups, Missing Panic Guards, and Unbounded Tower Error Propagation) 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