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

Axum 0.8 Type-Safe State Subtyping & Tower Panic-Resilient Middleware Composition

Enforces Axum 0.8 compile-time type-safe state sharing using FromRef sub-states instead of dynamic Extensions, alongside resilient Tower middleware stacks. Mandates CatchPanicLayer boundary encapsulation, deterministic middleware execution ordering, and total elimination of unhandled extractor panics through explicit IntoResponse rejection handling.

Prohibited Anti-Pattern: Relying on dynamic Extension extraction for shared state and omitting CatchPanicLayer or FromRef sub-state delegation in Axum routers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Type-Safe State Subtyping & Tower Panic-Resilient Middleware Composition - Enforces Axum 0.8 compile-time type-safe state sharing using FromRef sub-states instead of dynamic Extensions, alongside resilient Tower middleware stacks. Mandates CatchPanicLayer boundary encapsulation, deterministic middleware execution ordering, and total elimination of unhandled extractor panics through explicit IntoResponse rejection handling.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rust-axum-state-tower-resilience-guardrail"
---

# Axum 0.8 Type-Safe State Subtyping & Tower Panic-Resilient Middleware Composition

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Relying on dynamic Extension extraction for shared state and omitting CatchPanicLayer or FromRef sub-state delegation in Axum routers

## System Constraints
You are a Principal Rust Systems Architect enforcing Axum 0.8 and Tower service standards. Mandate compile-time type safety via axum::extract::State and FromRef, strict middleware evaluation ordering via tower::ServiceBuilder, and deterministic panic isolation across all HTTP boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` paired with `axum::extract::FromRef` implementations for modular sub-state extraction instead of `axum::Extension` to ensure compile-time dependency verification.
- Engineers MUST wrap all public Axum routers with `tower_http::catch_panic::CatchPanicLayer` before converting to an incoming listener service to prevent thread panics from dropping TCP connections silently.
- Engineers MUST compose Tower middleware layers via `tower::ServiceBuilder` where outer layers execute first on incoming requests: `TraceLayer` -> `CatchPanicLayer` -> `TimeoutLayer` -> `ConcurrencyLimitLayer`.
- Custom extractors MUST ALWAYS implement `FromRequest` or `FromRequestParts` with a concrete `Rejection` type that implements `IntoResponse`; panicking or unhandled `.unwrap()` calls inside extractors are strictly forbidden.
- Sub-routers MUST NOT define independent monolithic states; they MUST extract modular sub-states using the outer router's state via `FromRef` to maintain clean separation of concerns and testability.

## Bad vs Good Implementations
### Dynamic Extension Extraction and Fragile Tower Layering (Anti-Pattern)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension defers state dependency checking to runtime, yielding a 500 error if omitted. Raw unwrapping without CatchPanicLayer causes abrupt TCP connection drops and bypasses structured telemetry.
```rust
use axum::{routing::get, Extension, Router, Json};
use std::sync::Arc;
use tower_http::trace::TraceLayer;

struct AppState {
    db_pool: String,
}

// ANTI-PATTERN: Fails at runtime if Extension is missing from Router.
// No panic layer, no FromRef sub-state, and unwrapping inside handler causes connection drops.
async fn get_user(Extension(state): Extension<Arc<AppState>>) -> Json<String> {
    let val = state.db_pool.parse::<i32>().unwrap(); // Unhandled panic resets connection
    Json(format!("User: {}", val))
}

pub fn build_router(state: Arc<AppState>) -> Router {
    Router::new()
        .route("/user", get(get_user))
        .layer(TraceLayer::new_for_http())
        .layer(Extension(state)) // Dynamic runtime injection without compile-time guarantees
}
```

#### Production Standard (Correct)
> **Standard**: Leverages Axum 0.8 `State` combined with `FromRef` for sub-states, ensuring compile-time safety. Employs `CatchPanicLayer` and explicit `IntoResponse` error typing to eliminate dropped connections and unhandled runtime panics.
```rust
use axum::{
    extract::{FromRef, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Json,
    Router,
};
use std::sync::Arc;
use tower::ServiceBuilder;
use tower_http::{
    catch_panic::CatchPanicLayer,
    trace::TraceLayer,
};

#[derive(Clone)]
pub struct DatabaseConfig {
    pub pool_id: Arc<str>,
}

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

// Invariant: Implement FromRef for modular sub-state extraction
impl FromRef<AppState> for DatabaseConfig {
    fn from_ref(app_state: &AppState) -> Self {
        app_state.db.clone()
    }
}

#[derive(Debug)]
pub enum AppError {
    InvalidFormat,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, msg) = match self {
            AppError::InvalidFormat => (StatusCode::BAD_REQUEST, "Invalid state format"),
        };
        (status, Json(serde_json::json!({ "error": msg }))).into_response()
    }
}

// Type-safe handler extracting only the sub-state it requires
async fn get_user(State(db): State<DatabaseConfig>) -> Result<Json<serde_json::Value>, AppError> {
    let _parsed = db.pool_id.parse::<i32>().map_err(|_| AppError::InvalidFormat)?;
    Ok(Json(serde_json::json!({ "status": "connected" })))
}

pub fn build_router(state: AppState) -> Router {
    // Invariant: CatchPanicLayer ensures panics are caught and serialized into 500 responses
    let middleware = ServiceBuilder::new()
        .layer(TraceLayer::new_for_http())
        .layer(CatchPanicLayer::new());

    Router::new()
        .route("/user", get(get_user))
        .with_state(state)
        .layer(middleware)
}
```

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 Subtyping & Tower Panic-Resilient Middleware Composition

Axum 0.8 Type-Safe State Subtyping & Tower Panic-Resilient Middleware Composition defines an industrial-grade behavioral standard for backend engineering. Enforces Axum 0.8 compile-time type-safe state sharing using FromRef sub-states instead of dynamic Extensions, alongside resilient Tower middleware stacks. Mandates CatchPanicLayer boundary encapsulation, deterministic middleware execution ordering, and total elimination of unhandled extractor panics through explicit IntoResponse rejection handling. 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 dynamic Extension extraction for shared state and omitting CatchPanicLayer or FromRef sub-state delegation in Axum routers 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 dynamic Extension extraction for shared state and omitting CatchPanicLayer or FromRef sub-state delegation in Axum routersCritical
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` paired with `axum::extract::FromRef` implementations for modular sub-state extraction instead of `axum::Extension` to ensure compile-time dependency verification.

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

Engineers MUST wrap all public Axum routers with `tower_http::catch_panic::CatchPanicLayer` before converting to an incoming listener service to prevent thread panics from dropping TCP connections silently.

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 middleware layers via `tower

Engineers MUST compose Tower middleware layers via `tower::ServiceBuilder` where outer layers execute first on incoming requests: `TraceLayer` -> `CatchPanicLayer` -> `TimeoutLayer` -> `ConcurrencyLimitLayer`.

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

Custom extractors MUST ALWAYS implement `FromRequest` or `FromRequestParts` with a concrete `Rejection` type that implements `IntoResponse`

Custom extractors MUST ALWAYS implement `FromRequest` or `FromRequestParts` with a concrete `Rejection` type that implements `IntoResponse`; panicking or unhandled `.unwrap()` calls inside extractors are strictly forbidden.

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

Sub-routers MUST NOT define independent monolithic states

Sub-routers MUST NOT define independent monolithic states; they MUST extract modular sub-states using the outer router's state via `FromRef` to maintain clean separation of concerns and testability.

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 Subtyping & Tower Panic-Resilient Middleware Composition critical for AI coding assistants?

Enforces Axum 0.8 compile-time type-safe state sharing using FromRef sub-states instead of dynamic Extensions, alongside resilient Tower middleware stacks. Mandates CatchPanicLayer boundary encapsulation, deterministic middleware execution ordering, and total elimination of unhandled extractor panics through explicit IntoResponse rejection handling. 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 dynamic Extension extraction for shared state and omitting CatchPanicLayer or FromRef sub-state delegation in Axum routers) 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