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-and-tower-middleware-invariants

Axum 0.8 Type-Safe Sub-State Composition & Resilient Tower Middleware Ordering

Mandates compile-time type-safe FromRef sub-state extraction and deterministic Tower ServiceBuilder ordering in Axum 0.8 services. Prevents runtime extractor rejections, state type mismatches across modular sub-routers, and connection dropping from unhandled task panics.

Prohibited Anti-Pattern: Relying on untyped Extension injection and unhandled panics instead of FromRef State and CatchPanicLayer composition.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Type-Safe Sub-State Composition & Resilient Tower Middleware Ordering - Mandates compile-time type-safe FromRef sub-state extraction and deterministic Tower ServiceBuilder ordering in Axum 0.8 services. Prevents runtime extractor rejections, state type mismatches across modular sub-routers, and connection dropping from unhandled task panics.
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-and-tower-middleware-invariants"
---

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

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Relying on untyped Extension injection and unhandled panics instead of FromRef State and CatchPanicLayer composition.

## System Constraints
You are a Principal Rust Architect enforcing Axum 0.8 and Tower production invariants. Mandate compile-time type-safe State extraction via FromRef, strict Tower ServiceBuilder ordering, and zero-panic boundary enforcement.

## Strict Guidelines
- Engineers MUST ALWAYS use axum::extract::State<T> with FromRef implementations instead of axum::Extension for compile-time verified application state.
- Engineers MUST ALWAYS register tower_http::catch_panic::CatchPanicLayer inside the outermost TraceLayer to guarantee that panics are converted into 500 Internal Server Error responses and logged.
- Engineers MUST compose Tower layers via ServiceBuilder, placing TraceLayer outermost, followed by CatchPanicLayer, TimeoutLayer, and finally domain-specific authorization/rate-limiting middlewares.
- Engineers MUST NOT allow sub-routers to leak monolithic state dependencies; sub-routers MUST declare their own minimal state parameter S and leverage S: FromRef<AppState>.
- Engineers MUST wrap fallible extractors (Json, Query, Path) with custom AppRejection types to ensure predictable, structured RFC 7807 problem details rather than exposing raw Axum rejection strings.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension<T> bypasses Axum's compile-time State checks, risking runtime HTTP 500 drops if the extension is omitted. Additionally, the lack of CatchPanicLayer causes Tokio worker tasks to terminate abruptly without emitting valid HTTP response frames when panics occur.
```rust
use axum::{routing::get, Extension, Router};
use tower_http::trace::TraceLayer;

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

// ANTI-PATTERN: Extension causes runtime panic if omitted;
// Missing CatchPanicLayer drops connection on panic;
// No sub-state decoupling.
async fn get_db(Extension(pool): Extension<String>) -> String {
    if pool.is_empty() {
        panic!("Database connection lost!"); // Unhandled panic crashes the HTTP response task
    }
    format!("Connected to: {}", pool)
}

pub fn app() -> Router {
    Router::new()
        .route("/db", get(get_db))
        // TraceLayer alone leaves panics uncaught and unwrapped
        .layer(TraceLayer::new_for_http())
}
```

#### Production Standard (Correct)
> **Standard**: Uses Axum 0.8 State with FromRef to guarantee compile-time verification of injected sub-state. Employs ServiceBuilder to wrap the handler with TraceLayer and CatchPanicLayer, gracefully converting unhandled panics into structured JSON responses.
```rust
use axum::{extract::{FromRef, State}, http::StatusCode, response::{IntoResponse, Response}, routing::get, Json, Router};
use tower::ServiceBuilder;
use tower_http::{catch_panic::CatchPanicLayer, trace::TraceLayer};

#[derive(Clone)]
pub struct DatabaseConfig { pub connection_string: String }

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

// INVARIANT: Implement FromRef for modular sub-state extraction
impl FromRef<AppState> for DatabaseConfig {
    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, Json(serde_json::json!({
        "error": "InternalServerError",
        "message": "An unexpected error occurred."
    }))).into_response()
}

async fn get_db(State(db): State<DatabaseConfig>) -> Result<String, StatusCode> {
    Ok(format!("Connected to: {}", db.connection_string))
}

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

    Router::new()
        .route("/db", get(get_db))
        .layer(middleware)
        .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 Sub-State Composition & Resilient Tower Middleware Ordering

Axum 0.8 Type-Safe Sub-State Composition & Resilient Tower Middleware Ordering defines an industrial-grade behavioral standard for backend engineering. Mandates compile-time type-safe FromRef sub-state extraction and deterministic Tower ServiceBuilder ordering in Axum 0.8 services. Prevents runtime extractor rejections, state type mismatches across modular sub-routers, and connection dropping from unhandled task panics. 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: Relying on untyped Extension injection and unhandled panics instead of FromRef State and CatchPanicLayer composition. 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 DriftRelying on untyped Extension injection and unhandled panics instead of FromRef State and CatchPanicLayer composition.Critical
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> with FromRef implementations instead of axum::Extension for compile-time verified 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 ALWAYS register tower_http

Engineers MUST ALWAYS register tower_http::catch_panic::CatchPanicLayer inside the outermost TraceLayer to guarantee that panics are converted into 500 Internal Server Error responses and logged.

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 compose Tower layers via ServiceBuilder, placing TraceLayer outermost, followed by CatchPanicLayer, TimeoutLayer, and finally domain-specific authorization/rate-limiting middlewares.

Engineers MUST compose Tower layers via ServiceBuilder, placing TraceLayer outermost, followed by CatchPanicLayer, TimeoutLayer, and finally domain-specific authorization/rate-limiting middlewares.

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 NOT allow sub-routers to leak monolithic state dependencies

Engineers MUST NOT allow sub-routers to leak monolithic state dependencies; sub-routers MUST declare their own minimal state parameter S and leverage S: FromRef<AppState>.

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 wrap fallible extractors (Json, Query, Path) with custom AppRejection types to ensure predictable, structured RFC 7807 problem details rather than exposing raw Axum rejection strings.

Engineers MUST wrap fallible extractors (Json, Query, Path) with custom AppRejection types to ensure predictable, structured RFC 7807 problem details rather than exposing raw Axum rejection strings.

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

Mandates compile-time type-safe FromRef sub-state extraction and deterministic Tower ServiceBuilder ordering in Axum 0.8 services. Prevents runtime extractor rejections, state type mismatches across modular sub-routers, and connection dropping from unhandled task panics. 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 (Relying on untyped Extension injection and unhandled panics instead of FromRef State and CatchPanicLayer composition.) 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