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

Axum 0.8 Type-Safe State Architecture, Substates, and Tower Middleware Resilience

Enforces compile-time type-safe dependency injection via Axum 0.8 State and FromRef substate extraction, preventing runtime type misses from Extension. Mandates fault-tolerant Tower Service layers featuring CatchPanicLayer and custom rejection types to eliminate unhandled panics and silent connection drops.

Prohibited Anti-Pattern: Dynamic runtime Extension extraction and unhandled panic propagation without Tower CatchPanic layers.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Type-Safe State Architecture, Substates, and Tower Middleware Resilience - Enforces compile-time type-safe dependency injection via Axum 0.8 State and FromRef substate extraction, preventing runtime type misses from Extension. Mandates fault-tolerant Tower Service layers featuring CatchPanicLayer and custom rejection types to eliminate unhandled panics and silent connection drops.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-state-tower-resilience-standard"
---

# Axum 0.8 Type-Safe State Architecture, Substates, and Tower Middleware Resilience

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Dynamic runtime Extension extraction and unhandled panic propagation without Tower CatchPanic layers.

## System Constraints
You are a Principal Backend Engineer enforcing Axum 0.8 idioms, Tower service stack ordering, and compile-time state guarantees. Mandate type-safe State/FromRef extractors over Extension, explicit error response types, and resilient Tower middleware layers.

## Strict Guidelines
- Engineers MUST ALWAYS use axum::extract::State with the FromRef trait for modular substate extraction instead of monolithic state coupling or untyped Extension<T>.
- Engineers MUST NOT use Extension for core infrastructural singletons (pools, clients, config) as it bypasses Axum 0.8 compile-time type checking and panics at runtime on missing dependencies.
- Code MUST wrap edge routing in tower_http::catch_panic::CatchPanicLayer with a designated panic handler converting panics to structured HTTP 500 JSON responses.
- Services MUST order Tower middleware precisely: tracing and panic recovery MUST wrap outer layers, while route-specific state or authorization MUST be placed inside route_layer.
- Handlers MUST NEVER panic via unwrap() or expect(); all fallible operations must propagate errors via an AppResult<T> type implementing IntoResponse.
- State structs MUST implement Clone, Send, Sync, and 'static; heavy components (e.g., connection pools, caches) MUST be wrapped in Arc unless natively ref-counted.

## Bad vs Good Implementations
### State Extraction and Tower Panic Recovery Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension<T> delegates type checking to runtime; missing extensions result in runtime panics. Handlers lack structured error propagation, and the Router lacks a Tower CatchPanicLayer, resulting in unhandled panics, closed sockets, and opaque failure states.
```rust
use axum::{routing::get, Extension, Router};
use std::sync::Arc;

struct DatabasePool;

// ANTI-PATTERN: Using Extension lacks compile-time verification.
// If Extension is omitted from Router, this panics at runtime with a 500.
async fn handler(Extension(db): Extension<Arc<DatabasePool>>) -> &'static str {
    // ANTI-PATTERN: Explicit panic inside handler will tear down the task or drop
    // the HTTP connection without a structured response if no panic layer is present.
    if false {
        panic!("database failure");
    }
    "ok"
}

pub fn app() -> Router {
    Router::new()
        .route("/data", get(handler))
        // Missing State binding and missing CatchPanicLayer
}
```

#### Production Standard (Correct)
> **Standard**: AppState and FromRef guarantee compile-time type verification for all extractors. CatchPanicLayer captures unhandled panics and transforms them into standard JSON responses, and AppError converts operational errors into clean HTTP responses.
```rust
use axum::{
    extract::{FromRef, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Json,
    Router,
};
use serde_json::json;
use std::sync::Arc;
use tower_http::catch_panic::CatchPanicLayer;

#[derive(Clone)]
pub struct AppState {
    pub db_pool: Arc<DatabasePool>,
    pub api_token: String,
}

pub struct DatabasePool;

// Substate extraction via FromRef decouples handlers from root AppState
impl FromRef<AppState> for Arc<DatabasePool> {
    fn from_ref(state: &AppState) -> Self {
        state.db_pool.clone()
    }
}

async fn handler(State(db): State<Arc<DatabasePool>>) -> Result<Json<serde_json::Value>, AppError> {
    // Typed state is strictly verified at compile-time
    Ok(Json(json!({ "status": "connected" })))
}

// Fallback error response prevents unhandled 500 crashes
pub struct AppError(anyhow::Error);

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({ "error": self.0.to_string() })),
        )
            .into_response()
    }
}

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".to_string()
    };
    
    (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "panic": details }))).into_response()
}

pub fn build_app(state: AppState) -> Router {
    Router::new()
        .route("/data", get(handler))
        .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 Architecture, Substates, and Tower Middleware Resilience

Axum 0.8 Type-Safe State Architecture, Substates, and Tower Middleware Resilience defines an industrial-grade behavioral standard for backend engineering. Enforces compile-time type-safe dependency injection via Axum 0.8 State and FromRef substate extraction, preventing runtime type misses from Extension. Mandates fault-tolerant Tower Service layers featuring CatchPanicLayer and custom rejection types to eliminate unhandled panics and silent connection 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: Dynamic runtime Extension extraction and unhandled panic propagation without Tower CatchPanic layers. 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 extraction and unhandled panic propagation without Tower CatchPanic layers.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 with the FromRef trait for modular substate extraction instead of monolithic state coupling or untyped Extension<T>.

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 NOT use Extension for core infrastructural singletons (pools, clients, config) as it bypasses Axum 0.8 compile-time type checking and panics at runtime on missing dependencies.

Engineers MUST NOT use Extension for core infrastructural singletons (pools, clients, config) as it bypasses Axum 0.8 compile-time type checking and panics at runtime on missing 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.
3

Code MUST wrap edge routing in tower_http

Code MUST wrap edge routing in tower_http::catch_panic::CatchPanicLayer with a designated panic handler converting panics to structured HTTP 500 JSON responses.

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

Services MUST order Tower middleware precisely

Services MUST order Tower middleware precisely: tracing and panic recovery MUST wrap outer layers, while route-specific state or authorization MUST be placed inside route_layer.

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

Handlers MUST NEVER panic via unwrap() or expect()

Handlers MUST NEVER panic via unwrap() or expect(); all fallible operations must propagate errors via an AppResult<T> type implementing 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.
6

State structs MUST implement Clone, Send, Sync, and 'static

State structs MUST implement Clone, Send, Sync, and 'static; heavy components (e.g., connection pools, caches) MUST be wrapped in Arc unless natively ref-counted.

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 Architecture, Substates, and Tower Middleware Resilience critical for AI coding assistants?

Enforces compile-time type-safe dependency injection via Axum 0.8 State and FromRef substate extraction, preventing runtime type misses from Extension. Mandates fault-tolerant Tower Service layers featuring CatchPanicLayer and custom rejection types to eliminate unhandled panics and silent connection 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 (Dynamic runtime Extension extraction and unhandled panic propagation without Tower CatchPanic layers.) 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