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

Axum 0.8 Type-Safe State Extractors & Tower Service Composition Guardrail

Enforces strict type safety and compile-time validation for State extractors alongside modular sub-state derivation using FromRef in Axum 0.8. Mandates explicit CatchPanic layers, proper Tower service layer ordering, and zero unhandled rejections to prevent silent connection termination or service starvation under panic conditions.

Prohibited Anti-Pattern: Untyped Extensions, Missing FromRef Sub-state Derivation, and CatchPanic-less Tower Stacks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Type-Safe State Extractors & Tower Service Composition Guardrail - Enforces strict type safety and compile-time validation for State extractors alongside modular sub-state derivation using FromRef in Axum 0.8. Mandates explicit CatchPanic layers, proper Tower service layer ordering, and zero unhandled rejections to prevent silent connection termination or service starvation under panic conditions.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-08-state-tower-panic-resilience-guardrail"
---

# Axum 0.8 Type-Safe State Extractors & Tower Service Composition Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Untyped Extensions, Missing FromRef Sub-state Derivation, and CatchPanic-less Tower Stacks

## System Constraints
You are a Principal Engineer enforcing Rust Axum 0.8 State Extractors & Tower Service. Mandate invariants regarding strict static type safety via State<T> and FromRef, safe Tower middleware ordering with CatchPanicLayer, and zero unhandled panic rejections.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` instead of dynamic `Extension` for application context and shared dependencies to enforce compile-time verification.
- Engineers MUST implement `axum::extract::FromRef<AppState>` on modular sub-state types when decomposing multi-module routers rather than passing the monolithic `AppState` everywhere.
- Engineers MUST ALWAYS wrap the outermost router with `tower_http::catch_panic::CatchPanicLayer` configured with a custom panic handler returning an HTTP 500 status code.
- Services MUST place `CatchPanicLayer` before `TraceLayer` and timeout middleware to guarantee traces capture panics and prevent unhandled thread unwinds from dropping client sockets abruptly.
- Engineers MUST NEVER use `std::sync::Mutex` across `.await` points inside Axum handlers; use `tokio::sync::Mutex` or immutable/atomic state architectures to prevent async runtime executor deadlocks.

## Bad vs Good Implementations
### Axum 0.8 Type-Safe State Composition & Panic Boundary Enforcement

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension bypasses Axum's compile-time router state checking, leading to runtime 500 errors if missing. Furthermore, panics inside the handler trigger uncontrolled stack unwinding without an HTTP response, dropping client TCP connections.
```rust
use axum::{routing::get, Extension, Router};
use std::sync::Arc;

struct AppState {
    db_pool: String,
}

// ANTI-PATTERN: Handler uses Extension which fails at runtime if omitted.
// Missing CatchPanicLayer means an unwinding panic abruptly drops the TCP connection.
async fn get_user(Extension(state): Extension<Arc<AppState>>) -> String {
    if state.db_pool.is_empty() {
        panic!("Database connection dropped!");
    }
    format!("Connected to: {}", state.db_pool)
}

pub fn app() -> Router {
    Router::new()
        .route("/user", get(get_user))
        // No CatchPanicLayer or State registered
}
```

#### Production Standard (Correct)
> **Standard**: Employs Axum 0.8 State<T> with FromRef derivation for modular, type-checked sub-state access. Wraps the middleware stack with CatchPanicLayer using a custom response handler to guarantee deterministic HTTP 500 responses without unhandled connection termination.
```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, trace::TraceLayer};

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

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

// Sub-state extraction via FromRef enables modular, decoupled routers
impl FromRef<AppState> for DatabaseConfig {
    fn from_ref(state: &AppState) -> Self {
        state.db.clone()
    }
}

async fn get_user(State(db): State<DatabaseConfig>) -> impl IntoResponse {
    (StatusCode::OK, format!("Connected to: {}", db.pool_name))
}

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

pub fn build_app(state: AppState) -> Router {
    Router::new()
        .route("/user", get(get_user))
        .with_state(state)
        .layer(
            ServiceBuilder::new()
                .layer(TraceLayer::new_for_http())
                .layer(CatchPanicLayer::custom(handle_panic)),
        )
}
```

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 Extractors & Tower Service Composition Guardrail

Axum 0.8 Type-Safe State Extractors & Tower Service Composition Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict type safety and compile-time validation for State extractors alongside modular sub-state derivation using FromRef in Axum 0.8. Mandates explicit CatchPanic layers, proper Tower service layer ordering, and zero unhandled rejections to prevent silent connection termination or service starvation under panic conditions. 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 Extensions, Missing FromRef Sub-state Derivation, and CatchPanic-less Tower Stacks 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 Extensions, Missing FromRef Sub-state Derivation, and CatchPanic-less Tower StacksCritical
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 dynamic `Extension` for application context and shared dependencies to enforce compile-time 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 implement `axum

Engineers MUST implement `axum::extract::FromRef<AppState>` on modular sub-state types when decomposing multi-module routers rather than passing the monolithic `AppState` everywhere.

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 wrap the outermost router with `tower_http

Engineers MUST ALWAYS wrap the outermost router with `tower_http::catch_panic::CatchPanicLayer` configured with a custom panic handler returning an HTTP 500 status code.

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 place `CatchPanicLayer` before `TraceLayer` and timeout middleware to guarantee traces capture panics and prevent unhandled thread unwinds from dropping client sockets abruptly.

Services MUST place `CatchPanicLayer` before `TraceLayer` and timeout middleware to guarantee traces capture panics and prevent unhandled thread unwinds from dropping client sockets abruptly.

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 NEVER use `std

Engineers MUST NEVER use `std::sync::Mutex` across `.await` points inside Axum handlers; use `tokio::sync::Mutex` or immutable/atomic state architectures to prevent async runtime executor deadlocks.

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 Extractors & Tower Service Composition Guardrail critical for AI coding assistants?

Enforces strict type safety and compile-time validation for State extractors alongside modular sub-state derivation using FromRef in Axum 0.8. Mandates explicit CatchPanic layers, proper Tower service layer ordering, and zero unhandled rejections to prevent silent connection termination or service starvation under panic conditions. 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 Extensions, Missing FromRef Sub-state Derivation, and CatchPanic-less Tower Stacks) 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